From 0f709f184c60c6428f4a818a57fc8e96254241d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Xu=C3=A2n=20Minh?= Date: Tue, 1 Dec 2026 22:54:53 +0700 Subject: [PATCH 1/2] feat(backend): implement class assessments, mentor timesheet, KPI policies and curriculum package import --- .../Helpers/NotificationSemanticResolver.cs | 46 +- .../IServices/IClassQuizService.cs | 16 + .../ICurriculumPackageImportService.cs | 19 + .../IServices/IMentorKpiDashboardService.cs | 41 + .../IMentorLearnerSkillProfileService.cs | 4 + .../IServices/IPracticeTestService.cs | 12 + .../IServices/IStudyCourseService.cs | 13 +- RikiPath.Application/IUnitOfWork.cs | 2 + .../CreateMentorGroupPolicyRequest.cs | 20 +- .../Requests/StudyCourses/CourseRequests.cs | 13 +- .../Responses/AdminDashboardResponse.cs | 1 - .../ClassQuizzes/ClassQuizResponses.cs | 128 + .../Content/CurriculumPackageDtos.cs | 162 + .../Responses/Homework/HomeworkResponses.cs | 4 +- .../MentorKpi/MentorKpiDashboardResponses.cs | 217 + .../MentorLearnerSkillProfileResponse.cs | 109 +- .../CourseFinalAssessmentResponses.cs | 39 + .../PlacementTests/PlacementTestResponses.cs | 14 + .../Services/AdaptiveSkillProfileService.cs | 2 +- .../Services/AdminDashboardService.cs | 3 - .../Services/ClassQuizService.cs | 633 + .../Services/ClassRecordLock.cs | 46 + .../Services/ClassSessionLifecycleService.cs | 5 +- .../Services/ContentApprovalService.cs | 73 +- .../Services/CourseCompetencyPolicy.cs | 134 + .../Services/HomeworkGradingService.cs | 10 +- .../Services/HomeworkService.cs | 8 +- .../Services/ListeningAudioFilePolicy.cs | 21 + .../Services/ManualContentService.cs | 18 +- .../MentorLearnerSkillProfileService.cs | 731 +- .../Services/PracticeTestService.ClassQuiz.cs | 253 + .../PracticeTestService.CourseFinal.cs | 248 + .../Services/PracticeTestService.cs | 896 +- .../Services/RetakeEligibilityEvaluator.cs | 85 + .../Services/SidebarCounterService.cs | 11 - .../Services/StudyCohortFeedbackService.cs | 52 +- .../Services/StudyCohortLifecycleService.cs | 17 +- ...udyCohortMentorAssignmentHistoryService.cs | 33 + .../StudyCohortMentorReplacementService.cs | 251 - .../Services/StudyCohortService.cs | 4 +- .../Services/StudyCohortTransferService.cs | 499 - .../Services/StudyCourseService.cs | 225 +- .../Services/StudyCourseSharedHelpers.cs | 53 + RikiPath.Domain/AppSettings.cs | 9 - RikiPath.Domain/CourseRetakePolicy.cs | 178 +- RikiPath.Domain/Entities/ClassQuiz.cs | 51 + RikiPath.Domain/Entities/MentorGroupPolicy.cs | 13 +- RikiPath.Domain/Entities/MentorKpiPolicy.cs | 79 + RikiPath.Domain/Enums/AttemptKind.cs | 8 +- RikiPath.Domain/Enums/ImportEntityType.cs | 1 + RikiPath.Infrastructure/AppDbContext.cs | 106 + .../Configuration/ClassQuizConfig.cs | 50 + .../Configuration/MentorGroupPolicyConfig.cs | 4 + .../Configuration/MentorKpiPolicyConfig.cs | 69 + ...20261201045335_AddClassQuizzes.Designer.cs | 14429 +++++++++++++++ .../20261201045335_AddClassQuizzes.cs | 154 + ...dRetakeSupportPolicyThresholds.Designer.cs | 14444 +++++++++++++++ ...082900_AddRetakeSupportPolicyThresholds.cs | 58 + ...iPolicyAndTimesheetAdjustments.Designer.cs | 14635 ++++++++++++++++ ...dMentorKpiPolicyAndTimesheetAdjustments.cs | 129 + .../Migrations/AppDbContextModelSnapshot.cs | 395 + .../Repositories/MockTestAttemptRepository.cs | 2 +- .../Services/AwsAudioFileStorageService.cs | 2 +- .../CohortEnrollmentDeadlineService.cs | 4 +- .../ContentAudioTranscriptionService.cs | 18 +- .../CurriculumPackageImportService.cs | 2122 +++ .../Services/MentorGroupPolicyService.cs | 72 +- .../Services/MentorKpiDashboardService.cs | 620 + .../Services/MentorKpiPolicyService.cs | 184 + .../Services/MentorOutboxDispatcherService.cs | 2 +- .../Services/StudyCohortLifecycleWorker.cs | 2 +- RikiPath.Infrastructure/UnitOfWork.cs | 4 + .../Controllers/ClassQuizzesController.cs | 87 + .../Controllers/ContentImportController.cs | 83 +- .../Controllers/FileStorageController.cs | 2 +- .../Controllers/HomeworkController.cs | 14 + .../LearnerCourseCompetencyController.cs | 42 + .../MentorKpiDashboardController.cs | 72 + .../Controllers/StudyCoursesController.cs | 51 +- .../ClassRecordWriteAttribute.cs | 50 + RikiPath.WebApi/Services/ImportAudioFiles.cs | 12 +- .../dev-stage5-class-quiz-demo-cleanup.sql | 17 + seed-data/dev-stage5-class-quiz-demo.sql | 123 + .../dev-stage5-competency-demo-cleanup.sql | 32 + seed-data/dev-stage5-competency-demo.sql | 254 + 85 files changed, 51938 insertions(+), 1916 deletions(-) create mode 100644 RikiPath.Application/IServices/IClassQuizService.cs create mode 100644 RikiPath.Application/IServices/ICurriculumPackageImportService.cs create mode 100644 RikiPath.Application/IServices/IMentorKpiDashboardService.cs create mode 100644 RikiPath.Application/Responses/ClassQuizzes/ClassQuizResponses.cs create mode 100644 RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs create mode 100644 RikiPath.Application/Responses/MentorKpi/MentorKpiDashboardResponses.cs create mode 100644 RikiPath.Application/Responses/PlacementTests/CourseFinalAssessmentResponses.cs create mode 100644 RikiPath.Application/Services/ClassQuizService.cs create mode 100644 RikiPath.Application/Services/ClassRecordLock.cs create mode 100644 RikiPath.Application/Services/CourseCompetencyPolicy.cs create mode 100644 RikiPath.Application/Services/PracticeTestService.ClassQuiz.cs create mode 100644 RikiPath.Application/Services/PracticeTestService.CourseFinal.cs create mode 100644 RikiPath.Application/Services/RetakeEligibilityEvaluator.cs create mode 100644 RikiPath.Application/Services/StudyCohortMentorAssignmentHistoryService.cs delete mode 100644 RikiPath.Application/Services/StudyCohortMentorReplacementService.cs delete mode 100644 RikiPath.Application/Services/StudyCohortTransferService.cs create mode 100644 RikiPath.Application/Services/StudyCourseSharedHelpers.cs create mode 100644 RikiPath.Domain/Entities/ClassQuiz.cs create mode 100644 RikiPath.Domain/Entities/MentorKpiPolicy.cs create mode 100644 RikiPath.Infrastructure/Configuration/ClassQuizConfig.cs create mode 100644 RikiPath.Infrastructure/Configuration/MentorKpiPolicyConfig.cs create mode 100644 RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.Designer.cs create mode 100644 RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.cs create mode 100644 RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.Designer.cs create mode 100644 RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.cs create mode 100644 RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.Designer.cs create mode 100644 RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.cs create mode 100644 RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs create mode 100644 RikiPath.Infrastructure/Services/MentorKpiDashboardService.cs create mode 100644 RikiPath.Infrastructure/Services/MentorKpiPolicyService.cs create mode 100644 RikiPath.WebApi/Controllers/ClassQuizzesController.cs create mode 100644 RikiPath.WebApi/Controllers/LearnerCourseCompetencyController.cs create mode 100644 RikiPath.WebApi/Controllers/MentorKpiDashboardController.cs create mode 100644 RikiPath.WebApi/Infrastructure/ClassRecordWriteAttribute.cs create mode 100644 seed-data/dev-stage5-class-quiz-demo-cleanup.sql create mode 100644 seed-data/dev-stage5-class-quiz-demo.sql create mode 100644 seed-data/dev-stage5-competency-demo-cleanup.sql create mode 100644 seed-data/dev-stage5-competency-demo.sql diff --git a/RikiPath.Application/Helpers/NotificationSemanticResolver.cs b/RikiPath.Application/Helpers/NotificationSemanticResolver.cs index c58a560..38ccd53 100644 --- a/RikiPath.Application/Helpers/NotificationSemanticResolver.cs +++ b/RikiPath.Application/Helpers/NotificationSemanticResolver.cs @@ -47,7 +47,6 @@ private sealed class LiveEntitySnapshot public Dictionary CourseStates { get; } = []; public Dictionary MentorVerifications { get; } = []; public Dictionary ComplaintStates { get; } = []; - public Dictionary TransferStatuses { get; } = []; public Dictionary CohortScheduleStatuses { get; } = []; public Dictionary PendingCourseScheduleRequestsByCourse { get; } = []; public int PendingPaymentReviewsCount { get; set; } @@ -72,7 +71,6 @@ private sealed class LiveEntitySnapshot "CohortComplaintInformationRequested", "CohortComplaintMentorRequested", "LearningFeedbackPending", - "CohortTransfer", "CohortScheduleRequest", "CohortPaymentReconciliation", "CourseScheduleRequest", @@ -639,37 +637,13 @@ private static SemanticResolution ResolveCore( return new SemanticResolution(CategoryInfo, false, null); } - // 9. Cohort Transfer & Roster + // Legacy transfer notifications remain visible as historical, non-actionable records. if (string.Equals(type, "CohortTransfer", StringComparison.OrdinalIgnoreCase)) { var transferId = ExtractQueryInt(link, "transferRequestId"); - if (linkLower.StartsWith("/admin/", StringComparison.Ordinal) && transferId.HasValue) - { - if (snapshot is not null) - { - if (!snapshot.TransferStatuses.TryGetValue(transferId.Value, out var status)) - { - return new SemanticResolution( - CategoryNeutral, false, ActionUnavailable, - "CohortTransfer", transferId.Value, "NotFound", "Không còn khả dụng", false); - } - - return string.Equals(status, CohortTransferRequest.Pending, StringComparison.Ordinal) - ? new SemanticResolution( - CategoryWarning, true, ActionPending, - "CohortTransfer", transferId.Value, status, "Chờ duyệt", true) - : new SemanticResolution( - CategoryNeutral, false, ActionResolved, - "CohortTransfer", transferId.Value, status, "Đã xử lý", true); - } - - return new SemanticResolution(CategoryWarning, true, ActionPending, "CohortTransfer", transferId.Value, CohortTransferRequest.Pending, "Chờ duyệt", true); - } - if (titleLower.Contains("từ chối", StringComparison.Ordinal) || msgLower.Contains("chưa được chấp thuận", StringComparison.Ordinal)) - return new SemanticResolution(CategoryDanger, false, null); - if (titleLower.Contains("được chuyển", StringComparison.Ordinal) || titleLower.Contains("phê duyệt", StringComparison.Ordinal) || titleLower.Contains("thành công", StringComparison.Ordinal)) - return new SemanticResolution(CategorySuccess, false, null); - return new SemanticResolution(CategoryInfo, false, null); + return new SemanticResolution( + CategoryNeutral, false, ActionUnavailable, + "CohortTransfer", transferId, "Retired", "Không còn khả dụng", false); } if (string.Equals(type, "CohortRoster", StringComparison.OrdinalIgnoreCase) @@ -1040,7 +1014,6 @@ private static async Task LoadLiveSnapshotAsync( var mentorIds = new HashSet(); var complaintIds = new HashSet(); var feedbackIds = new HashSet(); - var transferIds = new HashSet(); var cohortScheduleIds = new HashSet(); var homeworkAssignmentIds = new HashSet(); var homeworkGroupKeys = new HashSet(); @@ -1065,7 +1038,6 @@ private static async Task LoadLiveSnapshotAsync( TryAdd(proposalIds, ExtractQueryInt(link, "proposalId")); TryAdd(complaintIds, ExtractQueryInt(link, "complaintId")); if (type == "LearningFeedbackPending") TryAdd(feedbackIds, ExtractQueryInt(link, "feedbackId")); - TryAdd(transferIds, ExtractQueryInt(link, "transferRequestId")); TryAdd(cohortScheduleIds, ExtractQueryInt(link, "cohortScheduleRequestId")); TryAdd(mentorIds, ExtractQueryInt(link, "mentorId")); @@ -1231,16 +1203,6 @@ private static async Task LoadLiveSnapshotAsync( snapshot.ComplaintStates[r.Id] = (r.Status, r.MentorResponded, r.IsPaymentCategory); } - if (transferIds.Count > 0) - { - var rows = await unitOfWork.CohortTransferRequests.Query().AsNoTracking() - .Where(t => transferIds.Contains(t.Id)) - .Select(t => new { t.Id, t.Status }) - .ToListAsync(ct); - foreach (var r in rows) - snapshot.TransferStatuses[r.Id] = r.Status; - } - if (cohortScheduleIds.Count > 0) { var rows = await unitOfWork.CohortScheduleRequests.Query().AsNoTracking() diff --git a/RikiPath.Application/IServices/IClassQuizService.cs b/RikiPath.Application/IServices/IClassQuizService.cs new file mode 100644 index 0000000..b4df68f --- /dev/null +++ b/RikiPath.Application/IServices/IClassQuizService.cs @@ -0,0 +1,16 @@ +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.ClassQuizzes; + +namespace RikiPath.Application.IServices; + +/// In-class skill quizzes (Stage 5): Mentor builds and publishes, Learner takes them on the assessment engine. +public interface IClassQuizService +{ + Task> GetBankAsync(int cohortId, CancellationToken cancellationToken = default); + Task> CreateAsync(int cohortId, CreateClassQuizRequest request, CancellationToken cancellationToken = default); + Task>> GetMentorQuizzesAsync(int? cohortId, CancellationToken cancellationToken = default); + Task> GetMentorQuizDetailAsync(int quizId, CancellationToken cancellationToken = default); + Task> GetMentorLearnerResultAsync(int assignmentId, CancellationToken cancellationToken = default); + Task>> GetLearnerQuizzesAsync(int? cohortId, CancellationToken cancellationToken = default); + Task> GetLearnerResultAsync(int assignmentId, CancellationToken cancellationToken = default); +} diff --git a/RikiPath.Application/IServices/ICurriculumPackageImportService.cs b/RikiPath.Application/IServices/ICurriculumPackageImportService.cs new file mode 100644 index 0000000..4beb0b1 --- /dev/null +++ b/RikiPath.Application/IServices/ICurriculumPackageImportService.cs @@ -0,0 +1,19 @@ +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.Content; + +namespace RikiPath.Application.IServices +{ + public interface ICurriculumPackageImportService + { + Task> GetInventoryAsync(CancellationToken cancellationToken); + + Task> PreviewAsync( + CurriculumPackagePreviewRequest request, + CancellationToken cancellationToken); + + Task> ConfirmAsync( + CurriculumPackageConfirmRequest request, + int actorUserId, + CancellationToken cancellationToken); + } +} diff --git a/RikiPath.Application/IServices/IMentorKpiDashboardService.cs b/RikiPath.Application/IServices/IMentorKpiDashboardService.cs new file mode 100644 index 0000000..787cbe9 --- /dev/null +++ b/RikiPath.Application/IServices/IMentorKpiDashboardService.cs @@ -0,0 +1,41 @@ +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.MentorKpi; + +namespace RikiPath.Application.IServices; + +/// Chính sách chấm công & KPI (phiên bản theo tháng, độc lập với Chính sách lớp học). +public interface IMentorKpiPolicyService +{ + Task> GetCurrentAsync(CancellationToken ct = default); + Task>> GetHistoryAsync(CancellationToken ct = default); + Task> PublishAsync(PublishMentorKpiPolicyRequest request, CancellationToken ct = default); + Task> DeleteAsync(int id, CancellationToken ct = default); +} + +/// +/// Một nguồn tính duy nhất cho Chấm công & KPI Giáo viên: Mentor (cá nhân), Admin (chi tiết từng Giáo viên) và +/// tổng quan toàn trung tâm đều dùng cùng bộ tính toán. +/// +public interface IMentorKpiDashboardService +{ + Task> GetMyDashboardAsync(string? month, string? level, int? cohortId, CancellationToken ct = default); + Task> GetMentorDashboardAsync(int mentorId, string? month, string? level, int? cohortId, CancellationToken ct = default); + Task> GetOverviewAsync(string? month, string? level, CancellationToken ct = default); + Task> ReconcileAsync(int mentorId, int sessionId, ReconcileTimesheetRequest request, CancellationToken ct = default); +} + +public sealed record PublishMentorKpiPolicyRequest( + int ExpectedLatestVersion, + string EffectiveFromMonth, + decimal MinimumPresencePercent, + decimal TeachingCompletionTargetPercent, + int HomeworkMinimumCount, + int HomeworkPerSessionCount, + decimal GradingCompletionTargetPercent, + int ResponseSlaHours, + decimal OnTimeResponseTargetPercent, + decimal AverageRatingTarget, + decimal PositiveReviewTargetPercent, + string? Note); + +public sealed record ReconcileTimesheetRequest(string Status, int? ConfirmedMinutes, string Reason, string? Evidence); diff --git a/RikiPath.Application/IServices/IMentorLearnerSkillProfileService.cs b/RikiPath.Application/IServices/IMentorLearnerSkillProfileService.cs index 94cef6a..2f4a31e 100644 --- a/RikiPath.Application/IServices/IMentorLearnerSkillProfileService.cs +++ b/RikiPath.Application/IServices/IMentorLearnerSkillProfileService.cs @@ -7,4 +7,8 @@ public interface IMentorLearnerSkillProfileService { Task> GetSkillProfileAsync( int learnerId, int? cohortId = null, CancellationToken cancellationToken = default); + + /// The signed-in Learner's own competency profile for one class enrollment (same data and rules as the Mentor view). + Task> GetLearnerCourseCompetencyAsync( + int enrollmentId, CancellationToken cancellationToken = default); } diff --git a/RikiPath.Application/IServices/IPracticeTestService.cs b/RikiPath.Application/IServices/IPracticeTestService.cs index 8c548a3..541a34b 100644 --- a/RikiPath.Application/IServices/IPracticeTestService.cs +++ b/RikiPath.Application/IServices/IPracticeTestService.cs @@ -31,6 +31,18 @@ Task> SubmitPlacementTestAsync( Task> GetPlacementTestResultAsync( int attemptId, CancellationToken cancellationToken = default); + /// Starts or resumes the learner's attempt for one assigned in-class quiz. + Task> StartClassQuizAsync(int assignmentId, CancellationToken cancellationToken = default); + + /// Server-side completion of quiz attempts whose time is over, from answers saved before the deadline. + Task FinalizeExpiredClassQuizAttemptsAsync(IReadOnlyCollection attemptIds, CancellationToken cancellationToken = default); + + /// End-of-course assessment state for one of the learner's class enrollments. + Task> GetCourseFinalAssessmentAsync(int enrollmentId, CancellationToken cancellationToken = default); + + /// Starts (or resumes) the end-of-course assessment; answers/submit/result reuse the Placement attempt endpoints. + Task> StartCourseFinalAssessmentAsync(int enrollmentId, CancellationToken cancellationToken = default); + Task> StartAttemptAsync(int practiceTestId, CancellationToken cancellationToken = default); Task> SubmitAttemptAsync(int attemptId, SubmitAttemptRequest request, CancellationToken cancellationToken = default); diff --git a/RikiPath.Application/IServices/IStudyCourseService.cs b/RikiPath.Application/IServices/IStudyCourseService.cs index 9d98100..1d9d4c7 100644 --- a/RikiPath.Application/IServices/IStudyCourseService.cs +++ b/RikiPath.Application/IServices/IStudyCourseService.cs @@ -43,18 +43,6 @@ public interface IStudyCourseService Task> ReviewRetakeAsync(int id, int requestId, ReviewCourseRetake request, CancellationToken ct); Task> SaveRetakeSupportPlanAsync(int id, int requestId, SaveRetakeSupportPlan request, CancellationToken ct); Task EvidenceAsync(int id, int requestId, CancellationToken ct); - // Chuyển lớp có kiểm soát (Học viên yêu cầu, Admin duyệt). - Task> RequestTransferAsync(int courseId, int? targetCohortId, string? reason, Guid idempotencyKey, IFormFile? evidence, CancellationToken ct); - Task> TransferRequestsAsync(string? status, CancellationToken ct); - Task> TransferRequestDetailAsync(int requestId, CancellationToken ct); - Task> TransferEligibilityAsync(int requestId, int targetCohortId, CancellationToken ct); - Task> ApproveTransferAsync(int requestId, ApproveCohortTransfer request, CancellationToken ct); - Task> RejectTransferAsync(int requestId, RejectCohortTransfer request, CancellationToken ct); - Task> WithdrawTransferAsync(int requestId, CancellationToken ct); - Task TransferEvidenceAsync(int requestId, CancellationToken ct); - // Admin thay cố vấn chính cho phần còn lại của lớp. - Task> PreviewMentorReplacementAsync(int cohortId, int mentorId, int? fromSessionNumber, CancellationToken ct); - Task> ReplaceCohortMentorAsync(int cohortId, ReplaceCohortMentorRequest request, CancellationToken ct); Task> MentorAssignmentsAsync(int cohortId, CancellationToken ct); // Dời toàn bộ lịch / hủy lớp chưa có học viên (Mentor chính hoặc Admin yêu cầu, Admin duyệt từng lần). Task> CreateCohortScheduleRequestAsync(int cohortId, CreateCohortScheduleRequest request, CancellationToken ct); @@ -69,6 +57,7 @@ public interface IStudyCourseService Task> CreateCohortMentorReviewAsync(int courseId, CreateCohortMentorReviewRequest request, CancellationToken ct); Task> UpdateCohortMentorReviewAsync(int courseId, int reviewId, UpdateCohortMentorReviewRequest request, CancellationToken ct); Task> CohortMentorReviewsAsync(int courseId, CancellationToken ct); + Task> MentorReviewPromptsAsync(CancellationToken ct); Task> CohortClassMentorReviewsAsync(int cohortId, CancellationToken ct); Task> MentorCohortReviewSummaryAsync(int mentorId, CancellationToken ct); Task> CreateCohortComplaintAsync(int courseId, string? category, string? message, int? mentorId, bool refundReviewRequested, Guid idempotencyKey, IFormFile? evidence, string? title, int? courseSessionId, CancellationToken ct); diff --git a/RikiPath.Application/IUnitOfWork.cs b/RikiPath.Application/IUnitOfWork.cs index 469ec16..824da67 100644 --- a/RikiPath.Application/IUnitOfWork.cs +++ b/RikiPath.Application/IUnitOfWork.cs @@ -100,6 +100,8 @@ public interface IUnitOfWork IStudyCourseRepository StudyCourses { get; } IGenericRepository StudyCoursePlans { get; } IGenericRepository StudyCohorts { get; } + IGenericRepository ClassQuizzes { get; } + IGenericRepository ClassQuizAssignments { get; } IGenericRepository CohortEnrollmentEntitlements { get; } IGenericRepository CourseScheduleRequests { get; } IGenericRepository CohortTransferRequests { get; } diff --git a/RikiPath.Application/Requests/MentorScheduling/CreateMentorGroupPolicyRequest.cs b/RikiPath.Application/Requests/MentorScheduling/CreateMentorGroupPolicyRequest.cs index 06cd2c4..737fbc7 100644 --- a/RikiPath.Application/Requests/MentorScheduling/CreateMentorGroupPolicyRequest.cs +++ b/RikiPath.Application/Requests/MentorScheduling/CreateMentorGroupPolicyRequest.cs @@ -29,12 +29,16 @@ public sealed class CreateMentorGroupPolicyRequest // Nhóm E — Đào tạo & đánh giá public int HomeworkDeadlineDays { get; init; } = 7; public int PlacementAttemptLimit { get; init; } = 2; - public decimal RemediationCompletionThresholdPercent { get; init; } = 90m; - public string RemediationThresholdComparison { get; init; } = ">"; + public decimal RemediationCompletionThresholdPercent { get; init; } = RikiPath.Domain.Entities.MentorGroupPolicy.DefaultRetakeHomeworkThresholdPercent; + public string RemediationThresholdComparison { get; init; } = ">="; public bool RequireOfficialExamEvidence { get; init; } = true; public bool RequireAdminRemediationReview { get; init; } = true; public int KpiReportingPeriodDays { get; init; } = 30; + // Nhóm F — Hỗ trợ ôn lại JLPT + public bool RetakeSupportEnabled { get; init; } = true; + public decimal RemediationAttendanceThresholdPercent { get; init; } = RikiPath.Domain.Entities.MentorGroupPolicy.DefaultRetakeAttendanceThresholdPercent; + // Học phí mỗi buổi theo cấp độ JLPT public decimal TuitionPerSessionN5 { get; init; } = 60_000m; public decimal TuitionPerSessionN4 { get; init; } = 75_000m; @@ -72,12 +76,16 @@ public sealed class UpdateMentorGroupPolicyRequest // Nhóm E — Đào tạo & đánh giá public int HomeworkDeadlineDays { get; init; } = 7; public int PlacementAttemptLimit { get; init; } = 2; - public decimal RemediationCompletionThresholdPercent { get; init; } = 90m; - public string RemediationThresholdComparison { get; init; } = ">"; + public decimal RemediationCompletionThresholdPercent { get; init; } = RikiPath.Domain.Entities.MentorGroupPolicy.DefaultRetakeHomeworkThresholdPercent; + public string RemediationThresholdComparison { get; init; } = ">="; public bool RequireOfficialExamEvidence { get; init; } = true; public bool RequireAdminRemediationReview { get; init; } = true; public int KpiReportingPeriodDays { get; init; } = 30; + // Nhóm F — Hỗ trợ ôn lại JLPT (null = keep the current version's value) + public bool? RetakeSupportEnabled { get; init; } + public decimal? RemediationAttendanceThresholdPercent { get; init; } + public decimal? TuitionPerSessionN5 { get; init; } public decimal? TuitionPerSessionN4 { get; init; } public decimal? TuitionPerSessionN3 { get; init; } @@ -117,4 +125,8 @@ public sealed class UpdateMentorGroupPolicySectionRequest public decimal? RemediationCompletionThresholdPercent { get; init; } public string? RemediationThresholdComparison { get; init; } public int? KpiReportingPeriodDays { get; init; } + + // F. Hỗ trợ ôn lại JLPT (sectionKey: "retake") — also owns RemediationCompletionThresholdPercent. + public bool? RetakeSupportEnabled { get; init; } + public decimal? RemediationAttendanceThresholdPercent { get; init; } } diff --git a/RikiPath.Application/Requests/StudyCourses/CourseRequests.cs b/RikiPath.Application/Requests/StudyCourses/CourseRequests.cs index 46190f7..6ee2c29 100644 --- a/RikiPath.Application/Requests/StudyCourses/CourseRequests.cs +++ b/RikiPath.Application/Requests/StudyCourses/CourseRequests.cs @@ -17,7 +17,15 @@ public sealed record SubmitCourseHomework(string Content); public sealed record GradeCourseHomework(bool Passed, string Feedback); public sealed record ReviewCourseRetake(bool Approve, bool OfficialFailureVerified, string Response, bool OnTimeHomeworkEvidenceVerified = false, int? CohortId = null); -public sealed record SaveRetakeSupportPlan(string SupportPlan); +/// Mentor retake plan: structured fields (preferred) or the legacy free-text . +public sealed record SaveRetakeSupportPlan( + string? SupportPlan = null, + string? Goal = null, + IReadOnlyList? FocusSkills = null, + string? Content = null, + string? Materials = null, + string? Timeline = null, + string? Guidance = null); public sealed record GrantCohortEntitlementRequest(int LearnerId, string SourceType = "AdminManualGrant", string? EntitlementReference = null, string? Note = null, DateTime? ExpiresAtUtc = null); public sealed record RevokeCohortEntitlementRequest(string Reason); @@ -57,13 +65,10 @@ public sealed record ReorderCourseCatalogRequest( public sealed record ReviewJlptExam(DateOnly ExamDate, string Location, bool Approve, string Note); public sealed record RequestCourseChange(int SessionId, string Kind, string Reason); -public sealed record ApproveCohortTransfer(int? TargetCohortId = null, string? Note = null, int? ExpectedRevision = null); -public sealed record RejectCohortTransfer(string Reason, int? ExpectedRevision = null); /// Mentor chính/Admin yêu cầu dời toàn bộ lớp trống (Kind = "ShiftWeeks", ShiftWeeks 1..8) hoặc hủy lớp trống (Kind = "CancelEmptyCohort"). public sealed record CreateCohortScheduleRequest(string Kind, int? ShiftWeeks, string Reason, Guid IdempotencyKey); public sealed record ApproveCohortScheduleRequest(string? Note = null, int? ExpectedRevision = null); public sealed record RejectCohortScheduleRequest(string Reason, int? ExpectedRevision = null); -public sealed record ReplaceCohortMentorRequest(int MentorId, string Reason, Guid IdempotencyKey, int ExpectedCohortRevision, int? FromSessionNumber = null); public sealed record CreateCohortMentorReviewRequest(int MentorId, int Rating, string? Comment = null); public sealed record UpdateCohortMentorReviewRequest(int Rating, string? Comment = null); public sealed record RespondCohortComplaintRequest(string Response, int? ExpectedRevision = null); diff --git a/RikiPath.Application/Responses/AdminDashboardResponse.cs b/RikiPath.Application/Responses/AdminDashboardResponse.cs index b05291e..dc0b2d5 100644 --- a/RikiPath.Application/Responses/AdminDashboardResponse.cs +++ b/RikiPath.Application/Responses/AdminDashboardResponse.cs @@ -44,7 +44,6 @@ public sealed class AdminDashboardResponse public int PendingSlotCancelRequests { get; init; } public int PendingSlotChangeRequests { get; init; } public int OpenComplaints { get; init; } - public int PendingTransferRequests { get; init; } public int PendingCohortScheduleRequests { get; init; } public int PublishedCohorts { get; init; } public int DraftCohorts { get; init; } diff --git a/RikiPath.Application/Responses/ClassQuizzes/ClassQuizResponses.cs b/RikiPath.Application/Responses/ClassQuizzes/ClassQuizResponses.cs new file mode 100644 index 0000000..aa946f9 --- /dev/null +++ b/RikiPath.Application/Responses/ClassQuizzes/ClassQuizResponses.cs @@ -0,0 +1,128 @@ +using System.ComponentModel.DataAnnotations; + +namespace RikiPath.Application.Responses.ClassQuizzes; + +public sealed record QuizOptionDto(int OptionId, string Content, string? ImageUrl, bool? IsCorrect); + +/// One question of the bank or of a quiz version. Answer fields are filled only where the viewer may see them. +public sealed record QuizQuestionDto( + int QuestionId, + string SkillCode, + string LevelCode, + string Content, + string? ImageUrl, + string? AudioUrl, + int? PassageId, + string? PassageTitle, + string? PassageText, + string? Topic, + string? Difficulty, + string? Source, + bool IsCustom, + List Options, + int? CorrectOptionId, + int? SelectedOptionId, + bool? IsCorrect, + string? Explanation); + +public sealed record QuizSkillCountDto(string SkillCode, int QuestionCount); + +public sealed record QuizSkillResultDto(string SkillCode, int CorrectCount, int TotalCount, double ScorePercent); + +/// Status: NotStarted | InProgress | Completed | Overdue. +public sealed record QuizLearnerRowDto( + int AssignmentId, + int LearnerId, + string LearnerName, + string? AvatarUrl, + int EnrollmentId, + string Status, + DateTime? StartedAtUtc, + DateTime? CompletedAtUtc, + double? ScorePercent, + int? CorrectCount, + int? TotalCount, + List Skills); + +public sealed record MentorQuizListItemDto( + int QuizId, + int CohortId, + string CohortName, + string Title, + string LevelCode, + List Skills, + int QuestionCount, + int TimeLimitMinutes, + DateTime DueAtUtc, + DateTime PublishedAtUtc, + int AssignedCount, + int CompletedCount, + double? AverageScorePercent, + string Status, + bool ClassCompleted = false, + /// Comparison series + structure ("s:{series}|skill:count,..."); only quizzes with the same key are compared. + string? StructureKey = null); + +public sealed record MentorQuizDetailDto( + MentorQuizListItemDto Quiz, + List Learners, + List Questions); + +public sealed record LearnerQuizCardDto( + int AssignmentId, + int QuizId, + int CohortId, + int EnrollmentId, + string CohortName, + string Title, + string LevelCode, + List Skills, + int QuestionCount, + int TimeLimitMinutes, + DateTime DueAtUtc, + string Status, + int? AttemptId, + DateTime? CompletedAtUtc, + double? ScorePercent, + bool ClassCompleted = false); + +/// Learner/Mentor result. controls whether answer keys and explanations are included. +public sealed record QuizResultDto( + LearnerQuizCardDto Quiz, + int CorrectCount, + int TotalCount, + double ScorePercent, + int DurationSeconds, + List Skills, + bool AnswersReleased, + DateTime? AnswersReleaseAtUtc, + List Questions); + +public sealed record QuizBankDto(string LevelCode, List Questions); + +public sealed class CreateClassQuizRequest +{ + [Required, MaxLength(200)] public string Title { get; set; } = string.Empty; + [Range(1, 240)] public int TimeLimitMinutes { get; set; } + public DateTime DueAtUtc { get; set; } + /// Null or empty = every learner currently enrolled in the class. + public List? LearnerIds { get; set; } + /// Earlier quiz of this class with the same structure that this quiz is an equivalent re-test of + /// (Mentor's explicit choice). Without it the quiz starts its own series and is never used to measure change. + public int? ComparableWithQuizId { get; set; } + public List Items { get; set; } = []; +} + +/// Either a bank question () or a Mentor-authored single-choice question. +public sealed class ClassQuizItemRequest +{ + public int? BankQuestionId { get; set; } + public string? SkillCode { get; set; } + [MaxLength(2000)] public string? Content { get; set; } + public List? Options { get; set; } + public int? CorrectOptionIndex { get; set; } + [MaxLength(2000)] public string? Explanation { get; set; } + [MaxLength(8000)] public string? PassageText { get; set; } + [MaxLength(1000)] public string? AudioUrl { get; set; } + [MaxLength(1000)] public string? ImageUrl { get; set; } +} diff --git a/RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs b/RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs new file mode 100644 index 0000000..f7c38ec --- /dev/null +++ b/RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs @@ -0,0 +1,162 @@ +namespace RikiPath.Application.Responses.Content +{ + public sealed class CurriculumPackageArchiveInfo + { + public string FileName { get; set; } = string.Empty; + public string? LevelCode { get; set; } + public bool Exists { get; set; } + public long SizeBytes { get; set; } + public int EntryCount { get; set; } + public int UnsafeEntryCount { get; set; } + public string? Sha256Short { get; set; } + } + + public sealed class CurriculumPackageLevelSummary + { + public string LevelCode { get; set; } = string.Empty; + public int? CertificateLevelId { get; set; } + public int TopicCount { get; set; } + public int LessonCount { get; set; } + public int VocabularyCount { get; set; } + public int KanjiCount { get; set; } + public int GrammarCount { get; set; } + public int PracticeExerciseCount { get; set; } + public int MockTestCount { get; set; } + public int AudioCount { get; set; } + public int ImageCount { get; set; } + public int SrsTemplateCount { get; set; } + } + + public sealed class CurriculumPackageChapterInfo + { + public string LevelCode { get; set; } = string.Empty; + public string TopicCode { get; set; } = string.Empty; + public int OrderIndex { get; set; } + public string TitleVi { get; set; } = string.Empty; + public string? TitleJa { get; set; } + public string? Description { get; set; } + public int LessonCount { get; set; } + public int ExistingPublishedLessonCount { get; set; } + public int ExistingDraftCount { get; set; } + } + + public sealed class CurriculumPackageInventoryResponse + { + public bool PackageRootFound { get; set; } + public string? PackageRootDisplay { get; set; } + public int TotalGlobalSrsTemplates { get; set; } + public List Archives { get; set; } = []; + public List Levels { get; set; } = []; + public List Chapters { get; set; } = []; + public List Warnings { get; set; } = []; + } + + public sealed class CurriculumPackagePreviewRequest + { + public List? Levels { get; set; } + public List? TopicCodes { get; set; } + public List? MockTestIds { get; set; } + public bool IncludeLessons { get; set; } = true; + public bool IncludeVocabKanjiGrammar { get; set; } = true; + public bool IncludePracticeExercises { get; set; } = true; + public bool IncludeSrsTemplates { get; set; } = true; + public bool IncludeMockTests { get; set; } = true; + public bool UploadAssets { get; set; } = true; + public int Page { get; set; } = 1; + public int PageSize { get; set; } = 25; + } + + public sealed class CurriculumPackagePreviewItemResponse + { + public string ExternalId { get; set; } = string.Empty; + public string EntityType { get; set; } = string.Empty; + public string LevelCode { get; set; } = string.Empty; + public string? TopicCode { get; set; } + public string RowKey { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string Action { get; set; } = "New"; + public string Status { get; set; } = "Draft"; + public bool PublishedReady { get; set; } + public string? AudioAsset { get; set; } + public string? ImageAsset { get; set; } + public int ChildCount { get; set; } + public List Warnings { get; set; } = []; + public List Errors { get; set; } = []; + } + + public sealed class CurriculumPackageIssueResponse + { + public string Severity { get; set; } = "Warning"; + public string Code { get; set; } = string.Empty; + public string Target { get; set; } = string.Empty; + public string Message { get; set; } = string.Empty; + } + + public sealed class CurriculumPackagePreviewResponse + { + public List SelectedLevels { get; set; } = []; + public List SelectedTopicCodes { get; set; } = []; + public int TotalItems { get; set; } + public int NewCount { get; set; } + public int ExistingCount { get; set; } + public int ModifiedCount { get; set; } + public int WarningCount { get; set; } + public int ErrorCount { get; set; } + public int AudioAssetCount { get; set; } + public int ImageAssetCount { get; set; } + public bool CanConfirm { get; set; } + public Dictionary ByEntityType { get; set; } = new(StringComparer.OrdinalIgnoreCase); + public List DependencyOrder { get; set; } = []; + public List Issues { get; set; } = []; + public int Page { get; set; } = 1; + public int PageSize { get; set; } = 25; + public int TotalPages { get; set; } = 1; + public List Items { get; set; } = []; + } + + public sealed class CurriculumPackageConfirmRequest + { + public List? Levels { get; set; } + public List? TopicCodes { get; set; } + public List? MockTestIds { get; set; } + public bool IncludeLessons { get; set; } = true; + public bool IncludeVocabKanjiGrammar { get; set; } = true; + public bool IncludePracticeExercises { get; set; } = true; + public bool IncludeSrsTemplates { get; set; } = true; + public bool IncludeMockTests { get; set; } = true; + public bool UploadAssets { get; set; } = true; + public string? IdempotencyKey { get; set; } + } + + public sealed class CurriculumPackageConfirmResponse + { + public Guid BatchId { get; set; } + public string Status { get; set; } = "Draft"; + public bool PublishedReady { get; set; } + public string RightsStatus { get; set; } = "Pending"; + public int DraftsCreatedCount { get; set; } + public int SkippedExistingCount { get; set; } + public int UploadedAudioCount { get; set; } + public int UploadedImageCount { get; set; } + public Dictionary ByEntityType { get; set; } = new(StringComparer.OrdinalIgnoreCase); + public List CreatedRequestIds { get; set; } = []; + public List Warnings { get; set; } = []; + } + + public sealed class SrsCardTemplateImportPayloadResponse + { + public string CardType { get; set; } = "Vocabulary"; + public string FrontText { get; set; } = string.Empty; + public string BackText { get; set; } = string.Empty; + public string? Reading { get; set; } + public string? Meaning { get; set; } + public string? ExampleSentence { get; set; } + public string? ExampleMeaning { get; set; } + public string? UsageNotes { get; set; } + public string? AudioUrl { get; set; } + public int CertificateLevelId { get; set; } + public string CertificateLevelCode { get; set; } = string.Empty; + public string NormalizedContentKey { get; set; } = string.Empty; + public string? ExternalStableId { get; set; } + } +} diff --git a/RikiPath.Application/Responses/Homework/HomeworkResponses.cs b/RikiPath.Application/Responses/Homework/HomeworkResponses.cs index 514f853..ef540ac 100644 --- a/RikiPath.Application/Responses/Homework/HomeworkResponses.cs +++ b/RikiPath.Application/Responses/Homework/HomeworkResponses.cs @@ -32,7 +32,9 @@ public sealed record HomeworkItem(int Id, int LearnerId, string LearnerName, str HomeworkAiDraftView? AiDraft = null, HomeworkPublishedGradeView? PublishedGrade = null, int? BookingId = null, string? AssignmentType = null, string? JlptLevel = null, IReadOnlyList? Questions = null, int? StudyCourseId = null, string? CohortName = null, IReadOnlyList? Attachments = null, - string? AnswerGuide = null, string? LearnerAvatarUrl = null); + string? AnswerGuide = null, string? LearnerAvatarUrl = null, + /// Class completed: learning records are read-only for every role (capability for the UI). + bool ClassCompleted = false); public sealed record HomeworkPeriodReport(DateOnly From, DateOnly To, int AssignedCount, int SubmittedCount, double? HomeworkPercent, int SessionCount, int AttendedCount, double? AttendancePercent, int UntrackedSessionCount); \ No newline at end of file diff --git a/RikiPath.Application/Responses/MentorKpi/MentorKpiDashboardResponses.cs b/RikiPath.Application/Responses/MentorKpi/MentorKpiDashboardResponses.cs new file mode 100644 index 0000000..534eeb3 --- /dev/null +++ b/RikiPath.Application/Responses/MentorKpi/MentorKpiDashboardResponses.cs @@ -0,0 +1,217 @@ +namespace RikiPath.Application.Responses.MentorKpi; + +/// +/// KPI evaluation status. Met/NotMet are decided on exact numerator/denominator (never on a rounded percent). +/// NoData = nothing to measure yet, NotApplicable = the policy disables the target, PendingConfirmation = unresolved data +/// could still change the result. marks a period that has not ended. +/// +public static class KpiStatus +{ + public const string Met = "Met"; + public const string NotMet = "NotMet"; + public const string NoData = "NoData"; + public const string NotApplicable = "NotApplicable"; + public const string PendingConfirmation = "PendingConfirmation"; +} + +/// Timesheet status of one class session for its Mentor. +public static class TimesheetStatus +{ + public const string Upcoming = "Upcoming"; + public const string InProgress = "InProgress"; + public const string Taught = "Taught"; + public const string Pending = "Pending"; + public const string Absent = "Absent"; + public const string Cancelled = "Cancelled"; +} + +/// How a taught session was confirmed. +public static class TimesheetSource +{ + /// Mentor and ≥1 learner joined the room and the Mentor completed the session (includes the Time Skip flow): scheduled minutes. + public const string CompletionFlow = "CompletionFlow"; + /// Completed session with Mentor presence ≥ policy minimum: min(presence, scheduled). + public const string Presence = "Presence"; + /// Admin reconciliation (latest adjustment wins; history is kept). + public const string AdminAdjustment = "AdminAdjustment"; +} + +public sealed record KpiPolicySnapshotResponse( + int Id, + int Version, + DateOnly EffectiveFromMonth, + decimal MinimumPresencePercent, + decimal TeachingCompletionTargetPercent, + int HomeworkMinimumCount, + int HomeworkPerSessionCount, + decimal GradingCompletionTargetPercent, + int ResponseSlaHours, + decimal OnTimeResponseTargetPercent, + decimal AverageRatingTarget, + decimal PositiveReviewTargetPercent, + int PositiveRatingMinimum, + string? Note, + DateTime CreatedAtUtc, + string? CreatedByAdminName, + bool IsCurrent, + bool CanDelete); + +public sealed record KpiMetricResponse( + string Key, + decimal? ActualValue, + decimal? TargetValue, + decimal? Numerator, + decimal? Denominator, + string Status, + bool Provisional); + +public sealed record KpiFilterOptionResponse(int CohortId, string CohortName, string? LevelCode); + +public sealed record TeachingSummaryResponse( + int RequiredSessions, + int TaughtSessions, + int PendingSessions, + int AbsentSessions, + int CancelledSessions, + int UpcomingSessions, + int InProgressSessions, + int ConfirmedMinutes, + int ScheduledMinutesOfTaught); + +public sealed record HomeworkSummaryResponse( + int AssignedHomework, + int RequiredHomework, + int RecognizedHomework, + int ClassesWithTarget, + int ClassesMeetingTarget, + int ReceivedSubmissions, + int GradedSubmissions, + int PendingSubmissions, + int OverduePendingSubmissions, + int GradedActivityInPeriod, + int BacklogFromEarlierPeriods, + int QuizzesAssigned); + +public sealed record ResponseTimePointResponse( + DateOnly From, + DateOnly To, + double? AverageMinutes, + int Samples, + int OnTime, + int SlaHours); + +public sealed record ResponseSummaryResponse( + double? AverageMinutes, + int Samples, + int EligibleSla, + int OnTime, + int Late, + int OverdueUnanswered, + int OpenWithinSla, + IReadOnlyList SlaHoursInUse, + IReadOnlyList Weekly); + +public sealed record ReviewItemResponse(int Id, int Rating, string? Comment, string? CohortName, DateTime CreatedAtUtc); + +public sealed record RatingSummaryResponse( + int TotalReviews, + decimal? AverageRating, + int PositiveReviews, + IReadOnlyDictionary Distribution, + IReadOnlyList Reviews); + +public sealed record KpiClassRowResponse( + int CohortId, + string CohortName, + string? LevelCode, + int RequiredSessions, + int TaughtSessions, + int ConfirmedMinutes, + int AssignedHomework, + int RequiredHomework, + int RecognizedHomework); + +public sealed record TimesheetRowResponse( + int SessionId, + int CohortId, + string CohortName, + string? LevelCode, + int SessionNumber, + DateTime ScheduledStartUtc, + DateTime ScheduledEndUtc, + int ScheduledMinutes, + int? PresenceMinutes, + int ConfirmedMinutes, + string Status, + string? Source, + string? ReasonCode, + DateTime? ActualStartedAtUtc, + DateTime? ActualEndedAtUtc, + bool LearnerJoined, + bool CanReconcile, + IReadOnlyList Adjustments); + +public sealed record TimesheetAdjustmentResponse( + long Id, + string PreviousStatus, + string NewStatus, + int PreviousConfirmedMinutes, + int NewConfirmedMinutes, + string Reason, + string? Evidence, + string? AdminName, + DateTime CreatedAtUtc); + +public sealed record MentorKpiDashboardResponse( + int MentorId, + string MentorName, + string? MentorAvatarUrl, + string Month, + DateTime PeriodStartUtc, + DateTime PeriodEndUtc, + bool PeriodEnded, + DateTime AsOfUtc, + string? LevelCode, + int? CohortId, + KpiPolicySnapshotResponse Policy, + IReadOnlyList LevelOptions, + IReadOnlyList ClassOptions, + IReadOnlyList ActiveLevels, + TeachingSummaryResponse Teaching, + HomeworkSummaryResponse Homework, + ResponseSummaryResponse Response, + RatingSummaryResponse Rating, + IReadOnlyList Metrics, + IReadOnlyList Classes, + IReadOnlyList Timesheet); + +public sealed record KpiMentorRowResponse( + int MentorId, + string MentorName, + string? AvatarUrl, + IReadOnlyList ActiveLevels, + int RequiredSessions, + int TaughtSessions, + int PendingSessions, + int ConfirmedMinutes, + int TotalReviews, + decimal? AverageRating, + KpiMetricResponse GradingCompletion, + KpiMetricResponse OnTimeResponse, + KpiMetricResponse HomeworkTarget, + bool HasActivity); + +public sealed record KpiOverviewResponse( + string Month, + bool PeriodEnded, + DateTime AsOfUtc, + string? LevelCode, + KpiPolicySnapshotResponse Policy, + IReadOnlyList LevelOptions, + IReadOnlyList Metrics, + int ActiveMentors, + int TaughtSessions, + int ConfirmedMinutes, + int TotalReviews, + decimal? AverageRating, + IReadOnlyList Mentors); diff --git a/RikiPath.Application/Responses/MentorMeetings/MentorLearnerSkillProfileResponse.cs b/RikiPath.Application/Responses/MentorMeetings/MentorLearnerSkillProfileResponse.cs index baf48e1..346c301 100644 --- a/RikiPath.Application/Responses/MentorMeetings/MentorLearnerSkillProfileResponse.cs +++ b/RikiPath.Application/Responses/MentorMeetings/MentorLearnerSkillProfileResponse.cs @@ -106,7 +106,9 @@ public sealed record InClassAssessmentEventResponse( double? ScorePercent, bool? Passed, List Skills, - string? MentorFeedback); + string? MentorFeedback, + string Status = "NotSubmitted", + double? Score10 = null); public sealed record InClassCompetencyResponse( bool HasClassStarted, @@ -124,7 +126,43 @@ public sealed record InClassCompetencyResponse( int ScoredAssessmentCount = 0, List? Strengths = null, List? FocusAreas = null, - List? TrendPoints = null); + List? TrendPoints = null, + double? AverageHomeworkScore10 = null, + List? HomeworkScoreTimeline = null, + InClassQuizSummaryResponse? Quizzes = null); + +public sealed record QuizSkillPointResponse(string SkillCode, int CorrectCount, int TotalCount, double ScorePercent); + +/// One completed in-class quiz (0–100%), with results only for the skills it actually tested. +public sealed record InClassQuizResultResponse( + int QuizId, + int AssignmentId, + string Title, + DateTime CompletedAtUtc, + double ScorePercent, + int CorrectCount, + int TotalCount, + string StructureKey, + List Skills); + +/// First vs latest result of one skill across comparable quizzes (same level and structure). +public sealed record QuizSkillChangeResponse( + string SkillCode, + double FirstScorePercent, + double LatestScorePercent, + double? DeltaPercent, + int FirstQuizId, + int LatestQuizId); + +/// Quiz statistics kept apart from homework (0–10) and from the end-of-course assessment. +public sealed record InClassQuizSummaryResponse( + int AssignedCount, + int CompletedCount, + double? AverageScorePercent, + List Results, + List SkillChanges, + bool IsComparable, + string? ComparableStructureKey); public sealed record SkillComparisonItemResponse( string SkillCode, @@ -132,7 +170,11 @@ public sealed record SkillComparisonItemResponse( double BaselineScorePercent, double CurrentScorePercent, double DeltaPercent, - string Status); + string Status, + int BaselineCorrectCount = 0, + int BaselineTotalCount = 0, + int CurrentCorrectCount = 0, + int CurrentTotalCount = 0); public sealed record CompetencyComparisonResponse( bool IsComparable, @@ -153,7 +195,17 @@ public sealed record CompetencyComparisonResponse( double? MostImprovedDeltaPercent = null, string? PriorityFocusSkill = null, List? CurrentStrengths = null, - List? NextRecommendations = null); + List? NextRecommendations = null, + string? ReasonCode = null, + string? ComparedLevelScope = null, + int? BaselineCorrectCount = null, + int? BaselineTotalCount = null, + int? CurrentCorrectCount = null, + int? CurrentTotalCount = null, + List? DeclinedSkills = null, + List? UnchangedSkills = null, + string? LowestCurrentSkill = null, + double? LowestCurrentScorePercent = null); public sealed record ParallelSelfStudySkillResponse( string SkillCode, @@ -179,4 +231,51 @@ public sealed record MentorLearnerSkillProfileResponse( CompetencyComparisonResponse? Comparison = null, List? ParallelSelfStudySkills = null, string? TargetJlptLevel = null, - DateTime? TargetExamDate = null); + DateTime? TargetExamDate = null, + CourseFinalAssessmentSummaryResponse? FinalAssessment = null, + PostCourseSupportResponse? PostCourseSupport = null, + string ViewerRole = "Mentor"); + +/// Published homework score on the 0–10 display scale, in grading order (never includes unpublished drafts). +public sealed record HomeworkScorePointResponse( + int AssignmentId, + string Title, + double Score10, + DateTime GradedAtUtc); + +public sealed record FinalSkillResultResponse( + string SkillCode, + string SkillLabel, + double ScorePercent, + int CorrectCount, + int TotalCount); + +/// End-of-course assessment state and official result for one class enrollment (same source for Mentor and Learner). +public sealed record CourseFinalAssessmentSummaryResponse( + string Availability, + string? LevelCode, + int AttemptLimit, + int AttemptsUsed, + int? ActiveAttemptId, + int? PendingSubmissionAttemptId, + int? AttemptId, + DateTime? CompletedAtUtc, + double? OverallScorePercent, + int? CorrectCount, + int? TotalQuestions, + bool? Passed, + double PassThresholdPercent, + List Skills); + +/// Data for the post-course reinforcement policy: raw homework ratio vs class threshold and official final result. +public sealed record PostCourseSupportResponse( + int AssignedHomeworkCount, + int SubmittedHomeworkCount, + int NotSubmittedHomeworkCount, + double? SubmittedHomeworkPercent, + decimal HomeworkThresholdPercent, + string HomeworkThresholdComparison, + bool MeetsHomeworkThreshold, + bool FinalAssessmentCompleted, + bool? FinalAssessmentPassed, + bool NeedsReinforcementPlan); diff --git a/RikiPath.Application/Responses/PlacementTests/CourseFinalAssessmentResponses.cs b/RikiPath.Application/Responses/PlacementTests/CourseFinalAssessmentResponses.cs new file mode 100644 index 0000000..c2dbf43 --- /dev/null +++ b/RikiPath.Application/Responses/PlacementTests/CourseFinalAssessmentResponses.cs @@ -0,0 +1,39 @@ +namespace RikiPath.Application.Responses.PlacementTests +{ + /// + /// Learner-facing state of the end-of-course competency assessment for one class enrollment. + /// Availability: NotOpen (class still running) | NotEligible | Available | InProgress | PendingSubmission | Completed. + /// + public sealed class CourseFinalAssessmentStatusResponse + { + public int EnrollmentId { get; set; } + public int CohortId { get; set; } + public string CohortName { get; set; } = string.Empty; + public string? LevelCode { get; set; } + public bool IsClassCompleted { get; set; } + public string Availability { get; set; } = CourseFinalAvailability.NotOpen; + public bool CanStart { get; set; } + public string? CannotStartReason { get; set; } + public int AttemptLimit { get; set; } + public int AttemptsUsed { get; set; } + public int? ActiveAttemptId { get; set; } + public DateTime? ActiveAttemptExpiresAt { get; set; } + public int? PendingSubmissionAttemptId { get; set; } + public int? CompletedAttemptId { get; set; } + public DateTime? CompletedAtUtc { get; set; } + public List PlannedLevelCodes { get; set; } = []; + public List PlannedSkillCodes { get; set; } = []; + public int PlannedQuestionCount { get; set; } + public int TimeLimitMinutes { get; set; } + } + + public static class CourseFinalAvailability + { + public const string NotOpen = "NotOpen"; + public const string NotEligible = "NotEligible"; + public const string Available = "Available"; + public const string InProgress = "InProgress"; + public const string PendingSubmission = "PendingSubmission"; + public const string Completed = "Completed"; + } +} diff --git a/RikiPath.Application/Responses/PlacementTests/PlacementTestResponses.cs b/RikiPath.Application/Responses/PlacementTests/PlacementTestResponses.cs index cb16891..3f5101a 100644 --- a/RikiPath.Application/Responses/PlacementTests/PlacementTestResponses.cs +++ b/RikiPath.Application/Responses/PlacementTests/PlacementTestResponses.cs @@ -6,6 +6,9 @@ namespace RikiPath.Application.Responses.PlacementTests { public sealed record PlacementAttemptAllowance(int Limit, int Started, int Remaining, int? PendingSubmissionAttemptId); + /// A completed attempt of the current quota scope; AttemptNumber is its stable start order in that scope (1, 2…). + public sealed record PlacementScopeAttemptResponse(int AttemptId, int AttemptNumber, DateTime? SubmittedAt, double? ScorePercent); + public class PlacementTestStatusResponse { public string AttemptType { get; set; } = "placement"; @@ -16,6 +19,9 @@ public class PlacementTestStatusResponse public PlacementAttemptAllowance? AttemptAllowance { get; set; } public bool QuotaInitialized { get; set; } = true; + + /// Completed attempts of the same quota scope, oldest first (Lần 1, Lần 2). Never mixes other scopes. + public List CompletedAttempts { get; set; } = []; public bool CanStartNewAttempt { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.Never)] @@ -219,6 +225,14 @@ public class PlacementTestResultResponse public int CorrectCount { get; set; } public int NotStudiedCount { get; set; } public int TotalQuestions { get; set; } + + // Read-only analysis scope (scoring is unchanged): questions that could be graded (e.g. listening sections without + // audio are excluded). Null when the attempt has no data to derive them. + public int? EvaluatedQuestionCount { get; set; } + public int? EvaluatedCorrectCount { get; set; } + public int? EvaluatedBlankCount { get; set; } + public int? UnevaluatedQuestionCount { get; set; } + public int AssessedJlptLevelId { get; set; } public string AssessedJlptLevelName { get; set; } = string.Empty; public int RecommendedTargetJlptLevelId { get; set; } diff --git a/RikiPath.Application/Services/AdaptiveSkillProfileService.cs b/RikiPath.Application/Services/AdaptiveSkillProfileService.cs index 33bc85f..30fc47e 100644 --- a/RikiPath.Application/Services/AdaptiveSkillProfileService.cs +++ b/RikiPath.Application/Services/AdaptiveSkillProfileService.cs @@ -97,7 +97,7 @@ public async Task BuildProfileAsync( && r.MockTestAttempt.IsCompleted && r.MockTestAttempt.SubmittedAt != null && !r.MockTestAttempt.IsPlacementAssessment - && r.MockTestAttempt.AttemptKind != AttemptKind.Placement + && r.MockTestAttempt.AttemptKind == AttemptKind.MockTest && r.TotalCount > 0) .Select(r => new { diff --git a/RikiPath.Application/Services/AdminDashboardService.cs b/RikiPath.Application/Services/AdminDashboardService.cs index c9a3f86..004f053 100644 --- a/RikiPath.Application/Services/AdminDashboardService.cs +++ b/RikiPath.Application/Services/AdminDashboardService.cs @@ -35,8 +35,6 @@ public async Task> GetAsync(CancellationToke .CountAsync(x => !x.IsDeleted && x.ChangeRequestedAt != null && x.ChangeResolution == null && x.StartTime > now, cancellationToken); var openComplaints = await unitOfWork.CohortComplaints.Query() .CountAsync(x => x.Status == CohortComplaint.Open || x.Status == CohortComplaint.UnderReview, cancellationToken); - var pendingTransferRequests = await unitOfWork.CohortTransferRequests.Query() - .CountAsync(x => x.Status == CohortTransferRequest.Pending, cancellationToken); var pendingCohortScheduleRequests = await unitOfWork.CohortScheduleRequests.Query() .CountAsync(x => x.Status == CohortScheduleRequest.Pending, cancellationToken); var publishedCohorts = await unitOfWork.StudyCohorts.Query() @@ -173,7 +171,6 @@ DateOnly ToVnDay(DateTime dt) PendingSlotCancelRequests = pendingSlotCancelRequests, PendingSlotChangeRequests = pendingSlotChangeRequests, OpenComplaints = openComplaints, - PendingTransferRequests = pendingTransferRequests, PendingCohortScheduleRequests = pendingCohortScheduleRequests, PublishedCohorts = publishedCohorts, DraftCohorts = draftCohorts, diff --git a/RikiPath.Application/Services/ClassQuizService.cs b/RikiPath.Application/Services/ClassQuizService.cs new file mode 100644 index 0000000..79806e8 --- /dev/null +++ b/RikiPath.Application/Services/ClassQuizService.cs @@ -0,0 +1,633 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using RikiPath.Application.IServices; +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.ClassQuizzes; +using RikiPath.Application.Services.ContentAuthoring; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; +using static RikiPath.Application.Services.PracticeTestService; + +namespace RikiPath.Application.Services; + +/// +/// In-class skill quizzes. Questions come from the approved, non-protected question bank of the class level +/// (never the Placement / end-of-course bank) or are authored by the Mentor for this class only (never added to +/// the shared bank). A quiz is frozen at publication; attempts, autosave and scoring run on the assessment engine. +/// Results are 0–100% per skill and stay separate from Homework (0–10) and from the end-of-course assessment. +/// +public sealed class ClassQuizService( + IUnitOfWork uow, + IClaimService claims, + IPracticeTestService engine, + INotificationService? notifications = null) : IClassQuizService +{ + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + private const int CustomQuestionIdBase = 1_900_000_000; + private static readonly string[] SkillOrder = ["vocabulary", "grammar", "reading", "listening"]; + + // ---------------------------------------------------------------- Mentor: bank + + public async Task> GetBankAsync(int cohortId, CancellationToken cancellationToken = default) + { + var cohort = await LoadMentorCohortAsync(cohortId, cancellationToken); + if (cohort is null) return ApiResponse.Fail("Bạn chỉ được giao bài kiểm tra cho lớp do mình phụ trách.", HttpStatusCode.Forbidden); + var levelCode = cohort.Plan.CertificateLevel.Code.Trim().ToUpperInvariant(); + var bank = await LoadBankQuestionsAsync(cohort.Plan.CertificateLevelId, null, cancellationToken); + return ApiResponse.Success(new QuizBankDto(levelCode, bank.Select(q => ToBankDto(q, levelCode)).ToList())); + } + + // ---------------------------------------------------------------- Mentor: create & publish + + public async Task> CreateAsync(int cohortId, CreateClassQuizRequest request, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Mentor) + return ApiResponse.Fail("Chỉ Giáo viên phụ trách lớp mới giao được bài kiểm tra.", HttpStatusCode.Forbidden); + var cohort = await LoadMentorCohortAsync(cohortId, cancellationToken); + if (cohort is null) + return ApiResponse.Fail("Bạn chỉ được giao bài kiểm tra cho lớp do mình phụ trách.", HttpStatusCode.Forbidden); + if (cohort.Status == "Completed") + return ApiResponse.Fail(ClassRecordLock.Message, HttpStatusCode.Conflict, ClassRecordLock.ErrorCode); + if (cohort.Status is "Cancelled" or "Draft") + return ApiResponse.Fail("Lớp học không còn mở để giao bài kiểm tra.", HttpStatusCode.Conflict); + + var now = DateTime.UtcNow; + var title = (request.Title ?? string.Empty).Trim(); + if (title.Length is 0 or > 200) return Invalid("Nhập tên bài kiểm tra (tối đa 200 ký tự)."); + if (request.TimeLimitMinutes is < 1 or > 240) return Invalid("Thời gian làm bài từ 1 đến 240 phút."); + var dueUtc = BusinessDateHelper.EnsureUtc(request.DueAtUtc); + if (dueUtc <= now.AddMinutes(5)) return Invalid("Hạn làm bài phải sau thời điểm hiện tại ít nhất 5 phút."); + if (request.Items is not { Count: > 0 }) return Invalid("Bài kiểm tra cần ít nhất 1 câu hỏi."); + if (request.Items.Count > 200) return Invalid("Bài kiểm tra tối đa 200 câu hỏi."); + + var roster = cohort.Enrollments + .Where(e => e.PaymentStatus is "Paid" or "PartiallyRefunded" && e.Status is "Ready" or "Active") + .GroupBy(e => e.LearnerId) + .Select(g => g.OrderByDescending(e => e.Id).First()) + .ToList(); + var recipients = request.LearnerIds is { Count: > 0 } + ? roster.Where(e => request.LearnerIds.Contains(e.LearnerId)).ToList() + : roster; + if (recipients.Count == 0) return Invalid("Chưa có học viên hợp lệ để nhận bài kiểm tra."); + if (request.LearnerIds is { Count: > 0 } && recipients.Count != request.LearnerIds.Distinct().Count()) + return Invalid("Có học viên không thuộc lớp học này."); + + var bankIds = request.Items.Where(i => i.BankQuestionId.HasValue).Select(i => i.BankQuestionId!.Value).ToList(); + if (bankIds.Count != bankIds.Distinct().Count()) return Invalid("Đề có câu hỏi bị trùng."); + var bank = (await LoadBankQuestionsAsync(cohort.Plan.CertificateLevelId, bankIds, cancellationToken)).ToDictionary(q => q.Question.Id); + + var levelId = cohort.Plan.CertificateLevelId; + var levelCode = cohort.Plan.CertificateLevel.Code.Trim().ToUpperInvariant(); + var questions = new List(); + var customIndex = 0; + foreach (var item in request.Items) + { + if (item.BankQuestionId is int bankId) + { + if (!bank.TryGetValue(bankId, out var candidate)) + return Invalid("Câu hỏi không thuộc kho câu hỏi được phép của cấp độ lớp."); + questions.Add(FromBank(candidate, levelId, levelCode)); + continue; + } + + customIndex++; + var skill = (item.SkillCode ?? string.Empty).Trim().ToLowerInvariant(); + if (!SkillOrder.Contains(skill)) return Invalid($"Câu tự soạn {customIndex}: chọn kỹ năng."); + var content = (item.Content ?? string.Empty).Trim(); + if (content.Length == 0) return Invalid($"Câu tự soạn {customIndex}: nhập nội dung câu hỏi."); + var options = (item.Options ?? []).Select(o => (o ?? string.Empty).Trim()).ToList(); + if (options.Count is < 2 or > 6 || options.Any(o => o.Length == 0)) + return Invalid($"Câu tự soạn {customIndex}: cần 2–6 phương án và không để trống phương án."); + if (options.Distinct(StringComparer.OrdinalIgnoreCase).Count() != options.Count) + return Invalid($"Câu tự soạn {customIndex}: các phương án không được trùng nhau."); + if (item.CorrectOptionIndex is not int correct || correct < 0 || correct >= options.Count) + return Invalid($"Câu tự soạn {customIndex}: chọn đáp án đúng."); + var audio = (item.AudioUrl ?? string.Empty).Trim(); + if (skill == "listening" && !IsValidMediaUrl(audio)) + return Invalid($"Câu tự soạn {customIndex}: câu Nghe hiểu cần audio hợp lệ."); + var passage = (item.PassageText ?? string.Empty).Trim(); + var qid = CustomQuestionIdBase + customIndex; + questions.Add(new PlacementSnapshotQuestionItem + { + QuestionId = qid, + MockTestId = 0, + MockTestSectionId = 0, + SectionTitle = SkillLabel(skill), + SectionOrder = Array.IndexOf(SkillOrder, skill) + 1, + LanguageSkillName = SkillEnglish(skill), + JlptLevelId = levelId, + JlptLevelName = levelCode, + Content = content, + AudioUrl = string.IsNullOrWhiteSpace(audio) ? null : audio, + ImageUrl = IsValidMediaUrl(item.ImageUrl) ? item.ImageUrl!.Trim() : null, + PassageText = passage.Length > 0 ? passage : null, + CorrectOptionId = CustomOptionId(customIndex, correct), + Explanation = string.IsNullOrWhiteSpace(item.Explanation) ? null : item.Explanation.Trim(), + Options = options.Select((text, i) => new PlacementSnapshotOptionItem + { + OptionId = CustomOptionId(customIndex, i), + Content = text, + Order = i + 1, + IsCorrect = i == correct, + }).ToList(), + }); + } + + // Canonical skill order; reading questions stay grouped with their passage. + questions = questions + .Select((q, i) => (q, i)) + .OrderBy(x => SkillRank(x.q.LanguageSkillName)) + .ThenBy(x => x.q.PassageId ?? int.MaxValue) + .ThenBy(x => x.i) + .Select(x => x.q) + .ToList(); + for (var i = 0; i < questions.Count; i++) questions[i].Order = i + 1; + + var skillCounts = SkillCounts(questions); + var countsKey = StructureKeyOf(skillCounts); + var seriesToken = Guid.NewGuid().ToString("N")[..16]; + if (request.ComparableWithQuizId is int previousId) + { + var previous = await uow.ClassQuizzes.Query().AsNoTracking() + .FirstOrDefaultAsync(q => q.Id == previousId && q.CohortId == cohort.Id && !q.IsDeleted, cancellationToken); + if (previous is null) return Invalid("Bài kiểm tra dùng để so sánh không thuộc lớp này."); + var parts = previous.StructureKey.Split('|', 2); + if (parts.Length != 2 || parts[1] != countsKey || !parts[0].StartsWith("s:", StringComparison.Ordinal)) + return Invalid("Chỉ so sánh được với bài kiểm tra có cùng số câu theo từng kỹ năng."); + seriesToken = parts[0][2..]; + } + var version = new PlacementAttemptSnapshotDocument + { + SchemaVersion = 2, + AssessmentTargetLevelId = levelId, + TimeLimitMinutes = request.TimeLimitMinutes, + CatalogLevels = [new PlacementSnapshotLevelCatalogItem { JlptLevelId = levelId, JlptLevelName = levelCode, Rank = JlptCurriculum.Rank(levelCode) }], + Questions = questions, + Purpose = ClassQuizPurpose, + CohortId = cohort.Id, + }; + + var quiz = new ClassQuiz + { + CohortId = cohort.Id, + MentorId = actor.Id, + CertificateLevelId = levelId, + Title = title, + TimeLimitMinutes = request.TimeLimitMinutes, + DueAtUtc = dueUtc, + SkillCodes = string.Join(",", skillCounts.Select(s => s.SkillCode)), + QuestionCount = questions.Count, + QuestionSnapshotJson = JsonSerializer.Serialize(version, JsonOptions), + StructureKey = $"s:{seriesToken}|{countsKey}", + Status = "Published", + PublishedAtUtc = now, + CreatedAtUtc = now, + Assignments = recipients.Select(e => new ClassQuizAssignment + { + LearnerId = e.LearnerId, + EnrollmentId = e.Id, + AssignedAtUtc = now, + }).ToList(), + }; + + var sent = new List(); + var locked = false; + await uow.ExecuteInTransactionAsync(async token => + { + if (await ClassRecordLock.IsCompletedUnderLockAsync(uow, cohort.Id, token)) + { + locked = true; + return; + } + await uow.ClassQuizzes.AddAsync(quiz, token); + await uow.SaveChangesAsync(token); + foreach (var a in quiz.Assignments) + { + var key = $"class-quiz:{quiz.Id}:{a.LearnerId}"; + if (await uow.Notifications.AnyAsync(n => n.IdempotencyKey == key, token)) continue; + var notification = new Notification + { + UserId = a.LearnerId, + Title = "Bài kiểm tra mới", + Message = quiz.Title, + Type = "ClassQuiz", + IsRead = false, + CreatedDate = now, + LinkUrl = $"/my-courses/{a.EnrollmentId}/?section=homework&hwTab=quiz&quizAssignmentId={a.Id}", + IdempotencyKey = key, + }; + await uow.Notifications.AddAsync(notification, token); + sent.Add(notification); + } + await uow.SaveChangesAsync(token); + }, cancellationToken); + + if (locked) + return ApiResponse.Fail(ClassRecordLock.Message, HttpStatusCode.Conflict, ClassRecordLock.ErrorCode); + + if (notifications is not null) + { + foreach (var n in sent) + { + try { await notifications.BroadcastPersistedNotificationAsync(n, cancellationToken); } + catch (Exception) when (!cancellationToken.IsCancellationRequested) { /* realtime is best-effort; the row is persisted */ } + } + } + + return await GetMentorQuizDetailAsync(quiz.Id, cancellationToken) is { IsSuccess: true } created + ? ApiResponse.Created(created.Result!) + : ApiResponse.Fail("Đã giao bài kiểm tra nhưng chưa tải lại được chi tiết.", HttpStatusCode.InternalServerError); + } + + // ---------------------------------------------------------------- Mentor: list & detail + + public async Task>> GetMentorQuizzesAsync(int? cohortId, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role is not (Role.Mentor or Role.Admin)) + return ApiResponse>.Fail("Bạn không có quyền xem bài kiểm tra.", HttpStatusCode.Forbidden); + var query = uow.ClassQuizzes.Query().AsNoTracking().Where(q => !q.IsDeleted); + if (actor.Role == Role.Mentor) query = query.Where(q => q.Cohort.MentorId == actor.Id); + if (cohortId.HasValue) query = query.Where(q => q.CohortId == cohortId.Value); + var quizzes = await query.Include(q => q.Cohort).Include(q => q.CertificateLevel).Include(q => q.Assignments) + .OrderByDescending(q => q.PublishedAtUtc).ToListAsync(cancellationToken); + await FinalizeExpiredAsync(quizzes.SelectMany(q => q.Assignments), cancellationToken); + var attempts = await LoadAttemptsAsync(quizzes.SelectMany(q => q.Assignments), cancellationToken); + var completed = await uow.ClassQuizAssignments.Query().AsNoTracking() + .Where(a => quizzes.Select(q => q.Id).Contains(a.QuizId) && a.CompletedAtUtc != null) + .Select(a => a.Id).ToListAsync(cancellationToken); + return ApiResponse>.Success(quizzes.Select(q => ToListItem(q, attempts, completed.ToHashSet())).ToList()); + } + + public async Task> GetMentorQuizDetailAsync(int quizId, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + var quiz = await uow.ClassQuizzes.Query().AsNoTracking() + .Include(q => q.Cohort).Include(q => q.CertificateLevel) + .Include(q => q.Assignments).ThenInclude(a => a.Learner) + .FirstOrDefaultAsync(q => q.Id == quizId && !q.IsDeleted, cancellationToken); + if (quiz is null || (actor.Role == Role.Mentor && quiz.Cohort.MentorId != actor.Id) || actor.Role is not (Role.Mentor or Role.Admin)) + return ApiResponse.NotFound("Không tìm thấy bài kiểm tra."); + await FinalizeExpiredAsync(quiz.Assignments, cancellationToken); + var assignments = await uow.ClassQuizAssignments.Query().AsNoTracking().Include(a => a.Learner) + .Where(a => a.QuizId == quiz.Id).ToListAsync(cancellationToken); + quiz.Assignments = assignments; + var attempts = await LoadAttemptsAsync(assignments, cancellationToken); + var now = DateTime.UtcNow; + var learners = assignments + .Select(a => LearnerRow(quiz, a, attempts.GetValueOrDefault(a.AttemptId ?? 0), now)) + .OrderBy(r => r.LearnerName) + .ToList(); + var version = Version(quiz); + // The Mentor sees the full version incl. answer key. + var questions = version.Questions.Select(q => ToQuestionDto(q, quiz.CertificateLevel.Code, includeAnswer: true, includeSelection: false)).ToList(); + return ApiResponse.Success(new MentorQuizDetailDto( + ToListItem(quiz, attempts, assignments.Where(a => a.CompletedAtUtc != null).Select(a => a.Id).ToHashSet()), + learners, + questions)); + } + + public async Task> GetMentorLearnerResultAsync(int assignmentId, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + var assignment = await LoadAssignmentAsync(assignmentId, cancellationToken); + if (assignment is null || actor.Role is not (Role.Mentor or Role.Admin) + || (actor.Role == Role.Mentor && assignment.Quiz.Cohort.MentorId != actor.Id)) + return ApiResponse.NotFound("Không tìm thấy bài làm."); + return await BuildResultAsync(assignment, releaseAnswers: true, cancellationToken); + } + + // ---------------------------------------------------------------- Learner + + public async Task>> GetLearnerQuizzesAsync(int? cohortId, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Learner) + return ApiResponse>.Fail("Chỉ học viên mới xem được bài kiểm tra của mình.", HttpStatusCode.Forbidden); + var query = uow.ClassQuizAssignments.Query().AsNoTracking() + .Where(a => a.LearnerId == actor.Id && !a.Quiz.IsDeleted && a.Quiz.Status == "Published"); + if (cohortId.HasValue) query = query.Where(a => a.Quiz.CohortId == cohortId.Value); + var assignments = await query.Include(a => a.Quiz).ThenInclude(q => q.Cohort) + .Include(a => a.Quiz).ThenInclude(q => q.CertificateLevel) + .ToListAsync(cancellationToken); + await FinalizeExpiredAsync(assignments, cancellationToken); + var refreshed = await uow.ClassQuizAssignments.Query().AsNoTracking() + .Where(a => assignments.Select(x => x.Id).Contains(a.Id)) + .Select(a => new { a.Id, a.CompletedAtUtc, a.AttemptId }).ToListAsync(cancellationToken); + foreach (var a in assignments) + { + var r = refreshed.First(x => x.Id == a.Id); + a.CompletedAtUtc = r.CompletedAtUtc; + a.AttemptId = r.AttemptId; + } + var attempts = await LoadAttemptsAsync(assignments, cancellationToken); + var now = DateTime.UtcNow; + return ApiResponse>.Success(assignments + .Select(a => Card(a, attempts.GetValueOrDefault(a.AttemptId ?? 0), now)) + .OrderBy(c => c.Status == "Completed" || c.Status == "Overdue" ? 1 : 0) + .ThenBy(c => c.DueAtUtc) + .ToList()); + } + + public async Task> GetLearnerResultAsync(int assignmentId, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + var assignment = await LoadAssignmentAsync(assignmentId, cancellationToken); + if (assignment is null || actor.Role != Role.Learner || assignment.LearnerId != actor.Id) + return ApiResponse.NotFound("Không tìm thấy bài kiểm tra của bạn."); + // Answer keys stay hidden until every recipient has finished or the deadline has passed. + var allDone = await uow.ClassQuizAssignments.Query().AsNoTracking() + .Where(a => a.QuizId == assignment.QuizId).AllAsync(a => a.CompletedAtUtc != null, cancellationToken); + var release = allDone || DateTime.UtcNow >= BusinessDateHelper.EnsureUtc(assignment.Quiz.DueAtUtc); + return await BuildResultAsync(assignment, release, cancellationToken); + } + + // ---------------------------------------------------------------- helpers + + private async Task> BuildResultAsync(ClassQuizAssignment assignment, bool releaseAnswers, CancellationToken ct) + { + await FinalizeExpiredAsync([assignment], ct); + var current = await uow.ClassQuizAssignments.Query().AsNoTracking().Include(a => a.Attempt) + .FirstAsync(a => a.Id == assignment.Id, ct); + if (current.Attempt is not { IsCompleted: true } attempt || !TryDeserializeSnapshot(attempt.QuestionSnapshotJson, out var snapshot)) + return ApiResponse.Fail("Bài kiểm tra chưa được nộp.", HttpStatusCode.Conflict); + assignment.CompletedAtUtc = current.CompletedAtUtc; + assignment.AttemptId = current.AttemptId; + var skills = SkillResults(snapshot); + var correct = skills.Sum(s => s.CorrectCount); + var total = skills.Sum(s => s.TotalCount); + var card = Card(assignment, attempt, DateTime.UtcNow); + var questions = snapshot.Questions + .OrderBy(q => q.Order) + .Select(q => ToQuestionDto(q, assignment.Quiz.CertificateLevel.Code, includeAnswer: releaseAnswers, includeSelection: true)) + .ToList(); + return ApiResponse.Success(new QuizResultDto( + card, correct, total, CourseCompetencyPolicy.Percent(correct, total), + snapshot.CompletedResult?.DurationSeconds ?? 0, + skills, releaseAnswers, releaseAnswers ? null : BusinessDateHelper.EnsureUtc(assignment.Quiz.DueAtUtc), + questions)); + } + + private async Task LoadMentorCohortAsync(int cohortId, CancellationToken ct) + { + var actor = claims.GetUserClaim(); + var cohort = await uow.StudyCohorts.Query().AsNoTracking() + .Include(c => c.Plan).ThenInclude(p => p.CertificateLevel) + .Include(c => c.Enrollments) + .FirstOrDefaultAsync(c => c.Id == cohortId, ct); + if (cohort is null) return null; + if (actor.Role == Role.Mentor && cohort.MentorId != actor.Id) return null; + return actor.Role is Role.Mentor or Role.Admin ? cohort : null; + } + + private async Task LoadAssignmentAsync(int assignmentId, CancellationToken ct) + => await uow.ClassQuizAssignments.Query().AsNoTracking() + .Include(a => a.Quiz).ThenInclude(q => q.Cohort) + .Include(a => a.Quiz).ThenInclude(q => q.CertificateLevel) + .FirstOrDefaultAsync(a => a.Id == assignmentId && !a.Quiz.IsDeleted, ct); + + private sealed record BankQuestion(MockQuestion Question, string SkillCode, string TestTitle); + + /// Approved, auto-gradable single-choice questions of the level, excluding the protected assessment bank. + private async Task> LoadBankQuestionsAsync(int levelId, IReadOnlyCollection? onlyIds, CancellationToken ct) + { + var approved = MockContentReviewState.ApprovedQuestionIds(uow); + var query = uow.QuestionBankItems.Query().AsNoTracking() + .Where(q => approved.Contains(q.Id) + && q.MockTestSection != null + && q.MockTestSection.MockTest.CertificateLevelId == levelId + && q.MockTestSection.MockTest.ExamKind != ExamKind.Placement + && !q.MockTestSection.MockTest.IsArchivedVersion); + if (onlyIds is not null) query = query.Where(q => onlyIds.Contains(q.Id)); + var rows = await query + .Include(q => q.Options) + .Include(q => q.Passage) + .Include(q => q.MockTestSection!).ThenInclude(s => s.LanguageSkill) + .Include(q => q.MockTestSection!).ThenInclude(s => s.MockTest) + .AsSplitQuery() + .ToListAsync(ct); + var result = new List(); + foreach (var q in rows) + { + if (SentenceOrdering.IsType(q.QuestionType) || !HasUsablePrompt(q)) continue; + var skill = JlptSkillAssessmentPolicy.Classify(q.MockTestSection!.LanguageSkill?.Name); + if (skill is null) continue; + var options = (q.Options ?? []).Where(o => !o.IsDeleted && (!string.IsNullOrWhiteSpace(o.OptionText) || !string.IsNullOrWhiteSpace(o.ImageUrl))).ToList(); + if (options.Count < 2 || options.Count(o => o.IsCorrect) != 1) continue; + if (skill == JlptStudySkill.Listening && string.IsNullOrWhiteSpace(ResolveQuestionAudioUrl(q))) continue; + if (q.PassageId.HasValue && (q.Passage is null || q.Passage.IsDeleted)) continue; + result.Add(new BankQuestion(q, skill.Value.ToString().ToLowerInvariant(), q.MockTestSection.MockTest.Title ?? string.Empty)); + } + return result + .OrderBy(b => Array.IndexOf(SkillOrder, b.SkillCode)) + .ThenBy(b => b.Question.PassageId ?? int.MaxValue) + .ThenBy(b => b.Question.Id) + .ToList(); + } + + private static PlacementSnapshotQuestionItem FromBank(BankQuestion b, int levelId, string levelCode) + { + var q = b.Question; + var options = (q.Options ?? []).Where(o => !o.IsDeleted && (!string.IsNullOrWhiteSpace(o.OptionText) || !string.IsNullOrWhiteSpace(o.ImageUrl))) + .OrderBy(o => o.SortOrder).ThenBy(o => o.Id).ToList(); + return new PlacementSnapshotQuestionItem + { + QuestionId = q.Id, + MockTestId = q.MockTestSection!.MockTestId, + MockTestSectionId = q.MockTestSection.Id, + SectionTitle = q.MockTestSection.Title ?? SkillLabel(b.SkillCode), + SectionOrder = Array.IndexOf(SkillOrder, b.SkillCode) + 1, + LanguageSkillName = q.MockTestSection.LanguageSkill?.Name ?? SkillEnglish(b.SkillCode), + JlptLevelId = levelId, + JlptLevelName = levelCode, + Content = q.QuestionText ?? string.Empty, + AudioUrl = ResolveQuestionAudioUrl(q), + ImageUrl = q.ImageUrl, + PassageId = q.PassageId, + PassageTitle = q.Passage?.Title, + PassageText = q.Passage?.PassageText, + PassageInstructions = q.Passage?.Instructions, + PassageImageUrl = q.Passage?.ImageUrl, + CorrectOptionId = options.First(o => o.IsCorrect).Id, + Explanation = q.Explanation, + Topic = q.Topic, + Options = options.Select(o => new PlacementSnapshotOptionItem + { + OptionId = o.Id, + Content = o.OptionText ?? string.Empty, + ImageUrl = o.ImageUrl, + Order = o.SortOrder, + IsCorrect = o.IsCorrect, + }).ToList(), + }; + } + + private static QuizQuestionDto ToBankDto(BankQuestion b, string levelCode) + { + var item = FromBank(b, 0, levelCode); + var dto = ToQuestionDto(item, levelCode, includeAnswer: true, includeSelection: false); + return dto with { Difficulty = b.Question.Difficulty, Source = b.TestTitle }; + } + + private static QuizQuestionDto ToQuestionDto(PlacementSnapshotQuestionItem q, string levelCode, bool includeAnswer, bool includeSelection) + => new( + q.QuestionId, + SkillCodeOf(q.LanguageSkillName), + levelCode.Trim().ToUpperInvariant(), + q.Content, + q.ImageUrl, + q.AudioUrl, + q.PassageId, + q.PassageTitle, + q.PassageText, + q.Topic, + null, + null, + q.MockTestSectionId <= 0, + q.Options.OrderBy(o => o.Order).Select(o => new QuizOptionDto(o.OptionId, o.Content, o.ImageUrl, includeAnswer ? o.IsCorrect : null)).ToList(), + includeAnswer ? q.CorrectOptionId : null, + includeSelection ? q.SelectedOptionId : null, + includeSelection && includeAnswer ? q.IsCorrect : null, + includeAnswer ? q.Explanation : null); + + private async Task FinalizeExpiredAsync(IEnumerable assignments, CancellationToken ct) + { + var ids = assignments.Where(a => a.AttemptId.HasValue && a.CompletedAtUtc is null).Select(a => a.AttemptId!.Value).Distinct().ToList(); + if (ids.Count > 0) await engine.FinalizeExpiredClassQuizAttemptsAsync(ids, ct); + } + + private async Task> LoadAttemptsAsync(IEnumerable assignments, CancellationToken ct) + { + var ids = assignments.Where(a => a.AttemptId.HasValue).Select(a => a.AttemptId!.Value).Distinct().ToList(); + if (ids.Count == 0) return []; + // Re-read after finalisation so assignment completion and scores are current. + return await uow.MockTestAttempts.Query().AsNoTracking().Where(a => ids.Contains(a.Id)).ToDictionaryAsync(a => a.Id, ct); + } + + private static MentorQuizListItemDto ToListItem(ClassQuiz quiz, IReadOnlyDictionary attempts, IReadOnlySet completedAssignmentIds) + { + var scores = quiz.Assignments + .Where(a => a.AttemptId.HasValue && attempts.TryGetValue(a.AttemptId.Value, out var at) && at.IsCompleted) + .Select(a => OverallPercent(attempts[a.AttemptId!.Value])) + .Where(p => p.HasValue) + .Select(p => p!.Value) + .ToList(); + var version = Version(quiz); + return new MentorQuizListItemDto( + quiz.Id, quiz.CohortId, quiz.Cohort?.Name ?? string.Empty, quiz.Title, + quiz.CertificateLevel?.Code ?? string.Empty, + SkillCounts(version.Questions), quiz.QuestionCount, quiz.TimeLimitMinutes, + BusinessDateHelper.EnsureUtc(quiz.DueAtUtc), BusinessDateHelper.EnsureUtc(quiz.PublishedAtUtc), + quiz.Assignments.Count, + quiz.Assignments.Count(a => completedAssignmentIds.Contains(a.Id) || a.CompletedAtUtc != null), + scores.Count > 0 ? Math.Round(scores.Average(), 1) : null, + DateTime.UtcNow >= BusinessDateHelper.EnsureUtc(quiz.DueAtUtc) || quiz.Cohort?.Status == "Completed" ? "Closed" : "Open", + quiz.Cohort?.Status == "Completed", + quiz.StructureKey); + } + + private static QuizLearnerRowDto LearnerRow(ClassQuiz quiz, ClassQuizAssignment a, MockTestAttempt? attempt, DateTime now) + { + var status = StatusOf(quiz, a, attempt, now); + List skills = []; + int? correct = null, total = null; + double? score = null; + if (attempt is { IsCompleted: true } && TryDeserializeSnapshot(attempt.QuestionSnapshotJson, out var snap)) + { + skills = SkillResults(snap); + correct = skills.Sum(s => s.CorrectCount); + total = skills.Sum(s => s.TotalCount); + score = CourseCompetencyPolicy.Percent(correct.Value, total.Value); + } + return new QuizLearnerRowDto( + a.Id, a.LearnerId, $"{a.Learner?.FirstName} {a.Learner?.LastName}".Trim(), a.Learner?.AvatarUrl, a.EnrollmentId, + status, + attempt is not null ? BusinessDateHelper.EnsureUtc(attempt.StartedAt) : null, + a.CompletedAtUtc.HasValue ? BusinessDateHelper.EnsureUtc(a.CompletedAtUtc.Value) : null, + score, correct, total, skills); + } + + private static LearnerQuizCardDto Card(ClassQuizAssignment a, MockTestAttempt? attempt, DateTime now) + { + var version = Version(a.Quiz); + return new LearnerQuizCardDto( + a.Id, a.QuizId, a.Quiz.CohortId, a.EnrollmentId, a.Quiz.Cohort?.Name ?? string.Empty, a.Quiz.Title, + a.Quiz.CertificateLevel?.Code ?? string.Empty, + SkillCounts(version.Questions), a.Quiz.QuestionCount, a.Quiz.TimeLimitMinutes, + BusinessDateHelper.EnsureUtc(a.Quiz.DueAtUtc), + StatusOf(a.Quiz, a, attempt, now), + a.AttemptId, + a.CompletedAtUtc.HasValue ? BusinessDateHelper.EnsureUtc(a.CompletedAtUtc.Value) : null, + attempt is { IsCompleted: true } ? OverallPercent(attempt) : null, + a.Quiz.Cohort?.Status == "Completed"); + } + + /// NotStarted | InProgress | Completed | Overdue (deadline passed without a submitted attempt). + private static string StatusOf(ClassQuiz quiz, ClassQuizAssignment a, MockTestAttempt? attempt, DateTime now) + { + if (a.CompletedAtUtc.HasValue || attempt is { IsCompleted: true }) return "Completed"; + if (attempt is not null && attempt.ExpiresAt is { } exp && BusinessDateHelper.EnsureUtc(exp) > now) return "InProgress"; + // A completed class closes every quiz that was not finished (no new attempt is possible). + return now >= BusinessDateHelper.EnsureUtc(quiz.DueAtUtc) || quiz.Cohort?.Status == "Completed" ? "Overdue" : "NotStarted"; + } + + internal static List SkillResults(PlacementAttemptSnapshotDocument snapshot) + => CourseCompetencyPolicy.ScopedSkills(snapshot, null) + .OrderBy(kv => Array.IndexOf(SkillOrder, kv.Key)) + .Select(kv => new QuizSkillResultDto(kv.Key, kv.Value.Correct, kv.Value.Total, CourseCompetencyPolicy.Percent(kv.Value.Correct, kv.Value.Total))) + .ToList(); + + private static double? OverallPercent(MockTestAttempt attempt) + { + if (!TryDeserializeSnapshot(attempt.QuestionSnapshotJson, out var snap)) return attempt.TotalScore; + var skills = SkillResults(snap); + var total = skills.Sum(s => s.TotalCount); + return total > 0 ? CourseCompetencyPolicy.Percent(skills.Sum(s => s.CorrectCount), total) : null; + } + + private static PlacementAttemptSnapshotDocument Version(ClassQuiz quiz) + => TryDeserializeSnapshot(quiz.QuestionSnapshotJson, out var doc) ? doc : new PlacementAttemptSnapshotDocument(); + + internal static List SkillCounts(IEnumerable questions) + => questions + .GroupBy(q => SkillCodeOf(q.LanguageSkillName)) + .Where(g => SkillOrder.Contains(g.Key)) + .OrderBy(g => Array.IndexOf(SkillOrder, g.Key)) + .Select(g => new QuizSkillCountDto(g.Key, g.Count())) + .ToList(); + + internal static string StructureKeyOf(IEnumerable counts) + => string.Join(",", counts.OrderBy(c => c.SkillCode, StringComparer.Ordinal).Select(c => $"{c.SkillCode}:{c.QuestionCount}")); + + private static string SkillCodeOf(string? name) + => JlptSkillAssessmentPolicy.Classify(name)?.ToString().ToLowerInvariant() ?? (name ?? string.Empty).Trim().ToLowerInvariant(); + + private static int SkillRank(string? name) => Array.IndexOf(SkillOrder, SkillCodeOf(name)) is var i && i >= 0 ? i : 99; + + private static string SkillEnglish(string code) => code switch + { + "vocabulary" => "Vocabulary", + "grammar" => "Grammar", + "reading" => "Reading", + _ => "Listening", + }; + + private static string SkillLabel(string code) => code switch + { + "vocabulary" => "Từ vựng", + "grammar" => "Ngữ pháp", + "reading" => "Đọc hiểu", + _ => "Nghe hiểu", + }; + + /// Synthetic option ids for Mentor-authored questions, far outside the bank's identity range. + private static int CustomOptionId(int customIndex, int optionIndex) => 1_800_000_000 + customIndex * 10 + optionIndex + 1; + + private static bool IsValidMediaUrl(string? url) + => !string.IsNullOrWhiteSpace(url) + && (Uri.TryCreate(url.Trim(), UriKind.Absolute, out var u) ? u.Scheme is "http" or "https" : url.Trim().StartsWith('/')); + + private static ApiResponse Invalid(string message) => ApiResponse.Fail(message); +} diff --git a/RikiPath.Application/Services/ClassRecordLock.cs b/RikiPath.Application/Services/ClassRecordLock.cs new file mode 100644 index 0000000..ba2ee9a --- /dev/null +++ b/RikiPath.Application/Services/ClassRecordLock.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; + +namespace RikiPath.Application.Services; + +/// +/// Single rule for the learning-record lock of a completed class: once a class (StudyCohort) is "Completed", +/// homework, in-class quizzes, attendance and schedule data become read-only for every role (Admin included). +/// Post-course flows (end-of-course assessment, Mentor review, complaints, retake support) are not learning +/// records and stay open. Use inside a transaction so a write can never +/// slip in after the class-completion transaction (both take the same class advisory lock). +/// +public static class ClassRecordLock +{ + public const string ErrorCode = "CLASS_COMPLETED_READ_ONLY"; + public const string Message = "Lớp học đã hoàn thành. Dữ liệu học tập của lớp chỉ còn quyền xem."; + + public static async Task IsCompletedAsync(IUnitOfWork uow, int? cohortId, CancellationToken ct) + => cohortId is int id && await uow.StudyCohorts.Query().AsNoTracking() + .AnyAsync(c => c.Id == id && c.Status == "Completed", ct); + + /// Takes the class lock (transaction-scoped) and then re-reads the class status. + public static async Task IsCompletedUnderLockAsync(IUnitOfWork uow, int? cohortId, CancellationToken ct) + { + if (cohortId is not int id) return false; + await uow.StudyCourses.LockCohortAsync(id, ct); + return await IsCompletedAsync(uow, id, ct); + } + + public static async Task CohortOfHomeworkAsync(IUnitOfWork uow, int assignmentId, CancellationToken ct) + => await uow.HomeworkAssignments.Query().AsNoTracking() + .Where(h => h.Id == assignmentId) + .Select(h => h.CohortId ?? (h.StudyCourse != null ? h.StudyCourse.CohortId : null)) + .FirstOrDefaultAsync(ct); + + public static async Task CohortOfEnrollmentAsync(IUnitOfWork uow, int enrollmentId, CancellationToken ct) + => await uow.StudyCourses.Query().AsNoTracking() + .Where(c => c.Id == enrollmentId).Select(c => c.CohortId).FirstOrDefaultAsync(ct); + + public static async Task CohortOfQuizAssignmentAsync(IUnitOfWork uow, int quizAssignmentId, CancellationToken ct) + => await uow.ClassQuizAssignments.Query().AsNoTracking() + .Where(a => a.Id == quizAssignmentId).Select(a => (int?)a.Quiz.CohortId).FirstOrDefaultAsync(ct); + + public static async Task CohortOfQuizAsync(IUnitOfWork uow, int quizId, CancellationToken ct) + => await uow.ClassQuizzes.Query().AsNoTracking() + .Where(q => q.Id == quizId).Select(q => (int?)q.CohortId).FirstOrDefaultAsync(ct); +} diff --git a/RikiPath.Application/Services/ClassSessionLifecycleService.cs b/RikiPath.Application/Services/ClassSessionLifecycleService.cs index 1571de4..4eb7359 100644 --- a/RikiPath.Application/Services/ClassSessionLifecycleService.cs +++ b/RikiPath.Application/Services/ClassSessionLifecycleService.cs @@ -78,6 +78,7 @@ await uow.ExecuteInTransactionAsync(async token => .Include(c => c.Enrollments).ThenInclude(e => e.Sessions) .AsSplitQuery().SingleOrDefaultAsync(c => c.Id == cohortId, token); if (cohort is null) throw new LifecycleConflict("Không tìm thấy lớp học."); + if (cohort.Status == "Completed") throw new LifecycleConflict(ClassRecordLock.Message); var session = cohort.Sessions.SingleOrDefault(s => s.Id == sessionId); if (session is null) throw new LifecycleConflict("Buổi học không hợp lệ."); // Mentor thực dạy của khung giờ chịu trách nhiệm điểm danh (giữ đúng sau khi thay Giáo viên). @@ -261,9 +262,9 @@ await uow.ExecuteInTransactionAsync(async token => UserId = id, Title = "Khóa học đã hoàn thành", Message = id == cohort.MentorId ? $"{NotificationDisplayNormalizer.ClassSubject(cohort.Name)} đã hoàn thành toàn bộ buổi học." - : $"{NotificationDisplayNormalizer.ClassSubject(cohort.Name)} đã hoàn thành toàn bộ buổi học; bạn có thể đánh giá Giáo viên.", + : $"{NotificationDisplayNormalizer.ClassSubject(cohort.Name)} đã hoàn thành toàn bộ buổi học; bạn có thể làm bài đánh giá cuối khóa và đánh giá Giáo viên.", Type = "CohortCompleted", - LinkUrl = id == cohort.MentorId ? $"/mentor-study-courses/{cohort.Id}/" : $"/my-courses/{roster.First(c => c.LearnerId == id).Id}/" + LinkUrl = id == cohort.MentorId ? $"/mentor-study-courses/{cohort.Id}/" : $"/my-courses/{roster.First(c => c.LearnerId == id).Id}/?section=competency&tab=progress" }) }), CreatedAtUtc = DateTime.UtcNow, AvailableAtUtc = DateTime.UtcNow }); } diff --git a/RikiPath.Application/Services/ContentApprovalService.cs b/RikiPath.Application/Services/ContentApprovalService.cs index 1fb3d8d..a63a3c1 100644 --- a/RikiPath.Application/Services/ContentApprovalService.cs +++ b/RikiPath.Application/Services/ContentApprovalService.cs @@ -917,6 +917,9 @@ private async Task ApplyReviewAsync( case ImportEntityType.PracticeSet: await ApplyMockTestApprovalAsync(req, cancellationToken); break; + case ImportEntityType.SrsCardTemplate: + await ApplySrsCardTemplateApprovalAsync(req, cancellationToken); + break; default: throw new NotSupportedException($"Chưa hỗ trợ phê duyệt tự động cho loại {req.EntityType}."); } @@ -1259,7 +1262,9 @@ private async Task ApplyPracticeExerciseApprovalAsync(ContentApprovalRequest req .Where(t => !t.IsDeleted && (t.CertificateLevelId == resolvedLevelId || resolvedLevelId == 0 || t.CertificateLevelId == null)) .OrderByDescending(t => t.CertificateLevelId == resolvedLevelId) .ToListAsync(cancellationToken); - var matchedTopic = topicRow.FirstOrDefault(t => string.Equals(t.Title.Trim().Normalize(), normalizedTopic, StringComparison.OrdinalIgnoreCase)); + var matchedTopic = topicRow.FirstOrDefault(t => + string.Equals(t.Title.Trim().Normalize(), normalizedTopic, StringComparison.OrdinalIgnoreCase) || + (!string.IsNullOrWhiteSpace(t.StageCode) && string.Equals(t.StageCode.Trim(), p.TopicTitle.Trim(), StringComparison.OrdinalIgnoreCase))); if (matchedTopic is null) throw new InvalidOperationException($"Không tìm thấy Topic/Chặng '{p.TopicTitle}' để lưu GroupQuiz."); resolvedTopicId = matchedTopic.Id; @@ -1291,7 +1296,7 @@ static List MapQuestions(IEnumerable 0 ? resolvedLevelId : null, LanguageSkillId = p.LanguageSkillId, Questions = MapQuestions(p.Questions) - }, cancellationToken); + }; + await unitOfWork.PracticeExercises.AddAsync(createdExercise, cancellationToken); + await unitOfWork.SaveChangesAsync(cancellationToken); + req.TargetEntityId = createdExercise.Id; return; } @@ -1605,6 +1613,8 @@ private async Task ApplyMockTestApprovalAsync(ContentApprovalRequest req, Cancel CertificateLevelId = p.CertificateLevelId, ExamKind = resolvedKind, IsManagedWorkflow = true, + SourceType = string.IsNullOrWhiteSpace(req.SourceType) ? "ImportExcel" : req.SourceType, + SourceReference = string.IsNullOrWhiteSpace(req.SourceReference) ? req.RowKey : req.SourceReference, Sections = p.Sections!.Select(s => CreateImportedSection(s, sectionIdByCode)).ToList() }; @@ -1717,6 +1727,63 @@ private static MockTestSection CreateImportedSection(MockTestSectionPayloadRespo } #endregion + private async Task ApplySrsCardTemplateApprovalAsync(ContentApprovalRequest req, CancellationToken cancellationToken) + { + var p = JsonSerializer.Deserialize(req.PayloadJson, JsonOptions) + ?? throw new InvalidOperationException("Payload thẻ mẫu SRS rỗng."); + if (string.IsNullOrWhiteSpace(p.FrontText) || string.IsNullOrWhiteSpace(p.BackText)) + throw new InvalidOperationException("Thẻ mẫu SRS thiếu mặt trước hoặc mặt sau."); + + var normalizedKey = string.IsNullOrWhiteSpace(p.NormalizedContentKey) + ? $"{p.CertificateLevelCode}:{p.CardType}:{p.FrontText.Trim()}" + : p.NormalizedContentKey.Trim(); + if (normalizedKey.Length > 300) normalizedKey = normalizedKey[..300]; + + var entity = req.TargetEntityId.HasValue + ? await unitOfWork.SrsCardTemplates.GetByIdAsync(req.TargetEntityId.Value, cancellationToken) + : null; + entity ??= await unitOfWork.SrsCardTemplates.FirstOrDefaultAsync( + x => !x.IsDeleted && x.NormalizedContentKey == normalizedKey, cancellationToken); + + var reviewer = claimService.GetUserClaim(); + var now = DateTime.UtcNow; + + if (entity is null) + { + entity = new SrsCardTemplate + { + NormalizedContentKey = normalizedKey, + SubmittedByUserId = req.SubmittedByUserId, + SubmittedAtUtc = req.SubmittedAt, + Version = 1, + }; + await unitOfWork.SrsCardTemplates.AddAsync(entity, cancellationToken); + } + else + { + entity.Version++; + unitOfWork.SrsCardTemplates.Update(entity); + } + + entity.CardType = p.CardType.Length > 30 ? p.CardType[..30] : p.CardType; + entity.FrontText = p.FrontText.Length > 500 ? p.FrontText[..500] : p.FrontText; + entity.BackText = p.BackText.Length > 1000 ? p.BackText[..1000] : p.BackText; + entity.Reading = p.Reading is { Length: > 300 } ? p.Reading[..300] : p.Reading; + entity.Meaning = p.Meaning is { Length: > 500 } ? p.Meaning[..500] : p.Meaning; + entity.ExampleSentence = p.ExampleSentence is { Length: > 1000 } ? p.ExampleSentence[..1000] : p.ExampleSentence; + entity.ExampleMeaning = p.ExampleMeaning is { Length: > 1000 } ? p.ExampleMeaning[..1000] : p.ExampleMeaning; + entity.UsageNotes = p.UsageNotes is { Length: > 2000 } ? p.UsageNotes[..2000] : p.UsageNotes; + entity.AudioUrl = p.AudioUrl is { Length: > 1000 } ? p.AudioUrl[..1000] : p.AudioUrl; + entity.CertificateLevelId = p.CertificateLevelId > 0 ? p.CertificateLevelId : null; + entity.JlptLevel = p.CertificateLevelCode.Length > 10 ? p.CertificateLevelCode[..10] : p.CertificateLevelCode; + entity.Status = ContentStatus.Published; + entity.ReviewedByAdminId = reviewer.Id > 0 ? reviewer.Id : null; + entity.ReviewedAtUtc = now; + + await unitOfWork.SaveChangesAsync(cancellationToken); + req.TargetEntityId = entity.Id; + } + private static string NormalizeMockQuestionType(string? questionType) => JlptMockQuestionFormats.NormalizeQuestionType(questionType) ?? throw new InvalidOperationException($"Dạng câu MockTest không hỗ trợ: {questionType}."); diff --git a/RikiPath.Application/Services/CourseCompetencyPolicy.cs b/RikiPath.Application/Services/CourseCompetencyPolicy.cs new file mode 100644 index 0000000..83664ff --- /dev/null +++ b/RikiPath.Application/Services/CourseCompetencyPolicy.cs @@ -0,0 +1,134 @@ +using RikiPath.Application.Responses.PlacementTests; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Application.Services; + +/// +/// Single source of the Stage 5 business rules shared by the Learner assessment flow and the +/// Mentor/Learner competency profile: who may take the end-of-course assessment, which attempt is the official +/// milestone, and how a pre-course vs end-of-course comparison is scoped so both sides use the same scale. +/// +internal static class CourseCompetencyPolicy +{ + /// One official end-of-course attempt per class enrollment (the first completed attempt is the milestone). + public const int FinalAttemptLimit = 1; + + /// Same pass mark the assessment engine uses to recognise a tested JLPT level (60% correct). + public const double FinalPassThresholdPercent = 60d; + + /// A skill change below this many percentage points is reported as "unchanged" (same rule as before). + public const double MeaningfulDeltaPoints = 2d; + + public sealed record FinalAttemptState( + string Availability, + MockTestAttempt? Active, + MockTestAttempt? PendingSubmission, + MockTestAttempt? Official, + PracticeTestService.PlacementAttemptSnapshotDocument? OfficialSnapshot, + int AttemptsUsed); + + public static bool IsClassCompleted(StudyCourse course) + => course.Cohort is not null + ? string.Equals(course.Cohort.Status, "Completed", StringComparison.OrdinalIgnoreCase) + : string.Equals(course.Status, "Completed", StringComparison.OrdinalIgnoreCase); + + public static bool IsEligibleEnrollment(StudyCourse course) + => course.PaymentStatus is "Paid" or "PartiallyRefunded" + && course.Status is "Active" or "Completed"; + + /// End-of-course attempts that belong to exactly this class enrollment (link stored in the attempt snapshot). + public static List<(MockTestAttempt Attempt, PracticeTestService.PlacementAttemptSnapshotDocument Snapshot)> FinalAttemptsFor( + IEnumerable attempts, int cohortId, int enrollmentId) + => attempts + .Where(a => a.AttemptKind == AttemptKind.CourseAssessment && !a.IsDeleted) + .Select(a => (Ok: PracticeTestService.TryDeserializeSnapshot(a.QuestionSnapshotJson, out var doc), Attempt: a, Snapshot: doc)) + .Where(x => x.Ok + && string.Equals(x.Snapshot.Purpose, PracticeTestService.CourseFinalPurpose, StringComparison.Ordinal) + && x.Snapshot.CohortId == cohortId + && x.Snapshot.EnrollmentId == enrollmentId) + .Select(x => (x.Attempt, x.Snapshot)) + .ToList(); + + public static FinalAttemptState ResolveFinalState( + bool classCompleted, + bool eligibleEnrollment, + IReadOnlyCollection<(MockTestAttempt Attempt, PracticeTestService.PlacementAttemptSnapshotDocument Snapshot)> forEnrollment, + DateTime nowUtc) + { + var official = forEnrollment + .Where(x => x.Attempt.IsCompleted && x.Attempt.TotalScore.HasValue && x.Snapshot.CompletedResult is not null) + .OrderBy(x => x.Attempt.SubmittedAt ?? x.Attempt.StartedAt) + .ThenBy(x => x.Attempt.Id) + .FirstOrDefault(); + var open = forEnrollment.Where(x => !x.Attempt.IsCompleted).OrderByDescending(x => x.Attempt.Id).ToList(); + var active = open.FirstOrDefault(x => x.Attempt.ExpiresAt.HasValue + && BusinessDateHelper.EnsureUtc(x.Attempt.ExpiresAt.Value) > nowUtc).Attempt; + var pending = open.FirstOrDefault(x => !x.Attempt.ExpiresAt.HasValue + || BusinessDateHelper.EnsureUtc(x.Attempt.ExpiresAt.Value) <= nowUtc).Attempt; + var used = forEnrollment.Count; + + string availability; + if (official.Attempt is not null) availability = CourseFinalAvailability.Completed; + else if (active is not null) availability = CourseFinalAvailability.InProgress; + else if (pending is not null) availability = CourseFinalAvailability.PendingSubmission; + else if (!classCompleted) availability = CourseFinalAvailability.NotOpen; + else if (!eligibleEnrollment) availability = CourseFinalAvailability.NotEligible; + else availability = CourseFinalAvailability.Available; + + return new FinalAttemptState(availability, active, pending, official.Attempt, official.Snapshot, used); + } + + /// + /// A pre-course result pinned to this class enrollment (CourseAssessment attempt with Purpose "CourseBaseline"), + /// completed before the class started. When present it is the class baseline and takes precedence over the + /// learner's global Placement history. + /// + public static MockTestAttempt? PinnedBaseline( + IEnumerable attempts, int cohortId, int enrollmentId, DateTime? cutoffUtc) + => attempts + .Where(a => a.AttemptKind == AttemptKind.CourseAssessment && !a.IsDeleted && a.IsCompleted && a.TotalScore.HasValue) + .Where(a => cutoffUtc is null || BusinessDateHelper.EnsureUtc(a.SubmittedAt ?? a.StartedAt) < cutoffUtc.Value) + .Select(a => (Ok: PracticeTestService.TryDeserializeSnapshot(a.QuestionSnapshotJson, out var doc), Attempt: a, Snapshot: doc)) + .Where(x => x.Ok + && string.Equals(x.Snapshot.Purpose, PracticeTestService.CourseBaselinePurpose, StringComparison.Ordinal) + && x.Snapshot.CohortId == cohortId + && x.Snapshot.EnrollmentId == enrollmentId) + .OrderByDescending(x => x.Attempt.SubmittedAt ?? x.Attempt.StartedAt) + .ThenByDescending(x => x.Attempt.Id) + .Select(x => x.Attempt) + .FirstOrDefault(); + + public static string NormalizeLevel(string? code) => (code ?? string.Empty).Trim().ToUpperInvariant(); + + public static HashSet TestedLevels(PracticeTestService.PlacementAttemptSnapshotDocument snapshot) + => snapshot.Questions + .Select(q => NormalizeLevel(q.JlptLevelName)) + .Where(code => JlptCurriculum.Rank(code) > 0) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + /// + /// Correct / total per assessed JLPT skill, restricted to the given JLPT levels. Listening questions without + /// audio are excluded (never scored). Skills with no question in scope are absent — never reported as 0%. + /// + public static Dictionary ScopedSkills( + PracticeTestService.PlacementAttemptSnapshotDocument snapshot, + IReadOnlySet? levels) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var q in snapshot.Questions) + { + if (levels is not null && !levels.Contains(NormalizeLevel(q.JlptLevelName))) continue; + var skill = JlptSkillAssessmentPolicy.Classify( + string.IsNullOrWhiteSpace(q.LanguageSkillName) ? q.SectionTitle : q.LanguageSkillName); + if (skill is null) continue; + if (skill == JlptStudySkill.Listening && string.IsNullOrWhiteSpace(q.AudioUrl)) continue; + var key = skill.Value.ToString().ToLowerInvariant(); + var current = result.GetValueOrDefault(key); + result[key] = (current.Correct + (q.IsCorrect ? 1 : 0), current.Total + 1); + } + return result; + } + + public static double Percent(int correct, int total) => total > 0 ? Math.Round(correct * 100d / total, 1, MidpointRounding.AwayFromZero) : 0d; +} diff --git a/RikiPath.Application/Services/HomeworkGradingService.cs b/RikiPath.Application/Services/HomeworkGradingService.cs index 7f66d31..86c7507 100644 --- a/RikiPath.Application/Services/HomeworkGradingService.cs +++ b/RikiPath.Application/Services/HomeworkGradingService.cs @@ -171,6 +171,8 @@ public async Task> CreateDraftAsync(int id, Ca .SingleOrDefaultAsync(a => a.Id == id, ct); if (assignment?.Submission is not { IsDeleted: false } submission) return ApiResponse.NotFound("Chưa tìm thấy bài nộp của học viên."); + if (await ClassRecordLock.IsCompletedAsync(unit, assignment.CohortId, ct)) + return ApiResponse.Fail(ClassRecordLock.Message, HttpStatusCode.Conflict, ClassRecordLock.ErrorCode); if (grader is null) return await DraftUnavailableAsync(assignment, "Tính năng chấm bài AI chưa sẵn sàng. Giáo viên có thể chấm trực tiếp.", HttpStatusCode.ServiceUnavailable, ct); @@ -417,6 +419,11 @@ await unit.ExecuteInTransactionAsync(async token => { await unit.UserAccounts.GetByIdForUpdateAsync(learnerId.Value, token); var assignment = await query.AsTracking().Include(a => a.Submission).ThenInclude(s => s!.GradingResult).SingleOrDefaultAsync(token); + if (assignment is not null && await ClassRecordLock.IsCompletedUnderLockAsync(unit, assignment.CohortId, token)) + { + response = ApiResponse.Fail(ClassRecordLock.Message, HttpStatusCode.Conflict, ClassRecordLock.ErrorCode); + return; + } if (assignment?.Submission is not { IsDeleted: false } submission) return; if (submission.Id != request.SubmissionId) { @@ -457,7 +464,8 @@ await unit.ExecuteInTransactionAsync(async token => assignment.MentorScore = score; assignment.MentorFeedback = feedback; assignment.Passed = passed ?? assignment.Passed; - assignment.PublishedFeedbackAtUtc = grade.GradedAt; + // First publication time (KPI response SLA); later edits only move GradingResult.GradedAt. + assignment.PublishedFeedbackAtUtc ??= grade.GradedAt; assignment.PublishedByMentorId = actor.Id; persistedNotification = await NotifyAsync(assignment.LearnerId, "Đã có kết quả bài tập", assignment.Title, assignment.CohortId, token, assignmentId: assignment.Id); diff --git a/RikiPath.Application/Services/HomeworkService.cs b/RikiPath.Application/Services/HomeworkService.cs index fb0a67f..51dfa2d 100644 --- a/RikiPath.Application/Services/HomeworkService.cs +++ b/RikiPath.Application/Services/HomeworkService.cs @@ -399,7 +399,8 @@ public async Task> GetAssignmentsAsync(int? learnerId, Cancel StudyCourseId: item.StudyCourseId, CohortName: item.Cohort?.Name, Attachments: VisibleAttachments(item, user.Role), - LearnerAvatarUrl: item.Learner?.AvatarUrl), item, user.Role)).ToList(); + LearnerAvatarUrl: item.Learner?.AvatarUrl, + ClassCompleted: item.Cohort?.Status == "Completed"), item, user.Role)).ToList(); } public async Task> GetAssignedLessonAsync(int assignmentId, int lessonId, CancellationToken ct) @@ -448,6 +449,11 @@ await unit.ExecuteInTransactionAsync(async token => .Include(item => item.Exercises).Include(item => item.HomeworkAssignmentLessons) .SingleOrDefaultAsync(item => item.Id == assignmentId && item.LearnerId == userId && !item.IsDeleted, token); if (assignment is null) return; + if (await ClassRecordLock.IsCompletedUnderLockAsync(unit, assignment.CohortId, token)) + { + response = ApiResponse.Fail(ClassRecordLock.Message, HttpStatusCode.Conflict, ClassRecordLock.ErrorCode); + return; + } if (assignment.Status == "Graded" || assignment.PublishedFeedbackAtUtc.HasValue || assignment.Submission?.GradingResult is { IsDeleted: false }) { diff --git a/RikiPath.Application/Services/ListeningAudioFilePolicy.cs b/RikiPath.Application/Services/ListeningAudioFilePolicy.cs index ce30564..1941bcb 100644 --- a/RikiPath.Application/Services/ListeningAudioFilePolicy.cs +++ b/RikiPath.Application/Services/ListeningAudioFilePolicy.cs @@ -6,6 +6,27 @@ public static class ListeningAudioFilePolicy // Keep the limit high enough for the upload flow; each request still accepts one file. public const int MaxBytes = 500 * 1024 * 1024; + public static bool IsSupportedExtension(string? extension) => + string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase) || + string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase); + + public static string GetContentType(string? extension) => + string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase) ? "audio/wav" : "audio/mpeg"; + + public static async Task HasSupportedAudioHeaderAsync(Stream audio, string fileName, CancellationToken ct) => + string.Equals(Path.GetExtension(fileName), ".wav", StringComparison.OrdinalIgnoreCase) + ? await HasWavHeaderAsync(audio, ct) + : await HasMp3HeaderAsync(audio, ct); + + public static async Task HasWavHeaderAsync(Stream audio, CancellationToken ct) + { + var header = new byte[12]; + if (await audio.ReadAtLeastAsync(header, header.Length, false, ct) < header.Length) + return false; + return header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F' && + header[8] == 'W' && header[9] == 'A' && header[10] == 'V' && header[11] == 'E'; + } + public static async Task HasMp3HeaderAsync(Stream audio, CancellationToken ct) { var header = new byte[4]; diff --git a/RikiPath.Application/Services/ManualContentService.cs b/RikiPath.Application/Services/ManualContentService.cs index df2a11c..6923e99 100644 --- a/RikiPath.Application/Services/ManualContentService.cs +++ b/RikiPath.Application/Services/ManualContentService.cs @@ -417,7 +417,8 @@ await uow.ContentBankItems.Query() private static bool IsExcelImportDraft(ContentApprovalRequest item) => item.SourceRowNumber > 0 && (item.SourceFileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) || - item.SourceFileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase)); + item.SourceFileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase) || + string.Equals(item.SourceType, "CurriculumV2", StringComparison.OrdinalIgnoreCase)); private static void ValidateStoredImportPayload(ContentApprovalRequest item) { @@ -525,6 +526,16 @@ private static void ValidateStoredImportPayload(ContentApprovalRequest item) ? exercise.LessonTitle : (!string.IsNullOrEmpty(exercise.TopicTitle) ? exercise.TopicTitle : level.Code); return (exercise, $"{exercise.Title} / {exTarget}"); + case ImportEntityType.SrsCardTemplate: + var srs = Read(input); + srs.CardType = Required(srs.CardType, "Loại thẻ SRS"); + srs.FrontText = Required(srs.FrontText, "Mặt trước thẻ SRS"); + srs.BackText = Required(srs.BackText, "Mặt sau thẻ SRS"); + srs.AudioUrl = MediaUrl(srs.AudioUrl, "URL âm thanh"); + srs.CertificateLevelCode = level.Code; + if (string.IsNullOrWhiteSpace(srs.NormalizedContentKey)) + srs.NormalizedContentKey = $"{level.Code}:{srs.CardType}:{srs.FrontText}"; + return (srs, srs.NormalizedContentKey); default: throw new ArgumentException("Loại nội dung không được hỗ trợ."); } @@ -690,6 +701,8 @@ await uow.LanguageSkills.Query().Where(x => !x.IsDeleted && x.Id == id).Select(x ImportEntityType.Vocabulary => uow.Vocabularies.Query().Where(x => !x.IsDeleted && x.Word == fields.Word && x.Reading == fields.Reading).Select(x => x.Id), ImportEntityType.Grammar => uow.GrammarPatterns.Query().Where(x => !x.IsDeleted && x.Title == fields.Title).Select(x => x.Id), + ImportEntityType.SrsCardTemplate => uow.SrsCardTemplates.Query().Where(x => !x.IsDeleted + && x.NormalizedContentKey == fields.NormalizedContentKey).Select(x => x.Id), _ => throw new ArgumentException("Loại nội dung không được hỗ trợ.") }; } @@ -728,7 +741,8 @@ private static string Required(string? value, string label) => string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{label} không được để trống.") : value.Trim(); private sealed record ManualIdentity(string? Title, string? Character, string? Word, string? Reading, - string? LessonTitle, int CertificateLevelId, string? Scope = null, string? TopicTitle = null); + string? LessonTitle, int CertificateLevelId, string? Scope = null, string? TopicTitle = null, + string? NormalizedContentKey = null); internal sealed record ManualListInfo(int? CertificateLevelId, string? TopicTitle, string? Title); } diff --git a/RikiPath.Application/Services/MentorLearnerSkillProfileService.cs b/RikiPath.Application/Services/MentorLearnerSkillProfileService.cs index 4076bef..625bb7c 100644 --- a/RikiPath.Application/Services/MentorLearnerSkillProfileService.cs +++ b/RikiPath.Application/Services/MentorLearnerSkillProfileService.cs @@ -6,6 +6,8 @@ using RikiPath.Application.IServices; using RikiPath.Application.Responses; using RikiPath.Application.Responses.MentorMeetings; +using RikiPath.Application.Responses.PlacementTests; +using RikiPath.Domain; using RikiPath.Domain.Entities; using RikiPath.Domain.Enums; @@ -14,7 +16,8 @@ namespace RikiPath.Application.Services; public sealed class MentorLearnerSkillProfileService( IUnitOfWork uow, IClaimService claims, - IMentorGroupPolicyService? groupPolicies = null) : IMentorLearnerSkillProfileService + IMentorGroupPolicyService? groupPolicies = null, + IPracticeTestService? assessmentEngine = null) : IMentorLearnerSkillProfileService { private static readonly JsonSerializerOptions FeedbackJsonOptions = new(JsonSerializerDefaults.Web); private sealed record FeedbackEnvelope(string? Feedback); @@ -99,6 +102,21 @@ private static string NormalizeSkillKey(int? skillId, string? skillCode, string? return gradingFeedbackJson.TrimStart().StartsWith("{", StringComparison.Ordinal) ? null : gradingFeedbackJson.Trim(); } + public async Task> GetLearnerCourseCompetencyAsync( + int enrollmentId, CancellationToken cancellationToken = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Learner) + return ApiResponse.Fail("Chỉ học viên mới xem được hồ sơ năng lực của mình.", HttpStatusCode.Forbidden); + var course = await uow.StudyCourses.Query().AsNoTracking() + .Where(c => c.Id == enrollmentId && c.LearnerId == actor.Id) + .Select(c => new { c.Id, c.CohortId }) + .FirstOrDefaultAsync(cancellationToken); + if (course is null) + return ApiResponse.NotFound("Không tìm thấy lớp học của bạn."); + return await GetSkillProfileAsync(actor.Id, course.CohortId, cancellationToken); + } + public async Task> GetSkillProfileAsync( int learnerId, int? cohortId = null, CancellationToken cancellationToken = default) { @@ -264,9 +282,10 @@ public async Task> GetSkillProfil : nowUtc; totalScheduledSessionsCount = Math.Max(validSessions.Count, learnerEnrollment?.TotalSessions ?? 0); - var endedCohortSessionsCount = hasClassStarted - ? validSessions.Count(s => BusinessDateHelper.EnsureUtc(s.Availability.EndTime) <= nowUtc) - : 0; + // Completed sessions come from the persisted session lifecycle, never from the clock alone. + var endedCohortSessionsCount = string.Equals(cohort.Status, "Completed", StringComparison.OrdinalIgnoreCase) + ? validSessions.Count + : validSessions.Count(s => string.Equals(s.Status, "Completed", StringComparison.OrdinalIgnoreCase)); completedSessionsCount = totalScheduledSessionsCount > 0 ? Math.Min(totalScheduledSessionsCount, Math.Max(endedCohortSessionsCount, deliveredSessionNumbers)) : Math.Max(endedCohortSessionsCount, deliveredSessionNumbers); @@ -312,6 +331,18 @@ public async Task> GetSkillProfil .Where(a => !hasClassStarted || BusinessDateHelper.EnsureUtc(a.SubmittedAt ?? a.StartedAt) < baselineCutoffUtc) .ToList(); + // Class-bound assessments (pinned pre-course baseline and end-of-course attempts) for this learner. + var courseAssessmentAttempts = cohortId.HasValue + ? await uow.MockTestAttempts.Query().AsNoTracking() + .Where(a => a.UserId == learnerId && !a.IsDeleted && a.AttemptKind == AttemptKind.CourseAssessment) + .ToListAsync(cancellationToken) + : []; + var pinnedBaseline = cohortId.HasValue + ? CourseCompetencyPolicy.PinnedBaseline(courseAssessmentAttempts, cohortId.Value, enrollmentId, hasClassStarted ? baselineCutoffUtc : null) + : null; + if (pinnedBaseline is not null) + preStartPlacements = [pinnedBaseline]; + var baselineCompatibility = PracticeTestService.EvaluatePlacementCompatibility( preStartPlacements, targetLevelId, targetLevelCode); var chosenPlacementAttempt = baselineCompatibility.CompatibleAttempt ?? baselineCompatibility.LatestAttempt; @@ -556,7 +587,7 @@ public async Task> GetSkillProfil && !r.MockTestAttempt.IsDeleted && r.MockTestAttempt.UserId == learnerId && r.MockTestAttempt.IsCompleted - && r.MockTestAttempt.AttemptKind != AttemptKind.Placement + && r.MockTestAttempt.AttemptKind == AttemptKind.MockTest && !r.MockTestAttempt.IsPlacementAssessment) .Select(r => new { @@ -694,34 +725,11 @@ void AddBucketSample( : cohortAssignmentsQuery.Where(h => !h.CohortId.HasValue && (h.StudyCourseId == enrollmentId || h.StudyCourseId == null)); var hwRows = await cohortAssignmentsQuery - .Include(h => h.HomeworkAssignmentLessons).ThenInclude(l => l.Lesson).ThenInclude(ls => ls.LanguageSkill) - .Include(h => h.Exercises).ThenInclude(e => e.PracticeExercise).ThenInclude(pe => pe.LanguageSkill) .Include(h => h.Submission).ThenInclude(s => s!.GradingResult) .AsSplitQuery() .OrderByDescending(h => h.PublishedFeedbackAtUtc ?? h.CreatedDate) .ToListAsync(cancellationToken); - var hwAssignmentIds = hwRows.Select(h => h.Id).ToArray(); - var hwPracticeAttempts = hwAssignmentIds.Length == 0 - ? [] - : await uow.PracticeExerciseAttempts.Query().AsNoTracking() - .Where(a => !a.IsDeleted - && a.UserId == learnerId - && a.HomeworkAssignmentId.HasValue - && hwAssignmentIds.Contains(a.HomeworkAssignmentId.Value) - && a.IsCompleted - && a.ScorePercent.HasValue) - .Select(a => new - { - AssignmentId = a.HomeworkAssignmentId!.Value, - SkillId = (int?)a.PracticeExercise.LanguageSkillId, - SkillCode = a.PracticeExercise.LanguageSkill.Code, - SkillName = a.PracticeExercise.LanguageSkill.Name, - Score = a.ScorePercent!.Value, - At = a.SubmittedAt ?? a.StartedAt - }) - .ToListAsync(cancellationToken); - var assignedCount = courseHw.Count + hwRows.Count; var submittedCount = courseHw.Count(h => h.SubmittedAt.HasValue) + hwRows.Count(h => h.Submission != null && !h.Submission.IsDeleted); @@ -758,144 +766,150 @@ void AddBucketSample( ? Math.Round(attendancePresentCount * 100d / attendanceMarkedCount, 1) : null; - var inClassBuckets = new Dictionary>(StringComparer.OrdinalIgnoreCase); var inClassAssessments = new List(); - var inClassTrendPoints = new List(); - var assignmentTitleById = hwRows.ToDictionary(h => h.Id, h => h.Title); + var homeworkTimeline = new List(); if (hasClassStarted) { - foreach (var ha in hwPracticeAttempts) - { - var atUtc = BusinessDateHelper.EnsureUtc(ha.At); - var key = NormalizeSkillKey(ha.SkillId, ha.SkillCode, ha.SkillName); - var labelVi = SkillLabelVi(key, ha.SkillName); - if (!skillDescriptors.ContainsKey(key)) - skillDescriptors[key] = new SkillDescriptor(key, labelVi); - if (!inClassBuckets.TryGetValue(key, out var list)) - inClassBuckets[key] = list = []; - list.Add(new SkillSample(ha.Score, atUtc, "CohortHomeworkExercise")); - - inClassTrendPoints.Add(new CompetencyTrendPointResponse( - atUtc, - assignmentTitleById.GetValueOrDefault(ha.AssignmentId) ?? "Bài tập luyện tập tại lớp", - "CohortHomeworkExercise", - "InClassHomeworkExercise", - key, - labelVi, - Math.Round(ha.Score, 1))); - } - foreach (var h in hwRows) { - var skillKeysForAssignment = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var l in h.HomeworkAssignmentLessons) - { - if (l.Lesson?.LanguageSkill is not null) - { - var key = NormalizeSkillKey(l.Lesson.LanguageSkillId, l.Lesson.LanguageSkill.Code, l.Lesson.LanguageSkill.Name); - skillKeysForAssignment[key] = SkillLabelVi(key, l.Lesson.LanguageSkill.Name); - } - } - foreach (var e in h.Exercises) - { - if (e.PracticeExercise?.LanguageSkill is not null) - { - var key = NormalizeSkillKey(e.PracticeExercise.LanguageSkillId, e.PracticeExercise.LanguageSkill.Code, e.PracticeExercise.LanguageSkill.Name); - skillKeysForAssignment[key] = SkillLabelVi(key, e.PracticeExercise.LanguageSkill.Name); - } - } - var sub = h.Submission != null && !h.Submission.IsDeleted ? h.Submission : null; - var validGrade = sub?.GradingResult != null && !sub.GradingResult.IsDeleted ? sub.GradingResult : null; - var exerciseScores = hwPracticeAttempts.Where(a => a.AssignmentId == h.Id).ToList(); - double? eventScore = h.MentorScore - ?? (validGrade is not null ? Math.Round(Math.Clamp(validGrade.OverallScore, 0, 100), 1) : (double?)null) - ?? (exerciseScores.Count > 0 ? Math.Round(exerciseScores.Average(x => x.Score), 1) : (double?)null); - - var gradedAt = h.PublishedFeedbackAtUtc ?? validGrade?.GradedAt; - var mentorNote = TryExtractMentorFeedbackText(h.MentorFeedback, validGrade?.FeedbackJson); - - // Attribute assignment-level mentor score strictly to assignment skills when no individual exercise score already logged for that skill. - if (eventScore.HasValue && gradedAt.HasValue && exerciseScores.Count == 0) - { - var gradedAtUtc = BusinessDateHelper.EnsureUtc(gradedAt.Value); - var roundedEventScore = Math.Round(eventScore.Value, 1); - if (skillKeysForAssignment.Count > 0) - { - foreach (var sk in skillKeysForAssignment) - { - if (!skillDescriptors.ContainsKey(sk.Key)) - skillDescriptors[sk.Key] = new SkillDescriptor(sk.Key, sk.Value); - if (!inClassBuckets.TryGetValue(sk.Key, out var list)) - inClassBuckets[sk.Key] = list = []; - list.Add(new SkillSample(roundedEventScore, gradedAtUtc, "CohortHomework")); - - inClassTrendPoints.Add(new CompetencyTrendPointResponse( - gradedAtUtc, - h.Title, - "CohortHomework", - "InClassCohortHomework", - sk.Key, - sk.Value, - roundedEventScore)); - } - } - else - { - inClassTrendPoints.Add(new CompetencyTrendPointResponse( - gradedAtUtc, - h.Title, - "CohortHomework", - "InClassCohortHomework", - null, - null, - roundedEventScore)); - } - } + var isPublished = h.PublishedFeedbackAtUtc.HasValue; + // Only grades the Mentor has published count; AI drafts and unpublished scores are never shown or averaged. + double? publishedScore = isPublished && h.MentorScore.HasValue + ? Math.Round(Math.Clamp(h.MentorScore.Value, 0d, 100d), 1) + : null; + DateTime? dueUtc = h.DueAt.HasValue ? BusinessDateHelper.EnsureUtc(h.DueAt.Value) : null; + DateTime? publishedUtc = isPublished ? BusinessDateHelper.EnsureUtc(h.PublishedFeedbackAtUtc!.Value) : null; + var status = isPublished + ? "Graded" + : sub is not null + ? "Submitted" + : dueUtc.HasValue && dueUtc.Value <= nowUtc ? "Overdue" : "NotSubmitted"; + var mentorNote = isPublished + ? TryExtractMentorFeedbackText(h.MentorFeedback, sub?.GradingResult is { IsDeleted: false } grade ? grade.FeedbackJson : null) + : null; inClassAssessments.Add(new InClassAssessmentEventResponse( h.Id, h.Title, h.AssignmentScope == "CohortIndividual" ? "Bài giao riêng" : "Bài tập lớp", - h.DueAt.HasValue ? BusinessDateHelper.EnsureUtc(h.DueAt.Value) : null, + dueUtc, sub is not null ? BusinessDateHelper.EnsureUtc(sub.SubmittedAt) : null, - gradedAt.HasValue ? BusinessDateHelper.EnsureUtc(gradedAt.Value) : null, - eventScore, - h.Passed, - skillKeysForAssignment.Values.Distinct().ToList(), - h.PublishedFeedbackAtUtc.HasValue ? mentorNote : null)); + publishedUtc, + publishedScore, + isPublished ? h.Passed : null, + [], + mentorNote, + status, + publishedScore.HasValue ? Math.Round(publishedScore.Value / 10d, 2) : null)); + + if (publishedScore.HasValue && publishedUtc.HasValue) + homeworkTimeline.Add(new HomeworkScorePointResponse(h.Id, h.Title, Math.Round(publishedScore.Value / 10d, 2), publishedUtc.Value)); + } + + foreach (var ch in courseHw) + { + var dueUtc = BusinessDateHelper.EnsureUtc(ch.DueAt); + var status = ch.ReviewedAt.HasValue ? "Graded" + : ch.SubmittedAt.HasValue ? "Submitted" + : dueUtc <= nowUtc ? "Overdue" : "NotSubmitted"; + inClassAssessments.Add(new InClassAssessmentEventResponse( + -ch.Id, + ch.Title, + "Bài tập khóa học", + dueUtc, + ch.SubmittedAt.HasValue ? BusinessDateHelper.EnsureUtc(ch.SubmittedAt.Value) : null, + ch.ReviewedAt.HasValue ? BusinessDateHelper.EnsureUtc(ch.ReviewedAt.Value) : null, + null, + ch.ReviewedAt.HasValue ? ch.Passed : null, + [], + ch.ReviewedAt.HasValue && !string.IsNullOrWhiteSpace(ch.Feedback) ? ch.Feedback.Trim() : null, + status, + null)); } } - var inClassSkills = inClassBuckets - .Select(kv => new InClassSkillItemResponse( - kv.Key, - SkillLabelVi(kv.Key, skillDescriptors.GetValueOrDefault(kv.Key)?.Label), - Math.Round(kv.Value.Average(s => s.Score), 1), - kv.Value.Count, - kv.Value.Max(s => s.At), - kv.Value.Select(s => s.Source).Distinct().ToList())) - .OrderBy(x => SkillSortOrder(x.SkillCode)) - .ThenBy(x => x.SkillLabel) - .ToList(); + var gradedScores = inClassAssessments.Where(a => a.ScorePercent.HasValue).Select(a => a.ScorePercent!.Value).ToList(); + var gradedHomeworkCount = gradedScores.Count; + double? averageGradedHomeworkScorePercent = gradedHomeworkCount > 0 ? Math.Round(gradedScores.Average(), 1) : null; + double? averageHomeworkScore10 = gradedHomeworkCount > 0 ? Math.Round(gradedScores.Average() / 10d, 2) : null; - var scoredAssessments = inClassAssessments.Where(a => a.ScorePercent.HasValue).ToList(); - var gradedHomeworkCount = scoredAssessments.Count; - double? averageGradedHomeworkScorePercent = gradedHomeworkCount > 0 - ? Math.Round(scoredAssessments.Average(a => a.ScorePercent!.Value), 1) - : null; - var scoredAssessmentCount = inClassBuckets.Values.Sum(v => v.Count); - var inClassStrengths = inClassSkills.Where(s => s.AverageScorePercent >= 80d).Select(s => s.SkillLabel).ToList(); - var inClassFocusAreas = inClassSkills.Where(s => s.AverageScorePercent < 60d).Select(s => s.SkillLabel).ToList(); - var orderedInClassTrend = inClassTrendPoints.OrderBy(p => p.DateUtc).ToList(); + // In-class quizzes: own statistics (0–100%), never mixed into homework or the end-of-course comparison. + InClassQuizSummaryResponse? quizSummary = null; + if (cohortId.HasValue) + { + var quizAssignments = await uow.ClassQuizAssignments.Query().AsNoTracking() + .Include(a => a.Quiz) + .Where(a => a.LearnerId == learnerId && a.Quiz.CohortId == cohortId.Value + && !a.Quiz.IsDeleted && a.Quiz.Status == "Published") + .ToListAsync(cancellationToken); + var pendingAttempts = quizAssignments.Where(a => a.AttemptId.HasValue && a.CompletedAtUtc == null) + .Select(a => a.AttemptId!.Value).ToList(); + if (pendingAttempts.Count > 0 && assessmentEngine is not null) + { + await assessmentEngine.FinalizeExpiredClassQuizAttemptsAsync(pendingAttempts, cancellationToken); + quizAssignments = await uow.ClassQuizAssignments.Query().AsNoTracking() + .Include(a => a.Quiz) + .Where(a => quizAssignments.Select(x => x.Id).Contains(a.Id)) + .ToListAsync(cancellationToken); + } + var quizAttemptIds = quizAssignments.Where(a => a.AttemptId.HasValue).Select(a => a.AttemptId!.Value).ToList(); + var quizAttempts = quizAttemptIds.Count == 0 + ? [] + : await uow.MockTestAttempts.Query().AsNoTracking() + .Where(a => quizAttemptIds.Contains(a.Id) && a.IsCompleted && !a.IsDeleted) + .ToDictionaryAsync(a => a.Id, cancellationToken); + var results = new List(); + foreach (var a in quizAssignments.Where(a => a.CompletedAtUtc.HasValue && a.AttemptId.HasValue)) + { + if (!quizAttempts.TryGetValue(a.AttemptId!.Value, out var att) + || !PracticeTestService.TryDeserializeSnapshot(att.QuestionSnapshotJson, out var snap)) continue; + var skills = CourseCompetencyPolicy.ScopedSkills(snap, null) + .OrderBy(kv => SkillSortOrder(kv.Key)) + .Select(kv => new QuizSkillPointResponse(kv.Key, kv.Value.Correct, kv.Value.Total, CourseCompetencyPolicy.Percent(kv.Value.Correct, kv.Value.Total))) + .ToList(); + var qc = skills.Sum(s => s.CorrectCount); + var qt = skills.Sum(s => s.TotalCount); + if (qt == 0) continue; + results.Add(new InClassQuizResultResponse( + a.QuizId, a.Id, a.Quiz.Title, BusinessDateHelper.EnsureUtc(a.CompletedAtUtc!.Value), + CourseCompetencyPolicy.Percent(qc, qt), qc, qt, a.Quiz.StructureKey, skills)); + } + results = results.OrderBy(r => r.CompletedAtUtc).ThenBy(r => r.QuizId).ToList(); - var inClassHasData = hasClassStarted && (assignedCount > 0 || inClassSkills.Count > 0 || attendanceMarkedCount > 0); + // Progress is only measured inside one group of comparable quizzes (same level = same class, same structure). + var comparableKey = results.Count > 0 ? results[^1].StructureKey : null; + var group = results.Where(r => r.StructureKey == comparableKey).ToList(); + var changes = new List(); + foreach (var code in group.SelectMany(r => r.Skills).Select(s => s.SkillCode).Distinct().OrderBy(SkillSortOrder)) + { + var withSkill = group.Where(r => r.Skills.Any(s => s.SkillCode == code)).ToList(); + var first = withSkill[0]; + var last = withSkill[^1]; + var fs = first.Skills.First(s => s.SkillCode == code).ScorePercent; + var ls = last.Skills.First(s => s.SkillCode == code).ScorePercent; + changes.Add(new QuizSkillChangeResponse(code, fs, ls, + withSkill.Count >= 2 ? Math.Round(ls - fs, 1) : null, first.QuizId, last.QuizId)); + } + quizSummary = new InClassQuizSummaryResponse( + quizAssignments.Count, + results.Count, + // Average of each quiz's exact correct ratio (not of already-rounded percentages). + results.Count > 0 ? Math.Round(results.Average(r => r.CorrectCount * 100d / r.TotalCount), 1, MidpointRounding.AwayFromZero) : null, + results, + changes, + group.Count >= 2, + comparableKey); + } + + var inClassHasData = hasClassStarted && (assignedCount > 0 || attendanceMarkedCount > 0 || completedSessionsCount > 0 + || (quizSummary?.AssignedCount ?? 0) > 0); var inClassCompetency = new InClassCompetencyResponse( hasClassStarted, inClassHasData, hwStats, - inClassSkills, + [], inClassAssessments, attendancePresentCount, attendanceMarkedCount, @@ -904,295 +918,194 @@ void AddBucketSample( totalScheduledSessionsCount, gradedHomeworkCount, averageGradedHomeworkScorePercent, - scoredAssessmentCount, - inClassStrengths, - inClassFocusAreas, - orderedInClassTrend); + 0, + [], + [], + [], + averageHomeworkScore10, + homeworkTimeline.OrderBy(p => p.GradedAtUtc).ThenBy(p => p.AssignmentId).ToList(), + quizSummary); + + // 6. C — End-of-course assessment (official milestone) and pre/post comparison on one shared scale. + CourseFinalAssessmentSummaryResponse? finalSummary = null; + CourseCompetencyPolicy.FinalAttemptState? finalState = null; + if (cohort is not null && learnerEnrollment is not null) + { + var forEnrollment = CourseCompetencyPolicy.FinalAttemptsFor(courseAssessmentAttempts, cohort.Id, enrollmentId); + finalState = CourseCompetencyPolicy.ResolveFinalState( + string.Equals(cohort.Status, "Completed", StringComparison.OrdinalIgnoreCase), + CourseCompetencyPolicy.IsEligibleEnrollment(learnerEnrollment), + forEnrollment, + nowUtc); + + var finalSkills = new List(); + double? finalOverall = null; + int? finalCorrect = null; + int? finalTotal = null; + if (finalState.OfficialSnapshot is { } officialSnapshot) + { + foreach (var kv in CourseCompetencyPolicy.ScopedSkills(officialSnapshot, null) + .OrderBy(kv => SkillSortOrder(kv.Key))) + { + finalSkills.Add(new FinalSkillResultResponse( + kv.Key, SkillLabelVi(kv.Key), CourseCompetencyPolicy.Percent(kv.Value.Correct, kv.Value.Total), + kv.Value.Correct, kv.Value.Total)); + } + finalCorrect = finalSkills.Sum(s => s.CorrectCount); + finalTotal = finalSkills.Sum(s => s.TotalCount); + finalOverall = finalTotal > 0 ? CourseCompetencyPolicy.Percent(finalCorrect.Value, finalTotal.Value) : null; + } + + finalSummary = new CourseFinalAssessmentSummaryResponse( + finalState.Availability, + targetLevelCode, + CourseCompetencyPolicy.FinalAttemptLimit, + finalState.AttemptsUsed, + finalState.Active?.Id, + finalState.PendingSubmission?.Id, + finalState.Official?.Id, + finalState.Official?.SubmittedAt is { } finalAt ? BusinessDateHelper.EnsureUtc(finalAt) : null, + finalOverall, + finalCorrect, + finalTotal, + finalOverall.HasValue ? finalOverall.Value >= CourseCompetencyPolicy.FinalPassThresholdPercent : null, + CourseCompetencyPolicy.FinalPassThresholdPercent, + finalSkills); + } + + CompetencyComparisonResponse NotComparable(string code, string reason) => new( + false, reason, targetLevelCode, null, + baselinePlacement?.AssessedAtUtc, finalSummary?.CompletedAtUtc, + baselinePlacement?.OverallScorePercent, finalSummary?.OverallScorePercent, null, + [], [], [], ReasonCode: code); - // 6. C — Compatible Scale-Matched Comparison (only same JLPT level & official JLPT section scale). CompetencyComparisonResponse comparison; - if (!hasClassStarted) + if (cohort is null || finalState is null) { - comparison = new CompetencyComparisonResponse( - false, "Lớp học chưa bắt đầu; so sánh tiến bộ sẽ khả dụng khi có dữ liệu đánh giá cùng cấp độ trong quá trình học.", - targetLevelCode, null, baselinePlacement?.AssessedAtUtc, null, baselinePlacement?.OverallScorePercent, null, null, [], [], []); + comparison = NotComparable("NO_CLASS_SCOPE", "Mức tiến bộ chỉ được so sánh trong phạm vi một lớp học."); } - else if (baselinePlacement is null || baselineCompatibility.Status != "COMPATIBLE") + else if (baselinePlacement is null || chosenPlacementAttempt is null) { - comparison = new CompetencyComparisonResponse( - false, - baselinePlacement is null - ? "Học viên chưa có bài đánh giá năng lực đầu vào tương thích để đối chiếu." - : baselineCompatibility.Reason ?? "Bài đánh giá đầu vào chưa khớp cấp độ mục tiêu của lớp để so sánh trực tiếp.", - targetLevelCode, null, baselinePlacement?.AssessedAtUtc, null, baselinePlacement?.OverallScorePercent, null, null, [], [], []); + comparison = NotComparable("NO_BASELINE", "Chưa có kết quả đánh giá đầu vào trước khi lớp bắt đầu."); + } + else if (finalState.Official is null || finalState.OfficialSnapshot is null) + { + comparison = finalState.Availability == CourseFinalAvailability.NotOpen + ? NotComparable("CLASS_NOT_COMPLETED", "Bài đánh giá cuối khóa mở sau khi lớp học hoàn thành.") + : NotComparable("FINAL_NOT_COMPLETED", "Chưa có kết quả đánh giá cuối khóa."); + } + else if (!PracticeTestService.TryDeserializeSnapshot(chosenPlacementAttempt.QuestionSnapshotJson, out var baselineSnapshot) + || baselineSnapshot.Questions.Count == 0) + { + comparison = NotComparable("BASELINE_DETAIL_UNAVAILABLE", "Kết quả đầu vào không có dữ liệu chi tiết theo câu hỏi để so sánh."); } else { - var postStartPlacements = allPlacements - .Where(a => a.IsCompleted && a.TotalScore.HasValue && BusinessDateHelper.EnsureUtc(a.SubmittedAt ?? a.StartedAt) >= baselineCutoffUtc) - .ToList(); - var postCompat = PracticeTestService.EvaluatePlacementCompatibility(postStartPlacements, targetLevelId, targetLevelCode); - - var currentByJlptSkill = new Dictionary(StringComparer.OrdinalIgnoreCase); - DateTime? currentAssessedAtUtc = null; - double? currentOverallPercent = null; - string? assessmentScale = null; - - if (postCompat.CompatibleAttempt is not null && postCompat.CompatibleResult is not null && !string.IsNullOrWhiteSpace(targetLevelCode)) + // Compare only the JLPT levels both assessments tested (e.g. the N5 part of an N5–N4 baseline vs an N5 final). + var sharedLevels = CourseCompetencyPolicy.TestedLevels(baselineSnapshot); + sharedLevels.IntersectWith(CourseCompetencyPolicy.TestedLevels(finalState.OfficialSnapshot)); + var baseScoped = CourseCompetencyPolicy.ScopedSkills(baselineSnapshot, sharedLevels); + var finalScoped = CourseCompetencyPolicy.ScopedSkills(finalState.OfficialSnapshot, sharedLevels); + var minimum = PlacementAssessmentModePolicy.MinimumQuestionsPerSkillAndLevel; + + var rows = new List(); + var gaps = new List(); + foreach (var skill in Enum.GetValues()) { - var postAudio = PracticeTestService.TryGetSkillEvidenceFromSnapshot(postCompat.CompatibleAttempt.QuestionSnapshotJson); - var postAssessed = JlptSkillAssessmentPolicy.Assess(postCompat.CompatibleResult, targetLevelCode, postAudio); - foreach (var sec in postAssessed.Where(s => s.HasData && s.ScorePercent.HasValue)) - currentByJlptSkill[sec.SkillCode] = (sec.ScorePercent!.Value, SkillLabelVi(sec.SkillCode, sec.SectionTitle)); - currentAssessedAtUtc = BusinessDateHelper.EnsureUtc(postCompat.CompatibleAttempt.SubmittedAt ?? postCompat.CompatibleAttempt.StartedAt); - var validPostSections = postAssessed.Where(s => s.HasData && s.TotalCount > 0).ToList(); - currentOverallPercent = postAudio is not null && validPostSections.Sum(s => s.TotalCount) > 0 - ? Math.Round(validPostSections.Sum(s => s.CorrectCount) * 100d / validPostSections.Sum(s => s.TotalCount), 1) - : Math.Round(postCompat.CompatibleResult.TotalScore, 1); - assessmentScale = $"Đánh giá JLPT {targetLevelCode}"; - } - else if (targetLevelId.HasValue) - { - var latestTargetMockId = nonPlacementMockSections - .Where(m => m.CertificateLevelId == targetLevelId.Value - && m.ExamKind == ExamKind.FullMockTest - && BusinessDateHelper.EnsureUtc(m.At) >= baselineCutoffUtc) - .OrderByDescending(m => m.At) - .ThenByDescending(m => m.MockTestAttemptId) - .Select(m => (int?)m.MockTestAttemptId) - .FirstOrDefault(); - - if (latestTargetMockId.HasValue) + var code = skill.ToString().ToLowerInvariant(); + var hasBase = baseScoped.TryGetValue(code, out var b) && b.Total >= minimum; + var hasFinal = finalScoped.TryGetValue(code, out var f) && f.Total >= minimum; + if (hasBase && hasFinal) { - var rowsForAttempt = nonPlacementMockSections.Where(m => m.MockTestAttemptId == latestTargetMockId.Value).ToList(); - foreach (var grp in rowsForAttempt - .Select(r => new { Row = r, Skill = JlptSkillAssessmentPolicy.Classify(string.IsNullOrWhiteSpace(r.SkillName) ? r.SectionTitle : r.SkillName) }) - .Where(x => x.Skill.HasValue && x.Row.TotalCount > 0) - .GroupBy(x => x.Skill!.Value)) - { - var correct = grp.Sum(x => x.Row.CorrectCount); - var total = grp.Sum(x => x.Row.TotalCount); - if (total <= 0) continue; - var code = grp.Key.ToString().ToLowerInvariant(); - currentByJlptSkill[code] = (Math.Round(correct * 100d / total, 1), SkillLabelVi(code)); - } - var head = rowsForAttempt[0]; - currentAssessedAtUtc = BusinessDateHelper.EnsureUtc(head.At); - var totalQ = rowsForAttempt.Sum(r => r.TotalCount); - var totalC = rowsForAttempt.Sum(r => r.CorrectCount); - currentOverallPercent = totalQ > 0 - ? Math.Round(totalC * 100d / totalQ, 1) - : (head.AttemptTotalScore.HasValue ? Math.Round(head.AttemptTotalScore.Value, 1) : null); - assessmentScale = $"Đề thi thử chuẩn JLPT {targetLevelCode}"; + var bp = CourseCompetencyPolicy.Percent(b.Correct, b.Total); + var fp = CourseCompetencyPolicy.Percent(f.Correct, f.Total); + var delta = Math.Round(fp - bp, 1); + var st = delta >= CourseCompetencyPolicy.MeaningfulDeltaPoints ? "Improved" + : delta <= -CourseCompetencyPolicy.MeaningfulDeltaPoints ? "Declined" : "Stable"; + rows.Add(new SkillComparisonItemResponse(code, SkillLabelVi(code), bp, fp, delta, st, b.Correct, b.Total, f.Correct, f.Total)); + } + else if (baseScoped.ContainsKey(code) || finalScoped.ContainsKey(code)) + { + gaps.Add(new SkillComparisonGapResponse( + code, + SkillLabelVi(code), + baseScoped.TryGetValue(code, out var bb) && bb.Total > 0 ? CourseCompetencyPolicy.Percent(bb.Correct, bb.Total) : null, + finalScoped.TryGetValue(code, out var ff) && ff.Total > 0 ? CourseCompetencyPolicy.Percent(ff.Correct, ff.Total) : null, + !hasBase && !hasFinal ? "NOT_ENOUGH_BOTH" : !hasBase ? "NOT_ENOUGH_BASELINE" : "NOT_ENOUGH_FINAL")); } } - var comparisons = new List(); - foreach (var b in baselineByJlptSkill) - { - if (!currentByJlptSkill.TryGetValue(b.Key, out var cur)) continue; - var delta = Math.Round(cur.ScorePercent - b.Value.ScorePercent, 1); - var status = delta >= 2d ? "Improved" : delta <= -2d ? "Declined" : "Stable"; - comparisons.Add(new SkillComparisonItemResponse( - b.Key, - SkillLabelVi(b.Key, cur.Label), - Math.Round(b.Value.ScorePercent, 1), - Math.Round(cur.ScorePercent, 1), - delta, - status)); - } - - comparisons = comparisons - .OrderBy(c => SkillSortOrder(c.SkillCode)) - .ThenBy(c => c.SkillLabel) - .ToList(); - - if (comparisons.Count == 0 || !currentAssessedAtUtc.HasValue) + if (sharedLevels.Count == 0 || rows.Count == 0) { - comparison = new CompetencyComparisonResponse( - false, - $"Chưa có bài kiểm tra hoặc thi thử JLPT {targetLevelCode} sau ngày khai giảng cùng thang đo để đối chiếu với năng lực đầu vào.", - targetLevelCode, null, baselinePlacement.AssessedAtUtc, null, baselinePlacement.OverallScorePercent, null, null, [], [], []); + comparison = NotComparable("SCOPE_MISMATCH", "Bài đánh giá đầu vào và cuối khóa chưa có phạm vi kỹ năng tương đương để so sánh."); } else { - var unmatchedSkills = new List(); - foreach (var bs in baselinePlacement.Skills) - { - if (comparisons.Any(c => string.Equals(c.SkillCode, bs.SkillCode, StringComparison.OrdinalIgnoreCase))) - continue; - currentByJlptSkill.TryGetValue(bs.SkillCode, out var curSkill); - var hasBase = bs.ScorePercent.HasValue && bs.Status != "Unassessed"; - var hasCur = currentByJlptSkill.ContainsKey(bs.SkillCode); - var reason = (!hasBase && !hasCur) - ? "Chưa được đánh giá ở cả hai mốc" - : (!hasBase ? "Chưa có dữ liệu đầu vào" : "Chưa có dữ liệu hiện tại"); - unmatchedSkills.Add(new SkillComparisonGapResponse( - bs.SkillCode, - bs.SkillLabel, - hasBase ? Math.Round(bs.ScorePercent!.Value, 1) : null, - hasCur ? Math.Round(curSkill.ScorePercent, 1) : null, - reason)); - } - - // Chronological trend points strictly on the same compatible target-level JLPT scale. - var comparisonTrendPoints = new List(); - var jlptScaleKey = !string.IsNullOrWhiteSpace(targetLevelCode) ? $"JLPT_{targetLevelCode}" : "JLPT_COMPATIBLE"; - comparisonTrendPoints.Add(new CompetencyTrendPointResponse( - baselinePlacement.AssessedAtUtc, - "Đầu vào", - "Placement", - jlptScaleKey, - null, - null, - baselinePlacement.OverallScorePercent, - baselinePlacement.CorrectCount, - baselinePlacement.TotalQuestions)); - foreach (var bs in baselinePlacement.Skills.Where(s => s.ScorePercent.HasValue && s.Status != "Unassessed")) - { - comparisonTrendPoints.Add(new CompetencyTrendPointResponse( - baselinePlacement.AssessedAtUtc, - "Đầu vào", - "Placement", - jlptScaleKey, - bs.SkillCode, - bs.SkillLabel, - Math.Round(bs.ScorePercent!.Value, 1), - bs.CorrectCount, - bs.TotalCount)); - } - - foreach (var postAtt in postStartPlacements.OrderBy(a => a.SubmittedAt ?? a.StartedAt)) - { - var check = PracticeTestService.EvaluatePlacementCompatibility([postAtt], targetLevelId, targetLevelCode); - if (check.Status != "COMPATIBLE" || check.CompatibleResult is null || string.IsNullOrWhiteSpace(targetLevelCode)) - continue; - var postAt = BusinessDateHelper.EnsureUtc(postAtt.SubmittedAt ?? postAtt.StartedAt); - var postEv = PracticeTestService.TryGetSkillEvidenceFromSnapshot(postAtt.QuestionSnapshotJson); - var postSkills = JlptSkillAssessmentPolicy.Assess(check.CompatibleResult, targetLevelCode, postEv) - .Where(s => s.HasData && s.TotalCount > 0 && s.ScorePercent.HasValue) - .ToList(); - var postCorrect = postSkills.Sum(s => s.CorrectCount); - var postTotal = postSkills.Sum(s => s.TotalCount); - var postOverall = postEv is not null && postTotal > 0 - ? Math.Round(postCorrect * 100d / postTotal, 1) - : Math.Round(check.CompatibleResult.TotalScore, 1); - - comparisonTrendPoints.Add(new CompetencyTrendPointResponse( - postAt, - $"Đánh giá {targetLevelCode}", - "Placement", - jlptScaleKey, - null, - null, - postOverall, - postEv is not null ? postCorrect : check.CompatibleResult.CorrectCount, - postEv is not null ? postTotal : check.CompatibleResult.TotalQuestions)); - - foreach (var ps in postSkills) - { - comparisonTrendPoints.Add(new CompetencyTrendPointResponse( - postAt, - $"Đánh giá {targetLevelCode}", - "Placement", - jlptScaleKey, - ps.SkillCode, - SkillLabelVi(ps.SkillCode, ps.SectionTitle), - Math.Round(ps.ScorePercent!.Value, 1), - ps.CorrectCount, - ps.TotalCount)); - } - } - - if (targetLevelId.HasValue) - { - var mockGroups = nonPlacementMockSections - .Where(m => m.CertificateLevelId == targetLevelId.Value - && m.ExamKind == ExamKind.FullMockTest - && BusinessDateHelper.EnsureUtc(m.At) >= baselineCutoffUtc) - .GroupBy(m => m.MockTestAttemptId) - .Select(g => new { AttemptId = g.Key, At = BusinessDateHelper.EnsureUtc(g.First().At), Rows = g.ToList() }) - .OrderBy(g => g.At); - - foreach (var mg in mockGroups) - { - var totalQ = mg.Rows.Sum(r => r.TotalCount); - var totalC = mg.Rows.Sum(r => r.CorrectCount); - if (totalQ <= 0) continue; - - comparisonTrendPoints.Add(new CompetencyTrendPointResponse( - mg.At, - $"Thi thử {targetLevelCode}", - "MockTest", - jlptScaleKey, - null, - null, - Math.Round(totalC * 100d / totalQ, 1), - totalC, - totalQ)); - - foreach (var sg in mg.Rows - .Select(r => new { Row = r, Skill = JlptSkillAssessmentPolicy.Classify(string.IsNullOrWhiteSpace(r.SkillName) ? r.SectionTitle : r.SkillName) }) - .Where(x => x.Skill.HasValue && x.Row.TotalCount > 0) - .GroupBy(x => x.Skill!.Value)) - { - var sc = sg.Sum(x => x.Row.CorrectCount); - var st = sg.Sum(x => x.Row.TotalCount); - if (st <= 0) continue; - var skCode = sg.Key.ToString().ToLowerInvariant(); - comparisonTrendPoints.Add(new CompetencyTrendPointResponse( - mg.At, - $"Thi thử {targetLevelCode}", - "MockTest", - jlptScaleKey, - skCode, - SkillLabelVi(skCode), - Math.Round(sc * 100d / st, 1), - sc, - st)); - } - } - } - - double? overallDelta = currentOverallPercent.HasValue - ? Math.Round(currentOverallPercent.Value - baselinePlacement.OverallScorePercent, 1) - : null; - var improved = comparisons.Where(x => x.Status == "Improved").Select(x => x.SkillLabel).ToList(); - var focusItems = comparisons.Where(x => x.CurrentScorePercent < 60d || x.Status == "Declined").ToList(); - var focus = focusItems.Select(x => x.SkillLabel).ToList(); - var topImproved = comparisons.Where(x => x.DeltaPercent > 0).OrderByDescending(x => x.DeltaPercent).FirstOrDefault(); - var priorityFocus = focusItems.OrderBy(x => x.CurrentScorePercent).ThenBy(x => x.DeltaPercent).FirstOrDefault(); - var currentStrengths = comparisons.Where(x => x.CurrentScorePercent >= 80d).Select(x => x.SkillLabel).ToList(); - var nextRecommendations = baselinePlacement.Skills - .Where(bs => focusItems.Any(fi => string.Equals(fi.SkillCode, bs.SkillCode, StringComparison.OrdinalIgnoreCase)) - && !string.IsNullOrWhiteSpace(bs.Recommendation)) - .Select(bs => bs.Recommendation!) - .Distinct() + var bc = rows.Sum(r => r.BaselineCorrectCount); + var bt = rows.Sum(r => r.BaselineTotalCount); + var fc = rows.Sum(r => r.CurrentCorrectCount); + var ft = rows.Sum(r => r.CurrentTotalCount); + var baseOverall = CourseCompetencyPolicy.Percent(bc, bt); + var finalOverallScoped = CourseCompetencyPolicy.Percent(fc, ft); + var top = rows.Where(r => r.DeltaPercent > 0).OrderByDescending(r => r.DeltaPercent).ThenBy(r => SkillSortOrder(r.SkillCode)).FirstOrDefault(); + var lowest = rows.OrderBy(r => r.CurrentScorePercent).ThenBy(r => SkillSortOrder(r.SkillCode)).First(); + var focus = rows + .Where(r => r.CurrentScorePercent < CourseCompetencyPolicy.FinalPassThresholdPercent || r.Status == "Declined") + .OrderBy(r => r.CurrentScorePercent) .ToList(); + var scope = string.Join("–", sharedLevels.OrderBy(JlptCurriculum.Rank)); comparison = new CompetencyComparisonResponse( true, null, targetLevelCode, - assessmentScale, + $"JLPT {scope}", baselinePlacement.AssessedAtUtc, - currentAssessedAtUtc, - baselinePlacement.OverallScorePercent, - currentOverallPercent, - overallDelta, - comparisons, - improved, - focus, - comparisonTrendPoints.OrderBy(p => p.DateUtc).ToList(), - unmatchedSkills, - topImproved?.SkillLabel, - topImproved?.DeltaPercent, - priorityFocus?.SkillLabel, - currentStrengths, - nextRecommendations); + finalSummary!.CompletedAtUtc, + baseOverall, + finalOverallScoped, + Math.Round(finalOverallScoped - baseOverall, 1), + rows, + rows.Where(r => r.Status == "Improved").Select(r => r.SkillCode).ToList(), + focus.Select(r => r.SkillCode).ToList(), + [], + gaps, + top?.SkillCode, + top?.DeltaPercent, + focus.FirstOrDefault()?.SkillCode, + rows.Where(r => r.CurrentScorePercent >= 80d).Select(r => r.SkillCode).ToList(), + [], + null, + scope, + bc, + bt, + fc, + ft, + rows.Where(r => r.Status == "Declined").Select(r => r.SkillCode).ToList(), + rows.Where(r => r.Status == "Stable").Select(r => r.SkillCode).ToList(), + lowest.SkillCode, + lowest.CurrentScorePercent); } } + // 7. Post-course support data: raw (unrounded) submitted-homework ratio against the class policy threshold. + var supportThreshold = cohort?.GroupPolicy?.RemediationCompletionThresholdPercent + ?? (learnerEnrollment is { MinimumHomeworkPercent: > 0 } ? (decimal)learnerEnrollment.MinimumHomeworkPercent : MentorGroupPolicy.DefaultRetakeHomeworkThresholdPercent); + var supportComparison = CourseRetakePolicy.Comparison; + var meetsHomework = CourseRetakePolicy.MeetsThreshold(submittedCount, assignedCount, supportThreshold); + var finalPassed = finalSummary?.Passed; + var postCourseSupport = new PostCourseSupportResponse( + assignedCount, + submittedCount, + Math.Max(0, assignedCount - submittedCount), + assignedCount > 0 ? Math.Round(submittedCount * 100d / assignedCount, 1) : null, + supportThreshold, + supportComparison, + meetsHomework, + finalSummary?.AttemptId is not null, + finalPassed, + meetsHomework && finalPassed == false); + // Legacy compatibility list preserving dynamic skill rows from DB. var skillMetrics = skillDescriptors.Values.Select(desc => { @@ -1221,6 +1134,10 @@ baselinePlacement is null comparison, parallelSelfStudySkills, learner.TargetJlptLevel, - learner.TargetExamDate)); + learner.TargetExamDate, + finalSummary, + // Reinforcement-plan data is a Mentor/Admin decision aid; the Learner payload never carries it. + cohort is not null && !isSelfLearnerActor ? postCourseSupport : null, + isSelfLearnerActor ? "Learner" : isAdminActor ? "Admin" : "Mentor")); } } diff --git a/RikiPath.Application/Services/PracticeTestService.ClassQuiz.cs b/RikiPath.Application/Services/PracticeTestService.ClassQuiz.cs new file mode 100644 index 0000000..8a0d74f --- /dev/null +++ b/RikiPath.Application/Services/PracticeTestService.ClassQuiz.cs @@ -0,0 +1,253 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.PlacementTests; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Application.Services +{ + /// + /// In-class quiz attempts on the shared assessment engine: the frozen quiz version becomes the attempt snapshot, + /// autosave/submit/result reuse the Placement attempt endpoints, and scoring is the same engine core. + /// The attempt deadline is the earlier of (start + time limit) and the quiz deadline; the server is authoritative. + /// + public partial class PracticeTestService + { + public const string ClassQuizPurpose = "ClassQuiz"; + public const string ErrorQuizNotFound = "CLASS_QUIZ_NOT_FOUND"; + public const string ErrorQuizClosed = "CLASS_QUIZ_CLOSED"; + public const string ErrorQuizCompleted = "CLASS_QUIZ_ALREADY_COMPLETED"; + + public async Task> StartClassQuizAsync( + int assignmentId, + CancellationToken cancellationToken = default) + { + var userId = claimService.GetUserClaim().Id; + var userLock = UserStartLocks.GetOrAdd(userId, _ => new SemaphoreSlim(1, 1)); + await userLock.WaitAsync(cancellationToken); + try + { + ApiResponse? response = null; + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await LockUserForPlacementStartAsync(userId, token); + var now = EnsureUtc(UtcNowProvider()); + var assignment = await unitOfWork.ClassQuizAssignments.Query() + .Include(a => a.Quiz) + .Include(a => a.Enrollment) + .Include(a => a.Attempt) + .FirstOrDefaultAsync(a => a.Id == assignmentId && a.LearnerId == userId, token); + if (assignment is null || assignment.Quiz.IsDeleted || assignment.Quiz.Status != "Published" + || !CourseCompetencyPolicy.IsEligibleEnrollment(assignment.Enrollment)) + { + response = ApiResponse.NotFound( + "Không tìm thấy bài kiểm tra của bạn.", errorCode: ErrorQuizNotFound, retryable: false); + return; + } + if (await ClassRecordLock.IsCompletedUnderLockAsync(unitOfWork, assignment.Quiz.CohortId, token)) + { + if (assignment.Attempt is { IsDeleted: false, IsCompleted: false } open) + { + await FinalizeAttemptIfExpiredAsync(open, now, token); + await unitOfWork.SaveChangesAsync(token); + } + response = ApiResponse.Fail( + ClassRecordLock.Message, HttpStatusCode.Conflict, errorCode: ClassRecordLock.ErrorCode, retryable: false); + return; + } + + if (assignment.Attempt is { IsDeleted: false } existing) + { + if (existing.IsCompleted) + { + response = ApiResponse.Fail( + "Bạn đã hoàn thành bài kiểm tra này.", HttpStatusCode.Conflict, + errorCode: ErrorQuizCompleted, retryable: false); + return; + } + if (existing.ExpiresAt is { } exp && EnsureUtc(exp) > now + && TryDeserializeSnapshot(existing.QuestionSnapshotJson, out var running)) + { + var resumed = BuildSnapshotResponse(existing, running, now, isResumed: true); + resumed.AttemptType = ClassQuizPurpose; + WithoutPlacementOnlyChoices(resumed); + response = ApiResponse.Success(resumed); + return; + } + // Time is over: complete it from the answers saved before the deadline. + await FinalizeAttemptIfExpiredAsync(existing, now, token); + await unitOfWork.SaveChangesAsync(token); + response = ApiResponse.Fail( + "Bài kiểm tra đã hết thời gian và được tự động nộp.", HttpStatusCode.Conflict, + errorCode: ErrorQuizCompleted, retryable: false); + return; + } + + var dueUtc = EnsureUtc(assignment.Quiz.DueAtUtc); + if (now >= dueUtc) + { + response = ApiResponse.Fail( + "Bài kiểm tra đã quá hạn.", HttpStatusCode.Conflict, errorCode: ErrorQuizClosed, retryable: false); + return; + } + if (!TryDeserializeSnapshot(assignment.Quiz.QuestionSnapshotJson, out var version) || !HasValidSnapshotQuestions(version.Questions)) + { + response = ApiResponse.Fail( + "Đề kiểm tra chưa sẵn sàng.", HttpStatusCode.Conflict, errorCode: ErrorAttemptNotReady, retryable: false); + return; + } + + var expiresAt = now.AddMinutes(assignment.Quiz.TimeLimitMinutes); + if (expiresAt > dueUtc) expiresAt = dueUtc; + version.StartedAt = now; + version.ExpiresAt = expiresAt; + version.TimeLimitMinutes = assignment.Quiz.TimeLimitMinutes; + version.Purpose = ClassQuizPurpose; + version.CohortId = assignment.Quiz.CohortId; + version.EnrollmentId = assignment.EnrollmentId; + version.QuizId = assignment.QuizId; + version.QuizAssignmentId = assignment.Id; + version.CompletedResult = null; + foreach (var q in version.Questions) + { + q.SelectedOptionId = null; + q.OrderingResponse = null; + q.IsCorrect = false; + } + + var attempt = new MockTestAttempt + { + UserId = userId, + AttemptKind = AttemptKind.CourseAssessment, + StartedAt = now, + ExpiresAt = expiresAt, + IsCompleted = false, + QuestionSnapshotJson = JsonSerializer.Serialize(version, SnapshotJsonOptions), + }; + await unitOfWork.MockTestAttempts.AddAsync(attempt, token); + await unitOfWork.SaveChangesAsync(token); + + // Answer rows only for bank questions (FK); Mentor-authored questions live in the frozen snapshot. + var bankIds = version.Questions.Where(q => q.MockTestSectionId > 0).Select(q => q.QuestionId).ToList(); + if (bankIds.Count > 0) + { + await unitOfWork.MockTestAnswers.AddRangeAsync(bankIds.Select(id => new MockTestAnswer + { + MockTestAttemptId = attempt.Id, + MockQuestionId = id, + IsCorrect = false, + }), token); + } + assignment.AttemptId = attempt.Id; + unitOfWork.ClassQuizAssignments.Update(assignment); + await unitOfWork.SaveChangesAsync(token); + + var started = BuildSnapshotResponse(attempt, version, now, isResumed: false); + started.AttemptType = ClassQuizPurpose; + WithoutPlacementOnlyChoices(started); + response = ApiResponse.Created(started); + }, cancellationToken); + return response!; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return ApiResponse.Fail( + "Không thể bắt đầu bài kiểm tra.", HttpStatusCode.InternalServerError); + } + finally + { + userLock.Release(); + } + } + + /// + /// Completes, from the answers saved before the deadline, any of the given quiz attempts whose time is over + /// and that the learner never submitted. Idempotent; used before lists and reports are built. + /// + public async Task FinalizeExpiredClassQuizAttemptsAsync( + IReadOnlyCollection attemptIds, + CancellationToken cancellationToken = default) + { + if (attemptIds.Count == 0) return; + var now = EnsureUtc(UtcNowProvider()); + var expiredIds = await unitOfWork.MockTestAttempts.Query().AsNoTracking() + .Where(a => attemptIds.Contains(a.Id) && !a.IsDeleted && !a.IsCompleted + && a.AttemptKind == AttemptKind.CourseAssessment && a.ExpiresAt != null && a.ExpiresAt <= now) + .Select(a => a.Id) + .ToListAsync(cancellationToken); + // Attempts still open when their class was completed are closed too (class learning records are locked). + var lockedClassIds = await unitOfWork.ClassQuizAssignments.Query().AsNoTracking() + .Where(a => a.AttemptId != null && attemptIds.Contains(a.AttemptId.Value) && a.CompletedAtUtc == null + && a.Quiz.Cohort.Status == "Completed") + .Select(a => a.AttemptId!.Value) + .ToListAsync(cancellationToken); + expiredIds = expiredIds.Union(lockedClassIds).ToList(); + foreach (var id in expiredIds) + { + var gate = AttemptSubmitLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(cancellationToken); + try + { + await unitOfWork.ExecuteInTransactionAsync(async token => + { + var attempt = await LoadPlacementAttemptForSubmissionAsync(id, token); + if (attempt is null) return; + await FinalizeAttemptIfExpiredAsync(attempt, EnsureUtc(UtcNowProvider()), token); + await unitOfWork.SaveChangesAsync(token); + }, cancellationToken); + } + finally + { + gate.Release(); + } + } + } + + private async Task FinalizeAttemptIfExpiredAsync(MockTestAttempt attempt, DateTime now, CancellationToken token) + { + if (attempt.IsCompleted || attempt.IsDeleted) return; + if (!TryDeserializeSnapshot(attempt.QuestionSnapshotJson, out var snapshot) || !HasValidSnapshotQuestions(snapshot.Questions)) return; + var expiresAt = EnsureUtc(attempt.ExpiresAt ?? snapshot.ExpiresAt); + var classLocked = await IsClassQuizLockedAsync(snapshot, token); + if (now < expiresAt && !classLocked) return; + // Completed at the deadline, or when the class lock closed it earlier; only answers saved before are graded. + var closedAt = now < expiresAt ? now : expiresAt; + await GradeAndCompleteAttemptAsync(attempt, snapshot, closedAt, expiresAt, isExpired: true, recoverEarlyClosure: false, token); + } + + private async Task IsClassQuizLockedAsync(PlacementAttemptSnapshotDocument snapshot, CancellationToken token) + => string.Equals(snapshot.Purpose, ClassQuizPurpose, StringComparison.Ordinal) + && snapshot.CohortId is int cohortId + && await ClassRecordLock.IsCompletedAsync(unitOfWork, cohortId, token); + + /// A quiz is a test, not a placement: drop the Placement-only "not studied yet" choice. + private static void WithoutPlacementOnlyChoices(PlacementAttemptSnapshotResponse response) + { + foreach (var q in response.Questions) + q.Options = q.Options.Where(o => o.OptionId != NotStudiedOptionId).ToList(); + } + + /// Marks the learner's class quiz assignment as completed when its attempt is graded. + private async Task CompleteClassQuizAssignmentAsync( + MockTestAttempt attempt, + PlacementAttemptSnapshotDocument snapshot, + DateTime completedAt, + CancellationToken token) + { + if (!string.Equals(snapshot.Purpose, ClassQuizPurpose, StringComparison.Ordinal) || snapshot.QuizAssignmentId is not int assignmentId) + return; + var assignment = await unitOfWork.ClassQuizAssignments.Query() + .FirstOrDefaultAsync(a => a.Id == assignmentId && a.LearnerId == attempt.UserId, token); + if (assignment is null || assignment.CompletedAtUtc.HasValue) return; + assignment.AttemptId ??= attempt.Id; + assignment.CompletedAtUtc = completedAt; + unitOfWork.ClassQuizAssignments.Update(assignment); + } + } +} diff --git a/RikiPath.Application/Services/PracticeTestService.CourseFinal.cs b/RikiPath.Application/Services/PracticeTestService.CourseFinal.cs new file mode 100644 index 0000000..160dacb --- /dev/null +++ b/RikiPath.Application/Services/PracticeTestService.CourseFinal.cs @@ -0,0 +1,248 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.PlacementTests; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Application.Services +{ + /// + /// End-of-course competency assessment (Stage 5). Reuses the Placement assessment engine end to end: + /// the same question selection policy, snapshot, autosave, timer, scoring and result model. The attempt is + /// stored as and linked to one class enrollment through its snapshot, + /// so it never changes the learner's global Placement history, level or learning-path decision. + /// + public partial class PracticeTestService + { + public const string AttemptTypeCourseFinal = "courseFinal"; + public const string CourseFinalPurpose = "CourseFinal"; + public const string CourseBaselinePurpose = "CourseBaseline"; + public const string ErrorCourseFinalNotOpen = "COURSE_FINAL_NOT_OPEN"; + public const string ErrorCourseFinalNotEligible = "COURSE_FINAL_NOT_ELIGIBLE"; + public const string ErrorCourseFinalCompleted = "COURSE_FINAL_ALREADY_COMPLETED"; + public const string ErrorCourseFinalPendingSubmission = "COURSE_FINAL_PENDING_SUBMISSION"; + public const string ErrorCourseFinalLevelUnsupported = "COURSE_FINAL_LEVEL_UNSUPPORTED"; + + internal static bool IsAssessmentEngineKind(AttemptKind kind) + => kind is AttemptKind.Placement or AttemptKind.CourseAssessment; + + private static int PlannedAssessmentQuestionCount => + PlacementVocabularyQuestions + PlacementGrammarQuestions + + PlacementReadingPassages * PlacementReadingQuestionsPerPassage + PlacementListeningQuestions; + + public async Task> GetCourseFinalAssessmentAsync( + int enrollmentId, + CancellationToken cancellationToken = default) + { + var userId = claimService.GetUserClaim().Id; + var course = await LoadCourseForFinalAsync(enrollmentId, cancellationToken); + if (course is null || course.LearnerId != userId || course.Cohort is null) + return ApiResponse.NotFound("Không tìm thấy lớp học của bạn."); + + var now = EnsureUtc(UtcNowProvider()); + var attempts = await LoadCourseFinalAttemptsAsync(userId, cancellationToken); + var forEnrollment = CourseCompetencyPolicy.FinalAttemptsFor(attempts, course.Cohort.Id, course.Id); + var state = CourseCompetencyPolicy.ResolveFinalState( + CourseCompetencyPolicy.IsClassCompleted(course), + CourseCompetencyPolicy.IsEligibleEnrollment(course), + forEnrollment, + now); + return ApiResponse.Success(BuildCourseFinalStatus(course, state)); + } + + public async Task> StartCourseFinalAssessmentAsync( + int enrollmentId, + CancellationToken cancellationToken = default) + { + var userId = claimService.GetUserClaim().Id; + var userLock = UserStartLocks.GetOrAdd(userId, _ => new SemaphoreSlim(1, 1)); + await userLock.WaitAsync(cancellationToken); + try + { + var course = await LoadCourseForFinalAsync(enrollmentId, cancellationToken); + if (course is null || course.LearnerId != userId || course.Cohort is null) + return ApiResponse.NotFound("Không tìm thấy lớp học của bạn."); + + var now = EnsureUtc(UtcNowProvider()); + var guard = await CheckCourseFinalStartAsync(course, userId, now, cancellationToken); + if (guard.Resume is not null) return guard.Resume; + if (guard.Failure is not null) return guard.Failure; + + var level = course.Cohort.Plan?.CertificateLevel ?? course.CertificateLevel; + var scopeCode = NormalizeLevelCode(level?.Code); + if (level is null || !JlptCurriculum.IsSupportedStudyLevel(scopeCode)) + return ApiResponse.Fail( + "Cấp độ của lớp học chưa được hỗ trợ đánh giá cuối khóa.", + HttpStatusCode.Conflict, errorCode: ErrorCourseFinalLevelUnsupported, retryable: false); + + var allLevelsRaw = (await unitOfWork.CertificateLevels.GetAllAsync(cancellationToken)) + .Where(l => !l.IsDeleted && l.Id > 0 && !string.IsNullOrWhiteSpace(l.Code)) + .ToList(); + + // Prefer questions the learner has not answered in any earlier assessment (incl. the pre-course baseline). + var seenQuestionIds = (await LoadUserPlacementAttemptsAsync(userId, cancellationToken)) + .Concat(await LoadCourseFinalAttemptsAsync(userId, cancellationToken)) + .SelectMany(a => TryDeserializeSnapshot(a.QuestionSnapshotJson, out var doc) + ? doc.Questions.Select(q => q.QuestionId) + : []) + .ToHashSet(); + + var built = await BuildAssessmentSnapshotAsync( + level.Id, scopeCode, false, PlacementAssessmentModePolicy.ComparisonLevel(scopeCode), + level.CertificateTypeId, allLevelsRaw, seenQuestionIds, cancellationToken); + if (built.Failure is not null) return built.Failure; + + var snapshotDoc = built.Snapshot!; + snapshotDoc.Purpose = CourseFinalPurpose; + snapshotDoc.CohortId = course.Cohort.Id; + snapshotDoc.EnrollmentId = course.Id; + var snapshotJson = JsonSerializer.Serialize(snapshotDoc, SnapshotJsonOptions); + + ApiResponse? response = null; + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await LockUserForPlacementStartAsync(userId, token); + var nowInTx = EnsureUtc(UtcNowProvider()); + var recheck = await CheckCourseFinalStartAsync(course, userId, nowInTx, token); + if (recheck.Resume is not null || recheck.Failure is not null) + { + response = recheck.Resume ?? recheck.Failure; + return; + } + + var attempt = new MockTestAttempt + { + UserId = userId, + AttemptKind = AttemptKind.CourseAssessment, + StartedAt = snapshotDoc.StartedAt, + ExpiresAt = snapshotDoc.ExpiresAt, + IsCompleted = false, + QuestionSnapshotJson = snapshotJson, + }; + await unitOfWork.MockTestAttempts.AddAsync(attempt, token); + await unitOfWork.SaveChangesAsync(token); + + await unitOfWork.MockTestAnswers.AddRangeAsync(built.QuestionIds.Select(questionId => new MockTestAnswer + { + MockTestAttemptId = attempt.Id, + MockQuestionId = questionId, + SelectedOptionId = null, + IsCorrect = false, + }), token); + await unitOfWork.SaveChangesAsync(token); + + var started = BuildSnapshotResponse(attempt, snapshotDoc, snapshotDoc.StartedAt, isResumed: false); + started.AttemptType = AttemptTypeCourseFinal; + response = ApiResponse.Created(started); + }, cancellationToken); + return response!; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return ApiResponse.Fail( + "Không thể bắt đầu bài đánh giá cuối khóa.", HttpStatusCode.InternalServerError); + } + finally + { + userLock.Release(); + } + } + + private async Task<(ApiResponse? Resume, ApiResponse? Failure)> + CheckCourseFinalStartAsync(StudyCourse course, int userId, DateTime now, CancellationToken cancellationToken) + { + var attempts = await LoadCourseFinalAttemptsAsync(userId, cancellationToken); + var forEnrollment = CourseCompetencyPolicy.FinalAttemptsFor(attempts, course.Cohort!.Id, course.Id); + var state = CourseCompetencyPolicy.ResolveFinalState( + CourseCompetencyPolicy.IsClassCompleted(course), + CourseCompetencyPolicy.IsEligibleEnrollment(course), + forEnrollment, + now); + + switch (state.Availability) + { + case CourseFinalAvailability.InProgress: + var active = forEnrollment.First(x => x.Attempt.Id == state.Active!.Id); + var resumed = BuildSnapshotResponse(active.Attempt, active.Snapshot, now, isResumed: true); + resumed.AttemptType = AttemptTypeCourseFinal; + return (ApiResponse.Success(resumed), null); + case CourseFinalAvailability.Completed: + return (null, ApiResponse.Fail( + "Bạn đã hoàn thành bài đánh giá cuối khóa của lớp này.", + HttpStatusCode.Conflict, errorCode: ErrorCourseFinalCompleted, retryable: false)); + case CourseFinalAvailability.PendingSubmission: + return (null, ApiResponse.Fail( + "Bài đánh giá cuối khóa đã hết giờ. Hãy nộp bài để xem kết quả.", + HttpStatusCode.Conflict, errorCode: ErrorCourseFinalPendingSubmission, retryable: false)); + case CourseFinalAvailability.NotOpen: + return (null, ApiResponse.Fail( + "Bạn có thể thực hiện bài đánh giá cuối khóa sau khi lớp học hoàn thành.", + HttpStatusCode.Conflict, errorCode: ErrorCourseFinalNotOpen, retryable: false)); + case CourseFinalAvailability.NotEligible: + return (null, ApiResponse.Fail( + "Ghi danh của bạn không còn hiệu lực để thực hiện bài đánh giá cuối khóa.", + HttpStatusCode.Forbidden, errorCode: ErrorCourseFinalNotEligible, retryable: false)); + } + + if (state.AttemptsUsed >= CourseCompetencyPolicy.FinalAttemptLimit) + return (null, ApiResponse.Fail( + "Bạn đã sử dụng lượt đánh giá cuối khóa của lớp này.", + HttpStatusCode.Conflict, errorCode: ErrorCourseFinalCompleted, retryable: false)); + return (null, null); + } + + private CourseFinalAssessmentStatusResponse BuildCourseFinalStatus( + StudyCourse course, CourseCompetencyPolicy.FinalAttemptState state) + { + var levelCode = NormalizeLevelCode(course.Cohort?.Plan?.CertificateLevel?.Code ?? course.CertificateLevel?.Code); + var comparisonLevel = string.IsNullOrWhiteSpace(levelCode) ? null : PlacementAssessmentModePolicy.ComparisonLevel(levelCode); + var canStart = state.Availability is CourseFinalAvailability.Available or CourseFinalAvailability.InProgress + && (state.Availability == CourseFinalAvailability.InProgress + || state.AttemptsUsed < CourseCompetencyPolicy.FinalAttemptLimit); + return new CourseFinalAssessmentStatusResponse + { + EnrollmentId = course.Id, + CohortId = course.Cohort?.Id ?? 0, + CohortName = course.Cohort?.Name ?? course.Name, + LevelCode = string.IsNullOrWhiteSpace(levelCode) ? null : levelCode, + IsClassCompleted = CourseCompetencyPolicy.IsClassCompleted(course), + Availability = state.Availability, + CanStart = canStart, + CannotStartReason = canStart ? null : state.Availability, + AttemptLimit = CourseCompetencyPolicy.FinalAttemptLimit, + AttemptsUsed = state.AttemptsUsed, + ActiveAttemptId = state.Active?.Id, + ActiveAttemptExpiresAt = state.Active?.ExpiresAt is { } exp ? EnsureUtc(exp) : null, + PendingSubmissionAttemptId = state.PendingSubmission?.Id, + CompletedAttemptId = state.Official?.Id, + CompletedAtUtc = state.Official?.SubmittedAt is { } sub ? EnsureUtc(sub) : null, + PlannedLevelCodes = new[] { comparisonLevel, levelCode } + .Where(code => !string.IsNullOrWhiteSpace(code) && JlptCurriculum.IsSupportedStudyLevel(code)) + .Select(code => code!) + .Distinct() + .ToList(), + PlannedSkillCodes = Enum.GetValues().Select(s => s.ToString().ToLowerInvariant()).ToList(), + PlannedQuestionCount = PlannedAssessmentQuestionCount, + TimeLimitMinutes = PlacementTimeLimitMinutes, + }; + } + + private async Task LoadCourseForFinalAsync(int enrollmentId, CancellationToken cancellationToken) + => await unitOfWork.StudyCourses.Query().AsNoTracking() + .Include(c => c.CertificateLevel) + .Include(c => c.Cohort).ThenInclude(c => c!.Plan).ThenInclude(p => p.CertificateLevel) + .FirstOrDefaultAsync(c => c.Id == enrollmentId, cancellationToken); + + private async Task> LoadCourseFinalAttemptsAsync(int userId, CancellationToken cancellationToken) + => await unitOfWork.MockTestAttempts.Query().AsNoTracking() + .Where(a => a.UserId == userId && !a.IsDeleted && a.AttemptKind == AttemptKind.CourseAssessment) + .OrderByDescending(a => a.Id) + .ToListAsync(cancellationToken); + } +} diff --git a/RikiPath.Application/Services/PracticeTestService.cs b/RikiPath.Application/Services/PracticeTestService.cs index 0a1c0d2..bfc6b76 100644 --- a/RikiPath.Application/Services/PracticeTestService.cs +++ b/RikiPath.Application/Services/PracticeTestService.cs @@ -61,7 +61,7 @@ public static bool IsFutureExamDate(DateTime? targetExamDate, DateTime utcNow) => targetExamDate.HasValue && GetDaysUntilExam(targetExamDate.Value, utcNow) >= 1; } - public class PracticeTestService( + public partial class PracticeTestService( IUnitOfWork unitOfWork, IClaimService claimService, IMentorGroupPolicyService? groupPolicies = null, @@ -167,6 +167,7 @@ public async Task> GetStatusAsync( var displayResult = compatibility.CompatibleResult ?? compatibility.LatestResult; var allowance = await GetAttemptAllowanceAsync(userId, scopeLevelId, serverNow, cancellationToken); + var scopeAttempts = await GetScopeCompletedAttemptsAsync(userId, scopeLevelId, cancellationToken); var availableLevelIds = await GetAvailableAssessmentLevelIdsAsync(cancellationToken); int? assessedLevelId = displayResult is { AssessedJlptLevelId: > 0 } @@ -215,6 +216,7 @@ public async Task> GetStatusAsync( PlacementDecision = decision, HasActiveAttempt = activeAttempt is not null, AttemptAllowance = allowance, + CompletedAttempts = scopeAttempts, QuotaInitialized = true, CanStartNewAttempt = canStart, CannotStartReason = cannotStartReason, @@ -386,6 +388,12 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken => } var expiresAt = EnsureUtc(attempt.ExpiresAt ?? snapshotDoc.ExpiresAt); + if (await IsClassQuizLockedAsync(snapshotDoc, transactionCancellationToken)) + { + response = ApiResponse.Fail( + ClassRecordLock.Message, HttpStatusCode.Conflict, errorCode: ClassRecordLock.ErrorCode, retryable: false); + return; + } if (now >= expiresAt) { response = ApiResponse.Fail( @@ -586,288 +594,15 @@ private async Task> StartPlacement ? previousSnapshot.Questions.Select(question => question.QuestionId).ToHashSet() : []; - var tests = await unitOfWork.MockTests.GetAllWithSectionsAndQuestionsAsync(cancellationToken); - var approvedTestIds = (await ContentAuthoring.MockContentReviewState.ApprovedExamIds(unitOfWork) - .ToListAsync(cancellationToken)).ToHashSet(); var certificateFamilyId = explicitLevel?.CertificateTypeId ?? goal?.TargetCertificateLevel?.CertificateTypeId; - var allLevels = allLevelsRaw - .Where(l => !certificateFamilyId.HasValue || l.CertificateTypeId == certificateFamilyId.Value) - .ToList(); - - var supportedCatalogLevels = allLevels - .Select(l => (LevelId: l.Id, LevelCode: NormalizeLevelCode(l.Code), Rank: GetLevelRank(l.Code))) - .Where(l => JlptCurriculum.Rank(l.LevelCode) > 0) - .GroupBy(l => l.LevelCode) - .Select(g => g.OrderBy(x => x.LevelId).First()) - .OrderBy(l => l.Rank) - .ToDictionary(l => l.LevelCode); - - var levelById = allLevels - .Select(l => (LevelId: l.Id, LevelCode: NormalizeLevelCode(l.Code), Rank: GetLevelRank(l.Code))) - .Where(l => JlptCurriculum.Rank(l.LevelCode) > 0) - .ToDictionary(l => l.LevelId); - var comparisonLevelId = comparisonLevel is not null && supportedCatalogLevels.TryGetValue(comparisonLevel, out var lowerLevel) - ? (int?)lowerLevel.LevelId : null; - - var eligibleCandidates = new List<( - MockTest Test, - MockTestSection Section, - MockQuestion Question, - List ValidOptions, - int? CorrectOptionId, - string[]? OrderingTokens, - string[]? OrderingAnswerKey, - int LevelId, - string LevelCode, - int LevelRank)>(); - - var seenQuestionIds = new HashSet(); - - foreach (var test in (tests ?? []).Where(t => t is not null && !t.IsDeleted && t.Id > 0 && t.CertificateLevelId > 0 - && t.ExamKind == ExamKind.Placement - && !t.IsArchivedVersion - && (!t.IsManagedWorkflow || approvedTestIds.Contains(t.Id))).OrderBy(t => t.Id)) - { - if (test.CertificateLevel is { IsDeleted: true }) - { - continue; - } - - string? resolvedCode = null; - int resolvedLevelId = test.CertificateLevelId; - - if (test.CertificateLevel is { IsDeleted: false, Id: > 0 } navLevel && - !string.IsNullOrWhiteSpace(navLevel.Code)) - { - resolvedCode = NormalizeLevelCode(navLevel.Code); - resolvedLevelId = navLevel.Id; - } - else if (levelById.TryGetValue(test.CertificateLevelId, out var catLevel)) - { - resolvedCode = catLevel.LevelCode; - resolvedLevelId = catLevel.LevelId; - } - - if (resolvedCode is null || JlptCurriculum.Rank(resolvedCode) == 0 || resolvedLevelId <= 0 || - (scopeLevelId.HasValue && resolvedLevelId != scopeLevelId.Value && resolvedLevelId != comparisonLevelId)) - { - continue; - } - - var levelRank = GetLevelRank(resolvedCode); - if (!supportedCatalogLevels.ContainsKey(resolvedCode)) - { - supportedCatalogLevels[resolvedCode] = (resolvedLevelId, resolvedCode, levelRank); - } - - var orderedSections = (test.Sections ?? []) - .Where(s => s is not null && !s.IsDeleted && s.Id > 0) - .OrderBy(s => s.SortOrder) - .ThenBy(s => s.Id); - - foreach (var section in orderedSections) - { - var skill = JlptSkillAssessmentPolicy.Classify(section.LanguageSkill?.Name); - if (skill is null) continue; - var orderedQuestions = (section.Questions ?? []) - .Where(q => q is not null && !q.IsDeleted && q.Id > 0) - .OrderBy(q => q.SortOrder) - .ThenBy(q => q.Id); - - foreach (var question in orderedQuestions) - { - if (!HasUsablePrompt(question) || !seenQuestionIds.Add(question.Id)) - { - continue; - } - if (skill == JlptStudySkill.Listening && - string.IsNullOrWhiteSpace(ResolveQuestionAudioUrl(question))) - continue; - if (skill == JlptStudySkill.Reading && - (question.PassageId is not > 0 || question.Passage is null || question.Passage.IsDeleted || - string.IsNullOrWhiteSpace(question.Passage.PassageText))) - continue; - - if (SentenceOrdering.IsType(question.QuestionType)) - { - if (JlptSkillAssessmentPolicy.Classify(section.LanguageSkill?.Name) == JlptStudySkill.Grammar && - SentenceOrdering.TryRead(question.InteractionDataJson, question.AnswerKeyJson, out var tokens, out var answerKey)) - { - eligibleCandidates.Add((test, section, question, [], null, tokens, answerKey, - resolvedLevelId, resolvedCode, levelRank)); - } - continue; - } - - var validOptions = (question.Options ?? []) - .Where(o => o is not null && - !o.IsDeleted && - o.Id > 0 && - (!string.IsNullOrWhiteSpace(o.OptionText) || !string.IsNullOrWhiteSpace(o.ImageUrl))) - .OrderBy(o => o.SortOrder) - .ThenBy(o => o.Id) - .ToList(); - - if (validOptions.Count < 2) - { - continue; - } - - if (validOptions.Select(o => o.Id).Distinct().Count() != validOptions.Count) - { - continue; - } - - var correctOptions = validOptions.Where(o => o.IsCorrect).ToList(); - if (correctOptions.Count != 1) - { - continue; - } - - eligibleCandidates.Add(( - Test: test, - Section: section, - Question: question, - ValidOptions: validOptions, - CorrectOptionId: correctOptions[0].Id, - OrderingTokens: null, - OrderingAnswerKey: null, - LevelId: resolvedLevelId, - LevelCode: resolvedCode, - LevelRank: levelRank)); - } - } - } - - if (scopeCode is null) - return ApiResponse.Fail( - "Vui lòng đặt mục tiêu JLPT trước khi làm bài đánh giá năng lực.", - HttpStatusCode.BadRequest, errorCode: "LEARNING_GOAL_REQUIRED"); - - // Chia đều câu giữa cấp mục tiêu và cấp liền dưới để vẫn so sánh năng lực; - // N5 không có cấp so sánh nên dùng toàn bộ câu ở N5. - var selectionLevels = comparisonLevel is null - ? new[] { scopeCode } - : new[] { comparisonLevel, scopeCode }; - var selectedQuestions = eligibleCandidates.GetRange(0, 0); - var selectedReadingPassageIds = new HashSet(); - foreach (var skill in Enum.GetValues()) - { - foreach (var levelCode in selectionLevels) - { - var candidates = eligibleCandidates.Where(candidate => - candidate.LevelCode == levelCode && - JlptSkillAssessmentPolicy.Classify(candidate.Section.LanguageSkill?.Name) == skill).ToList(); - - if (skill == JlptStudySkill.Reading) - { - var passageCount = selectionLevels.Length == 1 ? PlacementReadingPassages : 1; - var passages = candidates - .GroupBy(candidate => candidate.Question.PassageId!.Value) - .Where(group => !selectedReadingPassageIds.Contains(group.Key) && - group.Count() >= PlacementReadingQuestionsPerPassage) - .ToList(); - SecureShuffle(passages); - passages = passages - .OrderBy(group => group.Count(candidate => previousQuestionIds.Contains(candidate.Question.Id))) - .Take(passageCount) - .ToList(); - if (passages.Count != passageCount) - return ApiResponse.Fail( - $"Ngân hàng Placement {levelCode} cần {passageCount} đoạn đọc khác nhau, mỗi đoạn có ít nhất {PlacementReadingQuestionsPerPassage} câu hợp lệ.", - HttpStatusCode.Conflict, errorCode: ErrorBankNotReady, retryable: false); - - foreach (var passage in passages) - { - selectedReadingPassageIds.Add(passage.Key); - var passageQuestions = passage.ToList(); - SecureShuffle(passageQuestions); - selectedQuestions.AddRange(passageQuestions - .OrderBy(candidate => previousQuestionIds.Contains(candidate.Question.Id)) - .Take(PlacementReadingQuestionsPerPassage)); - } - continue; - } - - var required = (skill switch - { - JlptStudySkill.Vocabulary => PlacementVocabularyQuestions, - JlptStudySkill.Grammar => PlacementGrammarQuestions, - _ => PlacementListeningQuestions, - }) / selectionLevels.Length; - if (candidates.Count < required) - return ApiResponse.Fail( - $"Ngân hàng Placement {levelCode} cần ít nhất {required} câu {JlptSkillAssessmentPolicy.Label(skill)} hợp lệ; hiện có {candidates.Count}.", - HttpStatusCode.Conflict, errorCode: ErrorBankNotReady, retryable: false); - - SecureShuffle(candidates); - selectedQuestions.AddRange(candidates - .OrderBy(candidate => previousQuestionIds.Contains(candidate.Question.Id)) - .Take(required)); - } - } - - var timeLimitMinutes = PlacementTimeLimitMinutes; - - var startedAt = EnsureUtc(UtcNowProvider()); - var expiresAt = EnsureUtc(startedAt.AddMinutes(timeLimitMinutes)); - - var snapshotDoc = new PlacementAttemptSnapshotDocument - { - SchemaVersion = 2, - AssessmentTargetLevelId = scopeLevelId, - IsComprehensiveAssessment = isComprehensive || !scopeLevelId.HasValue, - IsShortenedAssessment = false, - TimeLimitMinutes = timeLimitMinutes, - StartedAt = startedAt, - ExpiresAt = expiresAt, - CatalogLevels = supportedCatalogLevels.Values - .Where(level => !scopeLevelId.HasValue || selectedQuestions.Any(question => question.LevelId == level.LevelId)) - .OrderBy(l => l.Rank) - .Select(l => new PlacementSnapshotLevelCatalogItem - { - JlptLevelId = l.LevelId, - JlptLevelName = l.LevelCode, - Rank = l.Rank, - }) - .ToList(), - Questions = selectedQuestions.Select((item, index) => new PlacementSnapshotQuestionItem - { - QuestionId = item.Question.Id, - MockTestId = item.Test.Id, - MockTestSectionId = item.Section.Id, - SectionTitle = item.Section.Title ?? string.Empty, - SectionOrder = item.Section.SortOrder, - LanguageSkillName = item.Section.LanguageSkill?.Name ?? string.Empty, - JlptLevelId = item.LevelId, - JlptLevelName = item.LevelCode, - Order = index + 1, - Content = item.Question.QuestionText ?? string.Empty, - AudioUrl = ResolveQuestionAudioUrl(item.Question), - ImageUrl = item.Question.ImageUrl, - PassageId = item.Question.PassageId, - PassageTitle = item.Question.Passage?.Title, - PassageText = JlptSkillAssessmentPolicy.Classify(item.Section.LanguageSkill?.Name) == JlptStudySkill.Reading - ? item.Question.Passage?.PassageText : null, - PassageInstructions = JlptSkillAssessmentPolicy.Classify(item.Section.LanguageSkill?.Name) == JlptStudySkill.Reading - ? item.Question.Passage?.Instructions : null, - PassageImageUrl = JlptSkillAssessmentPolicy.Classify(item.Section.LanguageSkill?.Name) == JlptStudySkill.Reading - ? item.Question.Passage?.ImageUrl : null, - CorrectOptionId = item.CorrectOptionId, - OrderingTokens = item.OrderingTokens, - OrderingAnswerKey = item.OrderingAnswerKey, - SelectedOptionId = null, - IsCorrect = false, - Options = item.ValidOptions.Select(opt => new PlacementSnapshotOptionItem - { - OptionId = opt.Id, - Content = opt.OptionText, - ImageUrl = opt.ImageUrl, - Order = opt.SortOrder, - IsCorrect = opt.IsCorrect, - }).ToList(), - }).ToList(), - }; + var built = await BuildAssessmentSnapshotAsync( + scopeLevelId, scopeCode, isComprehensive, comparisonLevel, certificateFamilyId, + allLevelsRaw, previousQuestionIds, cancellationToken); + if (built.Failure is not null) return built.Failure; + var snapshotDoc = built.Snapshot!; + var selectedQuestionIds = built.QuestionIds; + var startedAt = snapshotDoc.StartedAt; + var expiresAt = snapshotDoc.ExpiresAt; var snapshotJson = JsonSerializer.Serialize(snapshotDoc, SnapshotJsonOptions); @@ -946,10 +681,10 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken => await unitOfWork.MockTestAttempts.AddAsync(attempt, transactionCancellationToken); await unitOfWork.SaveChangesAsync(transactionCancellationToken); - var answerRows = selectedQuestions.Select(item => new MockTestAnswer + var answerRows = selectedQuestionIds.Select(questionId => new MockTestAnswer { MockTestAttemptId = attempt.Id, - MockQuestionId = item.Question.Id, + MockQuestionId = questionId, SelectedOptionId = null, IsCorrect = false, }); @@ -999,6 +734,307 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken => } } + /// + /// Shared question selection for the competency assessment engine (Placement and CourseFinal): + /// same per-skill structure, level scope (target + one lower comparison level), audio/passage validity rules, + /// and preference for questions the learner has not seen before. + /// + private async Task<(PlacementAttemptSnapshotDocument? Snapshot, List QuestionIds, ApiResponse? Failure)> + BuildAssessmentSnapshotAsync( + int? scopeLevelId, + string? scopeCode, + bool isComprehensive, + string? comparisonLevel, + int? certificateFamilyId, + List allLevelsRaw, + HashSet previousQuestionIds, + CancellationToken cancellationToken) + { + var tests = await unitOfWork.MockTests.GetAllWithSectionsAndQuestionsAsync(cancellationToken); + var approvedTestIds = (await ContentAuthoring.MockContentReviewState.ApprovedExamIds(unitOfWork) + .ToListAsync(cancellationToken)).ToHashSet(); + var allLevels = allLevelsRaw + .Where(l => !certificateFamilyId.HasValue || l.CertificateTypeId == certificateFamilyId.Value) + .ToList(); + + var supportedCatalogLevels = allLevels + .Select(l => (LevelId: l.Id, LevelCode: NormalizeLevelCode(l.Code), Rank: GetLevelRank(l.Code))) + .Where(l => JlptCurriculum.Rank(l.LevelCode) > 0) + .GroupBy(l => l.LevelCode) + .Select(g => g.OrderBy(x => x.LevelId).First()) + .OrderBy(l => l.Rank) + .ToDictionary(l => l.LevelCode); + + var levelById = allLevels + .Select(l => (LevelId: l.Id, LevelCode: NormalizeLevelCode(l.Code), Rank: GetLevelRank(l.Code))) + .Where(l => JlptCurriculum.Rank(l.LevelCode) > 0) + .ToDictionary(l => l.LevelId); + var comparisonLevelId = comparisonLevel is not null && supportedCatalogLevels.TryGetValue(comparisonLevel, out var lowerLevel) + ? (int?)lowerLevel.LevelId : null; + + var eligibleCandidates = new List<( + MockTest Test, + MockTestSection Section, + MockQuestion Question, + List ValidOptions, + int? CorrectOptionId, + string[]? OrderingTokens, + string[]? OrderingAnswerKey, + int LevelId, + string LevelCode, + int LevelRank)>(); + + var seenQuestionIds = new HashSet(); + + foreach (var test in (tests ?? []).Where(t => t is not null && !t.IsDeleted && t.Id > 0 && t.CertificateLevelId > 0 + && t.ExamKind == ExamKind.Placement + && !t.IsArchivedVersion + && (!t.IsManagedWorkflow || approvedTestIds.Contains(t.Id))).OrderBy(t => t.Id)) + { + if (test.CertificateLevel is { IsDeleted: true }) + { + continue; + } + + string? resolvedCode = null; + int resolvedLevelId = test.CertificateLevelId; + + if (test.CertificateLevel is { IsDeleted: false, Id: > 0 } navLevel && + !string.IsNullOrWhiteSpace(navLevel.Code)) + { + resolvedCode = NormalizeLevelCode(navLevel.Code); + resolvedLevelId = navLevel.Id; + } + else if (levelById.TryGetValue(test.CertificateLevelId, out var catLevel)) + { + resolvedCode = catLevel.LevelCode; + resolvedLevelId = catLevel.LevelId; + } + + if (resolvedCode is null || JlptCurriculum.Rank(resolvedCode) == 0 || resolvedLevelId <= 0 || + (scopeLevelId.HasValue && resolvedLevelId != scopeLevelId.Value && resolvedLevelId != comparisonLevelId)) + { + continue; + } + + var levelRank = GetLevelRank(resolvedCode); + if (!supportedCatalogLevels.ContainsKey(resolvedCode)) + { + supportedCatalogLevels[resolvedCode] = (resolvedLevelId, resolvedCode, levelRank); + } + + var orderedSections = (test.Sections ?? []) + .Where(s => s is not null && !s.IsDeleted && s.Id > 0) + .OrderBy(s => s.SortOrder) + .ThenBy(s => s.Id); + + foreach (var section in orderedSections) + { + var skill = JlptSkillAssessmentPolicy.Classify(section.LanguageSkill?.Name); + if (skill is null) continue; + var orderedQuestions = (section.Questions ?? []) + .Where(q => q is not null && !q.IsDeleted && q.Id > 0) + .OrderBy(q => q.SortOrder) + .ThenBy(q => q.Id); + + foreach (var question in orderedQuestions) + { + if (!HasUsablePrompt(question) || !seenQuestionIds.Add(question.Id)) + { + continue; + } + if (skill == JlptStudySkill.Listening && + string.IsNullOrWhiteSpace(ResolveQuestionAudioUrl(question))) + continue; + if (skill == JlptStudySkill.Reading && + (question.PassageId is not > 0 || question.Passage is null || question.Passage.IsDeleted || + string.IsNullOrWhiteSpace(question.Passage.PassageText))) + continue; + + if (SentenceOrdering.IsType(question.QuestionType)) + { + if (JlptSkillAssessmentPolicy.Classify(section.LanguageSkill?.Name) == JlptStudySkill.Grammar && + SentenceOrdering.TryRead(question.InteractionDataJson, question.AnswerKeyJson, out var tokens, out var answerKey)) + { + eligibleCandidates.Add((test, section, question, [], null, tokens, answerKey, + resolvedLevelId, resolvedCode, levelRank)); + } + continue; + } + + var validOptions = (question.Options ?? []) + .Where(o => o is not null && + !o.IsDeleted && + o.Id > 0 && + (!string.IsNullOrWhiteSpace(o.OptionText) || !string.IsNullOrWhiteSpace(o.ImageUrl))) + .OrderBy(o => o.SortOrder) + .ThenBy(o => o.Id) + .ToList(); + + if (validOptions.Count < 2) + { + continue; + } + + if (validOptions.Select(o => o.Id).Distinct().Count() != validOptions.Count) + { + continue; + } + + var correctOptions = validOptions.Where(o => o.IsCorrect).ToList(); + if (correctOptions.Count != 1) + { + continue; + } + + eligibleCandidates.Add(( + Test: test, + Section: section, + Question: question, + ValidOptions: validOptions, + CorrectOptionId: correctOptions[0].Id, + OrderingTokens: null, + OrderingAnswerKey: null, + LevelId: resolvedLevelId, + LevelCode: resolvedCode, + LevelRank: levelRank)); + } + } + } + + if (scopeCode is null) + return (null, [], ApiResponse.Fail( + "Vui lòng đặt mục tiêu JLPT trước khi làm bài đánh giá năng lực.", + HttpStatusCode.BadRequest, errorCode: "LEARNING_GOAL_REQUIRED")); + + // Chia đều câu giữa cấp mục tiêu và cấp liền dưới để vẫn so sánh năng lực; + // N5 không có cấp so sánh nên dùng toàn bộ câu ở N5. + var selectionLevels = comparisonLevel is null + ? new[] { scopeCode } + : new[] { comparisonLevel, scopeCode }; + var selectedQuestions = eligibleCandidates.GetRange(0, 0); + var selectedReadingPassageIds = new HashSet(); + foreach (var skill in Enum.GetValues()) + { + foreach (var levelCode in selectionLevels) + { + var candidates = eligibleCandidates.Where(candidate => + candidate.LevelCode == levelCode && + JlptSkillAssessmentPolicy.Classify(candidate.Section.LanguageSkill?.Name) == skill).ToList(); + + if (skill == JlptStudySkill.Reading) + { + var passageCount = selectionLevels.Length == 1 ? PlacementReadingPassages : 1; + var passages = candidates + .GroupBy(candidate => candidate.Question.PassageId!.Value) + .Where(group => !selectedReadingPassageIds.Contains(group.Key) && + group.Count() >= PlacementReadingQuestionsPerPassage) + .ToList(); + SecureShuffle(passages); + passages = passages + .OrderBy(group => group.Count(candidate => previousQuestionIds.Contains(candidate.Question.Id))) + .Take(passageCount) + .ToList(); + if (passages.Count != passageCount) + return (null, [], ApiResponse.Fail( + $"Ngân hàng Placement {levelCode} cần {passageCount} đoạn đọc khác nhau, mỗi đoạn có ít nhất {PlacementReadingQuestionsPerPassage} câu hợp lệ.", + HttpStatusCode.Conflict, errorCode: ErrorBankNotReady, retryable: false)); + + foreach (var passage in passages) + { + selectedReadingPassageIds.Add(passage.Key); + var passageQuestions = passage.ToList(); + SecureShuffle(passageQuestions); + selectedQuestions.AddRange(passageQuestions + .OrderBy(candidate => previousQuestionIds.Contains(candidate.Question.Id)) + .Take(PlacementReadingQuestionsPerPassage)); + } + continue; + } + + var required = (skill switch + { + JlptStudySkill.Vocabulary => PlacementVocabularyQuestions, + JlptStudySkill.Grammar => PlacementGrammarQuestions, + _ => PlacementListeningQuestions, + }) / selectionLevels.Length; + if (candidates.Count < required) + return (null, [], ApiResponse.Fail( + $"Ngân hàng Placement {levelCode} cần ít nhất {required} câu {JlptSkillAssessmentPolicy.Label(skill)} hợp lệ; hiện có {candidates.Count}.", + HttpStatusCode.Conflict, errorCode: ErrorBankNotReady, retryable: false)); + + SecureShuffle(candidates); + selectedQuestions.AddRange(candidates + .OrderBy(candidate => previousQuestionIds.Contains(candidate.Question.Id)) + .Take(required)); + } + } + + var timeLimitMinutes = PlacementTimeLimitMinutes; + + var startedAt = EnsureUtc(UtcNowProvider()); + var expiresAt = EnsureUtc(startedAt.AddMinutes(timeLimitMinutes)); + + var snapshotDoc = new PlacementAttemptSnapshotDocument + { + SchemaVersion = 2, + AssessmentTargetLevelId = scopeLevelId, + IsComprehensiveAssessment = isComprehensive || !scopeLevelId.HasValue, + IsShortenedAssessment = false, + TimeLimitMinutes = timeLimitMinutes, + StartedAt = startedAt, + ExpiresAt = expiresAt, + CatalogLevels = supportedCatalogLevels.Values + .Where(level => !scopeLevelId.HasValue || selectedQuestions.Any(question => question.LevelId == level.LevelId)) + .OrderBy(l => l.Rank) + .Select(l => new PlacementSnapshotLevelCatalogItem + { + JlptLevelId = l.LevelId, + JlptLevelName = l.LevelCode, + Rank = l.Rank, + }) + .ToList(), + Questions = selectedQuestions.Select((item, index) => new PlacementSnapshotQuestionItem + { + QuestionId = item.Question.Id, + MockTestId = item.Test.Id, + MockTestSectionId = item.Section.Id, + SectionTitle = item.Section.Title ?? string.Empty, + SectionOrder = item.Section.SortOrder, + LanguageSkillName = item.Section.LanguageSkill?.Name ?? string.Empty, + JlptLevelId = item.LevelId, + JlptLevelName = item.LevelCode, + Order = index + 1, + Content = item.Question.QuestionText ?? string.Empty, + AudioUrl = ResolveQuestionAudioUrl(item.Question), + ImageUrl = item.Question.ImageUrl, + PassageId = item.Question.PassageId, + PassageTitle = item.Question.Passage?.Title, + PassageText = JlptSkillAssessmentPolicy.Classify(item.Section.LanguageSkill?.Name) == JlptStudySkill.Reading + ? item.Question.Passage?.PassageText : null, + PassageInstructions = JlptSkillAssessmentPolicy.Classify(item.Section.LanguageSkill?.Name) == JlptStudySkill.Reading + ? item.Question.Passage?.Instructions : null, + PassageImageUrl = JlptSkillAssessmentPolicy.Classify(item.Section.LanguageSkill?.Name) == JlptStudySkill.Reading + ? item.Question.Passage?.ImageUrl : null, + CorrectOptionId = item.CorrectOptionId, + OrderingTokens = item.OrderingTokens, + OrderingAnswerKey = item.OrderingAnswerKey, + SelectedOptionId = null, + IsCorrect = false, + Options = item.ValidOptions.Select(opt => new PlacementSnapshotOptionItem + { + OptionId = opt.Id, + Content = opt.OptionText, + ImageUrl = opt.ImageUrl, + Order = opt.SortOrder, + IsCorrect = opt.IsCorrect, + }).ToList(), + }).ToList(), + }; + + return (snapshotDoc, selectedQuestions.Select(item => item.Question.Id).ToList(), null); + } + public async Task> SubmitPlacementTestAsync( int attemptId, SubmitPlacementTestRequest request, @@ -1023,7 +1059,7 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken => transactionCancellationToken); if (attempt is null || - attempt.AttemptKind != AttemptKind.Placement || + !IsAssessmentEngineKind(attempt.AttemptKind) || attempt.UserId != userId) { response = ApiResponse.NotFound( @@ -1105,7 +1141,8 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken => } var expiresAt = EnsureUtc(attempt.ExpiresAt ?? snapshotDoc.ExpiresAt); - var isExpired = serverNow >= expiresAt; + // A class quiz of a completed class is closed from the answers saved before the lock (nothing new accepted). + var isExpired = serverNow >= expiresAt || await IsClassQuizLockedAsync(snapshotDoc, transactionCancellationToken); if (request?.Answers is null) { @@ -1179,93 +1216,18 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken => ApplyPlacementSelection(snapshotQuestionsById[submittedAnswer.QuestionId], submittedAnswer); } - foreach (var question in snapshotDoc.Questions) - question.IsCorrect = question.OrderingAnswerKey is { } answerKey - ? question.OrderingResponse is { } sequence && sequence.SequenceEqual(answerKey) - : question.CorrectOptionId.HasValue && question.SelectedOptionId == question.CorrectOptionId; - - var existingAnswerRows = await unitOfWork.MockTestAnswers.GetByAttemptIdAsync( - attemptId, - transactionCancellationToken); - if (existingAnswerRows.Count > 0) - { - var answerRowsByQuestionId = existingAnswerRows.ToDictionary(a => a.MockQuestionId); - foreach (var frozenQuestion in snapshotDoc.Questions) - { - if (answerRowsByQuestionId.TryGetValue(frozenQuestion.QuestionId, out var answerRow)) - { - SetPersistedPlacementSelection(answerRow, frozenQuestion); - answerRow.IsCorrect = frozenQuestion.IsCorrect; - } - } - } - - var sectionResults = BuildSectionResultsFromSnapshot(attemptId, snapshotDoc.Questions); - var existingSectionResults = await unitOfWork.MockTestSectionResults.GetByAttemptIdAsync( - attemptId, - transactionCancellationToken); - if (existingSectionResults.Count == 0 && sectionResults.Entities.Count > 0) - { - await unitOfWork.MockTestSectionResults.AddRangeAsync( - sectionResults.Entities, - transactionCancellationToken); - } - - var evaluation = EvaluateLevelsFromSnapshot( - snapshotDoc.Questions, - snapshotDoc.CatalogLevels, - sectionResults.OverallScore); - - var isTargetAssessment = snapshotDoc.AssessmentTargetLevelId.HasValue && - !snapshotDoc.ParentAssessmentAttemptId.HasValue && !snapshotDoc.IsComprehensiveAssessment; - var targetLevel = evaluation.LevelBreakdowns - .FirstOrDefault(level => level.JlptLevelId == snapshotDoc.AssessmentTargetLevelId); - var canonicalResult = new PlacementTestResultResponse - { - AttemptId = attempt.Id, - AttemptType = AttemptTypePlacement, - Status = StatusCompleted, - StartedAt = EnsureUtc(attempt.StartedAt), - DurationSeconds = Math.Max(0, (int)( - (isExpired ? expiresAt : serverNow) - EnsureUtc(attempt.StartedAt)).TotalSeconds), - SubmittedAt = serverNow, - AssessmentTargetLevelId = snapshotDoc.AssessmentTargetLevelId, - IsComprehensiveAssessment = snapshotDoc.IsComprehensiveAssessment, - IsShortenedAssessment = snapshotDoc.IsShortenedAssessment, - ParentAssessmentAttemptId = snapshotDoc.ParentAssessmentAttemptId, - TotalScore = sectionResults.OverallScore, - CorrectCount = snapshotDoc.Questions.Count(q => q.IsCorrect), - NotStudiedCount = snapshotDoc.Questions.Count(q => q.SelectedOptionId == NotStudiedOptionId), - TotalQuestions = snapshotDoc.Questions.Count, - AssessedJlptLevelId = evaluation.AssessedLevelId, - AssessedJlptLevelName = evaluation.AssessedLevelName, - RecommendedTargetJlptLevelId = targetLevel?.JlptLevelId ?? evaluation.RecommendedTargetLevelId, - RecommendedTargetJlptLevelName = targetLevel?.JlptLevelName ?? evaluation.RecommendedTargetLevelName, - WrongQuestionIds = snapshotDoc.Questions - .Where(q => !q.IsCorrect) - .Select(q => q.QuestionId) - .OrderBy(id => id) - .ToList(), - LevelBreakdowns = evaluation.LevelBreakdowns, - Sections = sectionResults.Responses, - }; - - snapshotDoc.CompletedResult = canonicalResult; - if (recoverEarlyClosure) - { - attempt.IsDeleted = false; - } - attempt.SubmittedAt = serverNow; - attempt.IsCompleted = true; - attempt.TotalScore = sectionResults.OverallScore; - attempt.QuestionSnapshotJson = JsonSerializer.Serialize(snapshotDoc, SnapshotJsonOptions); - unitOfWork.MockTestAttempts.Update(attempt); + var graded = await GradeAndCompleteAttemptAsync( + attempt, snapshotDoc, serverNow, expiresAt, isExpired, recoverEarlyClosure, transactionCancellationToken); + var canonicalResult = graded.Result; + var evaluation = (AssessedLevelId: graded.AssessedLevelId, Unused: 0); + var isCourseFinal = attempt.AttemptKind == AttemptKind.CourseAssessment; // Assessment updates estimated proficiency level (AssessedCertificateLevelId) and PlacementDecision // strictly without mutating TargetCertificateLevelId or StartingCertificateLevelId. var learner = await unitOfWork.UserAccounts.GetByIdForUpdateAsync( userId, transactionCancellationToken); - if (learner is not null && !snapshotDoc.ParentAssessmentAttemptId.HasValue) + // An end-of-course assessment is a class milestone: it never changes the learner's global level or Placement decision. + if (learner is not null && !isCourseFinal && !snapshotDoc.ParentAssessmentAttemptId.HasValue) { if (evaluation.AssessedLevelId > 0) learner.AssessedCertificateLevelId = evaluation.AssessedLevelId; @@ -1300,7 +1262,7 @@ await unitOfWork.MockTestSectionResults.AddRangeAsync( var latestAttempt = await LoadPlacementAttemptByIdAsync(attemptId, cancellationToken); if (latestAttempt is not null && !latestAttempt.IsDeleted && - latestAttempt.AttemptKind == AttemptKind.Placement && + IsAssessmentEngineKind(latestAttempt.AttemptKind) && latestAttempt.UserId == userId && latestAttempt.IsCompleted) { @@ -1345,6 +1307,107 @@ await unitOfWork.MockTestSectionResults.AddRangeAsync( } } + /// + /// Engine scoring core shared by learner submission and server-side finalisation of expired attempts: + /// marks every frozen question, persists answer/section rows and the canonical result on the attempt. + /// Class quiz attempts also complete their assignment. The caller saves the unit of work. + /// + private async Task<(PlacementTestResultResponse Result, int AssessedLevelId)> GradeAndCompleteAttemptAsync( + MockTestAttempt attempt, + PlacementAttemptSnapshotDocument snapshotDoc, + DateTime serverNow, + DateTime expiresAt, + bool isExpired, + bool recoverEarlyClosure, + CancellationToken cancellationToken) + { + foreach (var question in snapshotDoc.Questions) + question.IsCorrect = question.OrderingAnswerKey is { } answerKey + ? question.OrderingResponse is { } sequence && sequence.SequenceEqual(answerKey) + : question.CorrectOptionId.HasValue && question.SelectedOptionId == question.CorrectOptionId; + + var existingAnswerRows = await unitOfWork.MockTestAnswers.GetByAttemptIdAsync( + attempt.Id, + cancellationToken); + if (existingAnswerRows.Count > 0) + { + var answerRowsByQuestionId = existingAnswerRows.ToDictionary(a => a.MockQuestionId); + foreach (var frozenQuestion in snapshotDoc.Questions) + { + if (answerRowsByQuestionId.TryGetValue(frozenQuestion.QuestionId, out var answerRow)) + { + SetPersistedPlacementSelection(answerRow, frozenQuestion); + answerRow.IsCorrect = frozenQuestion.IsCorrect; + } + } + } + + var sectionResults = BuildSectionResultsFromSnapshot(attempt.Id, snapshotDoc.Questions); + var existingSectionResults = await unitOfWork.MockTestSectionResults.GetByAttemptIdAsync( + attempt.Id, + cancellationToken); + if (existingSectionResults.Count == 0 && sectionResults.Entities.Count > 0) + { + await unitOfWork.MockTestSectionResults.AddRangeAsync( + sectionResults.Entities, + cancellationToken); + } + + var evaluation = EvaluateLevelsFromSnapshot( + snapshotDoc.Questions, + snapshotDoc.CatalogLevels, + sectionResults.OverallScore); + + var isTargetAssessment = snapshotDoc.AssessmentTargetLevelId.HasValue && + !snapshotDoc.ParentAssessmentAttemptId.HasValue && !snapshotDoc.IsComprehensiveAssessment; + var targetLevel = evaluation.LevelBreakdowns + .FirstOrDefault(level => level.JlptLevelId == snapshotDoc.AssessmentTargetLevelId); + var isCourseFinal = attempt.AttemptKind == AttemptKind.CourseAssessment; + var canonicalResult = new PlacementTestResultResponse + { + AttemptId = attempt.Id, + AttemptType = isCourseFinal ? AttemptTypeCourseFinal : AttemptTypePlacement, + Status = StatusCompleted, + StartedAt = EnsureUtc(attempt.StartedAt), + DurationSeconds = Math.Max(0, (int)( + (isExpired ? expiresAt : serverNow) - EnsureUtc(attempt.StartedAt)).TotalSeconds), + SubmittedAt = serverNow, + AssessmentTargetLevelId = snapshotDoc.AssessmentTargetLevelId, + IsComprehensiveAssessment = snapshotDoc.IsComprehensiveAssessment, + IsShortenedAssessment = snapshotDoc.IsShortenedAssessment, + ParentAssessmentAttemptId = snapshotDoc.ParentAssessmentAttemptId, + TotalScore = sectionResults.OverallScore, + CorrectCount = snapshotDoc.Questions.Count(q => q.IsCorrect), + NotStudiedCount = snapshotDoc.Questions.Count(q => q.SelectedOptionId == NotStudiedOptionId), + TotalQuestions = snapshotDoc.Questions.Count, + AssessedJlptLevelId = evaluation.AssessedLevelId, + AssessedJlptLevelName = evaluation.AssessedLevelName, + RecommendedTargetJlptLevelId = targetLevel?.JlptLevelId ?? evaluation.RecommendedTargetLevelId, + RecommendedTargetJlptLevelName = targetLevel?.JlptLevelName ?? evaluation.RecommendedTargetLevelName, + WrongQuestionIds = snapshotDoc.Questions + .Where(q => !q.IsCorrect) + .Select(q => q.QuestionId) + .OrderBy(id => id) + .ToList(), + LevelBreakdowns = evaluation.LevelBreakdowns, + Sections = sectionResults.Responses, + }; + ApplyEvaluationCounts(canonicalResult, snapshotDoc.Questions); + + snapshotDoc.CompletedResult = canonicalResult; + if (recoverEarlyClosure) + { + attempt.IsDeleted = false; + } + attempt.SubmittedAt = serverNow; + attempt.IsCompleted = true; + attempt.TotalScore = sectionResults.OverallScore; + attempt.QuestionSnapshotJson = JsonSerializer.Serialize(snapshotDoc, SnapshotJsonOptions); + unitOfWork.MockTestAttempts.Update(attempt); + await CompleteClassQuizAssignmentAsync(attempt, snapshotDoc, serverNow, cancellationToken); + return (canonicalResult, evaluation.AssessedLevelId); + } + public async Task> GetPlacementTestResultAsync( int attemptId, CancellationToken cancellationToken = default) @@ -1355,7 +1418,7 @@ public async Task> GetPlacementTestResu var attempt = await LoadPlacementAttemptByIdAsync(attemptId, cancellationToken); if (attempt is null || attempt.IsDeleted || - attempt.AttemptKind != AttemptKind.Placement || + !IsAssessmentEngineKind(attempt.AttemptKind) || attempt.UserId != userId) { return ApiResponse.NotFound( @@ -1693,7 +1756,7 @@ private async Task> LoadUserPlacementAttemptsAsync( { var attempt = await unitOfWork.MockTestAttempts.GetPlacementByIdAsync(attemptId, cancellationToken); attempt ??= await unitOfWork.MockTestAttempts.GetByIdAsync(attemptId, cancellationToken); - if (attempt is null || attempt.IsDeleted || attempt.AttemptKind != AttemptKind.Placement) + if (attempt is null || attempt.IsDeleted || !IsAssessmentEngineKind(attempt.AttemptKind)) { return null; } @@ -1718,7 +1781,7 @@ private async Task> LoadUserPlacementAttemptsAsync( } attempt ??= await unitOfWork.MockTestAttempts.GetByIdAsync(attemptId, cancellationToken); - if (attempt is null || attempt.AttemptKind != AttemptKind.Placement) + if (attempt is null || !IsAssessmentEngineKind(attempt.AttemptKind)) { return null; } @@ -1772,6 +1835,35 @@ internal static (MockTestAttempt? Attempt, PlacementTestResultResponse? Recovere .ThenByDescending(item => item.Attempt!.Id) .FirstOrDefault(); + /// + /// Fills the graded-question scope used by every analysis view: a listening section without audio evidence + /// (the same rule the skill breakdown uses) is "chưa đánh giá" and leaves the denominator. Stored scores are untouched. + /// Blank = no answer or the "chưa học" option. + /// + internal static void ApplyEvaluationCounts(PlacementTestResultResponse result, IReadOnlyCollection? questions) + { + var unevaluated = (result.Sections ?? []) + .Where(s => JlptSkillAssessmentPolicy.Classify(s.LanguageSkillName) == JlptStudySkill.Listening && s.HasAudioEvidence == false) + .Select(s => (s.MockTestSectionId, s.JlptLevelId)) + .ToHashSet(); + if (questions is { Count: > 0 }) + { + var evaluated = questions.Where(q => !unevaluated.Contains((q.MockTestSectionId, q.JlptLevelId))).ToList(); + result.EvaluatedQuestionCount = evaluated.Count; + result.EvaluatedCorrectCount = evaluated.Count(q => q.IsCorrect); + result.EvaluatedBlankCount = evaluated.Count(q => q.SelectedOptionId is null || q.SelectedOptionId == NotStudiedOptionId); + result.UnevaluatedQuestionCount = questions.Count - evaluated.Count; + } + else if (result.Sections is { Count: > 0 } sections) + { + var evaluated = sections.Where(s => !unevaluated.Contains((s.MockTestSectionId, s.JlptLevelId))).ToList(); + result.EvaluatedQuestionCount = evaluated.Sum(s => s.TotalCount); + result.EvaluatedCorrectCount = evaluated.Sum(s => s.CorrectCount); + result.EvaluatedBlankCount = null; + result.UnevaluatedQuestionCount = Math.Max(0, result.TotalQuestions - result.EvaluatedQuestionCount.Value); + } + } + internal static PlacementTestResultResponse? TryGetCompletedResultFromSnapshot(string? snapshotJson) { if (!TryDeserializeSnapshot(snapshotJson, out var snapshotDoc) || @@ -1780,6 +1872,7 @@ snapshotDoc.CompletedResult is not { } completedResult || { return null; } + ApplyEvaluationCounts(completedResult, snapshotDoc.Questions); // Older low results stored no recommendation while waiting for a mini assessment. if (completedResult.ScreeningLevelName is { } targetLevel) @@ -2098,7 +2191,7 @@ private static ( var targetBreakdown = evaluation.LevelBreakdowns .FirstOrDefault(level => level.JlptLevelId == snapshotDoc.AssessmentTargetLevelId); - return new PlacementTestResultResponse + var tierOne = new PlacementTestResultResponse { AttemptId = attempt.Id, AttemptType = AttemptTypePlacement, @@ -2128,6 +2221,8 @@ private static ( IsLegacyRecovered = true, HasCompleteSkillData = sectionResults.Responses.Count > 0, }; + ApplyEvaluationCounts(tierOne, snapshotDoc.Questions); + return tierOne; } // Tier 2: Reconstruct strictly from persisted MockTestSectionResults & MockTestAnswers @@ -2367,17 +2462,17 @@ internal static bool TryDeserializeSnapshot( } } - private static bool HasUsablePrompt(MockQuestion question) + internal static bool HasUsablePrompt(MockQuestion question) => !string.IsNullOrWhiteSpace(question.QuestionText) || !string.IsNullOrWhiteSpace(question.ImageUrl) || !string.IsNullOrWhiteSpace(ResolveQuestionAudioUrl(question)); - private static string? ResolveQuestionAudioUrl(MockQuestion question) + internal static string? ResolveQuestionAudioUrl(MockQuestion question) => !string.IsNullOrWhiteSpace(question.AudioUrl) ? question.AudioUrl : question.Passage?.AudioUrl; - private static void SecureShuffle(IList items) + internal static void SecureShuffle(IList items) { for (var index = items.Count - 1; index > 0; index--) { @@ -2395,6 +2490,14 @@ private static bool IsSupportedLevel(string? levelCode) private async Task PopulatePlacementResultDetailsAsync( PlacementTestResultResponse result, int userId, string? snapshotJson, CancellationToken cancellationToken) { + // Class quiz: per-question correctness stays hidden here; the quiz result API applies the release policy. + if (TryDeserializeSnapshot(snapshotJson, out var quizSnapshot) + && string.Equals(quizSnapshot.Purpose, ClassQuizPurpose, StringComparison.Ordinal)) + { + result.AttemptType = ClassQuizPurpose; + result.WrongQuestionIds = []; + return; + } var goal = await unitOfWork.UserAccounts.GetWithLearningGoalAsync(userId, cancellationToken); var targetCode = goal?.TargetCertificateLevel?.Code; if (string.IsNullOrWhiteSpace(targetCode) && goal?.TargetCertificateLevelId is int goalLevelId) @@ -2477,6 +2580,34 @@ private async Task> GetAvailableAssessmentLevelIdsAsync(CancellationTo .ToList(); } + /// + /// Completed attempts in the same quota scope as (same snapshot rules), numbered by + /// start order so "Lần 1/Lần 2" never changes after refresh or a later attempt. Read-only; scores are the stored ones. + /// + private async Task> GetScopeCompletedAttemptsAsync(int userId, int? scopeLevelId, + CancellationToken cancellationToken) + { + var attempts = await unitOfWork.MockTestAttempts.Query().AsNoTracking() + .Where(attempt => attempt.UserId == userId && attempt.AttemptKind == AttemptKind.Placement) + .OrderBy(attempt => attempt.Id) + .Select(attempt => new { attempt.Id, attempt.IsDeleted, attempt.IsCompleted, attempt.SubmittedAt, attempt.TotalScore, attempt.QuestionSnapshotJson }) + .ToListAsync(cancellationToken); + var result = new List(); + var number = 0; + foreach (var attempt in attempts) + { + if (!TryDeserializeSnapshot(attempt.QuestionSnapshotJson, out var snapshot) || + snapshot.ParentAssessmentAttemptId.HasValue || + !HasValidSnapshotQuestions(snapshot.Questions) || + snapshot.AssessmentTargetLevelId != scopeLevelId) continue; + number++; + if (attempt.IsCompleted && !attempt.IsDeleted) + result.Add(new PlacementScopeAttemptResponse(attempt.Id, number, + attempt.SubmittedAt is { } sub ? EnsureUtc(sub) : null, attempt.TotalScore)); + } + return result; + } + private async Task GetAttemptAllowanceAsync(int userId, int? scopeLevelId, DateTime now, CancellationToken cancellationToken) { @@ -2619,6 +2750,15 @@ internal sealed class PlacementAttemptSnapshotDocument public List CatalogLevels { get; set; } = []; public List Questions { get; set; } = []; public PlacementTestResultResponse? CompletedResult { get; set; } + /// "CourseFinal" for an end-of-course assessment; null for the learner's own Placement. + public string? Purpose { get; set; } + /// Class (StudyCohort) the end-of-course attempt belongs to. + public int? CohortId { get; set; } + /// Learner enrollment (StudyCourse) the end-of-course attempt belongs to. + public int? EnrollmentId { get; set; } + /// In-class quiz (Purpose "ClassQuiz") and the learner assignment this attempt belongs to. + public int? QuizId { get; set; } + public int? QuizAssignmentId { get; set; } } internal sealed class PlacementSnapshotLevelCatalogItem @@ -2648,6 +2788,10 @@ internal sealed class PlacementSnapshotQuestionItem public string? PassageInstructions { get; set; } public string? PassageImageUrl { get; set; } public int? CorrectOptionId { get; set; } + /// Answer explanation (class quiz review only; never sent while the attempt is running). + public string? Explanation { get; set; } + /// Optional topic/difficulty labels copied from the bank (class quiz only). + public string? Topic { get; set; } public string[]? OrderingTokens { get; set; } public string[]? OrderingAnswerKey { get; set; } public string[]? OrderingResponse { get; set; } diff --git a/RikiPath.Application/Services/RetakeEligibilityEvaluator.cs b/RikiPath.Application/Services/RetakeEligibilityEvaluator.cs new file mode 100644 index 0000000..6e79278 --- /dev/null +++ b/RikiPath.Application/Services/RetakeEligibilityEvaluator.cs @@ -0,0 +1,85 @@ +using Microsoft.EntityFrameworkCore; +using System.Text.Json; +using RikiPath.Application.IServices; +using RikiPath.Application.Requests.StudyCourses; +using RikiPath.Domain; +using RikiPath.Domain.Entities; + +namespace RikiPath.Application.Services; + +/// +/// One place that resolves the class policy pinned to an enrollment and evaluates JLPT retake-support eligibility, +/// so Learner, Mentor and Admin screens and the request/review endpoints never compute it differently. +/// +internal static class RetakeEligibilityEvaluator +{ + /// + /// Policy that applies to the enrollment: the version pinned on the enrollment, else the version pinned on its class, + /// else (legacy rows only) the version effective when the course started. Never "the latest" policy. + /// + public static async Task ResolvePolicyAsync( + IUnitOfWork uow, IMentorGroupPolicyService? policies, StudyCourse course, CancellationToken ct) + { + if (course.GroupPolicy is not null) return course.GroupPolicy; + if (course.CohortId is int cohortId) + { + var pinned = await uow.StudyCohorts.Query().AsNoTracking() + .Where(x => x.Id == cohortId && x.GroupPolicyId != null) + .Select(x => x.GroupPolicy) + .FirstOrDefaultAsync(ct); + if (pinned is not null) return pinned; + } + return policies is null + ? null + : await policies.GetEffectiveAsync(course.StartsAt ?? course.Cohort?.StartsAt ?? DateTime.UtcNow, ct); + } + + public static async Task EvaluateAsync( + IUnitOfWork uow, IMentorGroupPolicyService? policies, StudyCourse course, CancellationToken ct, + IReadOnlyCollection? assignments = null) + { + var policy = await ResolvePolicyAsync(uow, policies, course, ct); + assignments ??= course.CohortId.HasValue + ? await uow.HomeworkAssignments.Query().AsNoTracking() + .Include(h => h.Submission) + .Where(h => !h.IsDeleted && h.StudyCourseId == course.Id) + .ToListAsync(ct) + : []; + var retaken = await uow.StudyCourses.Query().AsNoTracking().AnyAsync(x => x.RetakeOfId == course.Id, ct); + return CourseRetakePolicy.Evaluate(course, retaken, policy, assignments); + } +} + +/// Stores the Mentor retake plan in the existing MentorSupportPlan column (JSON v1 or legacy text). +internal static class RetakeSupportPlanFormat +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + public static string? Normalize(SaveRetakeSupportPlan r) + { + static string? Clean(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + var goal = Clean(r.Goal); + var content = Clean(r.Content); + var structured = goal is not null || content is not null || r.FocusSkills is { Count: > 0 } + || Clean(r.Materials) is not null || Clean(r.Timeline) is not null || Clean(r.Guidance) is not null; + if (!structured) + return Clean(r.SupportPlan); + if (goal is null || content is null) + return null; + var skills = (r.FocusSkills ?? []) + .Select(s => s?.Trim().ToLowerInvariant()) + .Where(s => s is "vocabulary" or "grammar" or "reading" or "listening") + .Distinct() + .ToList(); + return JsonSerializer.Serialize(new + { + v = 1, + goal, + focusSkills = skills, + content, + materials = Clean(r.Materials), + timeline = Clean(r.Timeline), + guidance = Clean(r.Guidance), + }, Json); + } +} diff --git a/RikiPath.Application/Services/SidebarCounterService.cs b/RikiPath.Application/Services/SidebarCounterService.cs index 0c2a829..492c0c5 100644 --- a/RikiPath.Application/Services/SidebarCounterService.cs +++ b/RikiPath.Application/Services/SidebarCounterService.cs @@ -391,17 +391,6 @@ private async Task PopulateAdminCountersAsync( }, }); - var pendingTransfers = await unitOfWork.CohortTransferRequests.Query() - .AsNoTracking() - .CountAsync(x => x.Status == CohortTransferRequest.Pending, ct); - - response.Counters.Add(new SidebarCounterItemDto - { - Key = "admin.cohort_transfers", - Count = Math.Max(0, pendingTransfers), - Kind = SidebarCounterKind.ActionRequired, - }); - var decidableComplaints = await unitOfWork.CohortComplaints.Query() .AsNoTracking() .CountAsync(x => x.Status == CohortComplaint.Open || x.Status == CohortComplaint.UnderReview, ct); diff --git a/RikiPath.Application/Services/StudyCohortFeedbackService.cs b/RikiPath.Application/Services/StudyCohortFeedbackService.cs index e684460..98e7de6 100644 --- a/RikiPath.Application/Services/StudyCohortFeedbackService.cs +++ b/RikiPath.Application/Services/StudyCohortFeedbackService.cs @@ -242,7 +242,7 @@ await uow.ExecuteInTransactionAsync(async token => CreatedAtUtc = now, UpdatedAtUtc = now }; - // Đánh giá không bao giờ tự tạo yêu cầu chuyển lớp, đặt lịch 1-1 hay giao dịch thanh toán/hoàn tiền. + // Đánh giá không tự điều chỉnh ghi danh, đặt lịch 1-1 hay tạo giao dịch thanh toán/hoàn tiền. await uow.CohortMentorReviews.AddAsync(review, token); await uow.SaveChangesAsync(token); @@ -257,6 +257,43 @@ await uow.ExecuteInTransactionAsync(async token => return result; }); + /// + /// Completed classes where the signed-in Learner may still rate their Mentor (same rule as + /// : completed + paid, at least one Present session, not yet reviewed). + /// Drives the optional "Đánh giá Giáo viên" CTA on "Lớp của tôi"; it never blocks other features. + /// + public Task> MentorReviewPromptsAsync(CancellationToken ct) => Run(async () => + { + if (Actor.Role != Role.Learner) throw new UnauthorizedAccessException(); + var reviews = uow.CohortMentorReviews.Query(); + var rows = await uow.StudyCourses.Query().AsNoTracking() + .Where(c => c.LearnerId == Actor.Id && c.CohortId != null && c.Status == "Completed" + && (c.PaymentStatus == "Paid" || c.PaymentStatus == "PartiallyRefunded") + && c.Cohort!.Status == "Completed" + && c.Sessions.Any(s => s.Status == "Present") + && !reviews.Any(r => r.CourseId == c.Id)) + .Select(c => new + { + CourseId = c.Id, + c.CohortId, + CohortName = c.Cohort!.Name, + MentorId = c.Cohort.MentorId, + MentorFirstName = c.Cohort.Mentor.FirstName, + MentorLastName = c.Cohort.Mentor.LastName, + MentorAvatarUrl = c.Cohort.Mentor.AvatarUrl, + }) + .ToListAsync(ct); + return rows.Select(r => new + { + r.CourseId, + r.CohortId, + r.CohortName, + r.MentorId, + MentorName = $"{r.MentorFirstName} {r.MentorLastName}".Trim(), + r.MentorAvatarUrl, + }).ToList(); + }); + public Task> UpdateCohortMentorReviewAsync( int courseId, int reviewId, UpdateCohortMentorReviewRequest request, CancellationToken ct) => Run(async () => { @@ -853,11 +890,7 @@ void RememberMentor(UserAccount? u) .OrderByDescending(f => f.PublishedAtUtc) .ToList(); - var retaken = await uow.StudyCourses.Query().AsNoTracking().AnyAsync(x => x.RetakeOfId == courseId, ct); - var effectivePolicy = course.GroupPolicy ?? (groupPolicies is null - ? null - : await groupPolicies.GetEffectiveAsync(course.StartsAt ?? course.Cohort?.StartsAt ?? now, ct)); - var eligibility = CourseRetakePolicy.Evaluate(course, retaken, effectivePolicy, assignments); + var eligibility = await RetakeEligibilityEvaluator.EvaluateAsync(uow, groupPolicies, course, ct, assignments); MentorLearnerSkillProfileResponse? skillProgress = null; var skillProgressAvailable = false; @@ -929,8 +962,11 @@ void RememberMentor(UserAccount? u) Eligibility = eligibility, CompletionPolicy = new { - HomeworkThresholdPercent = effectivePolicy?.RemediationCompletionThresholdPercent ?? course.MinimumHomeworkPercent, - HomeworkThresholdComparison = effectivePolicy?.RemediationThresholdComparison ?? ">=" + HomeworkThresholdPercent = eligibility.HomeworkThresholdPercent, + AttendanceThresholdPercent = eligibility.AttendanceThresholdPercent, + HomeworkThresholdComparison = eligibility.ThresholdComparison, + RetakeSupportEnabled = eligibility.SupportEnabled, + PolicyVersion = eligibility.PolicyVersion }, SkillProgressAvailable = skillProgressAvailable, SkillProgress = skillProgress, diff --git a/RikiPath.Application/Services/StudyCohortLifecycleService.cs b/RikiPath.Application/Services/StudyCohortLifecycleService.cs index c577a89..f491d88 100644 --- a/RikiPath.Application/Services/StudyCohortLifecycleService.cs +++ b/RikiPath.Application/Services/StudyCohortLifecycleService.cs @@ -26,11 +26,11 @@ public sealed partial class StudyCourseService private sealed record ShiftedCohortSession(StudyCohortSession Session, DateTime ProposedStart, DateTime ProposedEnd); private sealed record CohortPaymentBlocker(int CourseId, string Kind, string PaymentStatus, string Status, DateTime? PaymentExpiresAt); - private sealed record CohortScheduleEvaluation(StudyCohort? Cohort, string Kind, int? Weeks, List Checks, + private sealed record CohortScheduleEvaluation(StudyCohort? Cohort, string Kind, int? Weeks, List Checks, List Blockers, List Shifted, TeachingConflictReport? Report, DateTime? NewCutoffUtc) { public bool Eligible => Checks.All(c => c.Passed); - public TransferCheck? FirstFailure => Checks.FirstOrDefault(c => !c.Passed); + public CohortOperationCheck? FirstFailure => Checks.FirstOrDefault(c => !c.Passed); } private IQueryable ScheduleRequestDetails => uow.CohortScheduleRequests.Query() @@ -57,19 +57,22 @@ private void AddScheduleRequestEvent(CohortScheduleRequest request, string actio return null; } + private static DateTime? FirstSessionStartUtc(StudyCohort cohort) + => cohort.Sessions.Count == 0 ? null : cohort.Sessions.Min(s => s.Availability.StartTime); + // Toàn bộ điều kiện dời/hủy lớp; gọi khi xem trước, khi tạo yêu cầu và gọi lại trong giao dịch khi duyệt. private async Task EvaluateCohortScheduleAsync(int cohortId, string kind, int? weeks, CancellationToken ct) { var now = DateTime.UtcNow; - var checks = new List(); + var checks = new List(); void Check(string code, bool passed, string message, HttpStatusCode status = HttpStatusCode.Conflict) - => checks.Add(new TransferCheck(code, passed, message, (int)status)); + => checks.Add(new CohortOperationCheck(code, passed, message, (int)status)); var isShift = kind == CohortScheduleRequest.KindShiftWeeks; if (isShift) Check("COHORT_SHIFT_WEEKS_INVALID", weeks is >= 1 and <= MaxCohortShiftWeeks, $"Số tuần dời phải từ 1 đến {MaxCohortShiftWeeks}.", HttpStatusCode.UnprocessableEntity); - var cohort = await CohortForTransfer.SingleOrDefaultAsync(x => x.Id == cohortId, ct); + var cohort = await CohortWithSchedulingDetails.SingleOrDefaultAsync(x => x.Id == cohortId, ct); Check("COHORT_NOT_FOUND", cohort is not null, "Không tìm thấy lớp.", HttpStatusCode.NotFound); if (cohort is null) return new(null, kind, weeks, checks, [], [], null, null); @@ -117,7 +120,7 @@ void Check(string code, bool passed, string message, HttpStatusCode status = Htt IncludeOwnIntervals = false }, ct); var first = report.First; - checks.Add(new TransferCheck(first?.Code ?? MentorTeachingConflictService.ScheduleConflict, report.IsValid, + checks.Add(new CohortOperationCheck(first?.Code ?? MentorTeachingConflictService.ScheduleConflict, report.IsValid, report.IsValid ? "Giáo viên không bị trùng lịch dạy trong các tuần mới." : $"Buổi {first!.SessionNumber} sau khi dời bị trùng lịch: {first.Message}", (int)HttpStatusCode.Conflict)); var firstShift = shifted.MinBy(x => x.ProposedStart)!; @@ -528,7 +531,7 @@ public Task> MentorCancelRecruitingCohortAsync(int cohortId, await uow.ExecuteInTransactionAsync(async token => { await uow.StudyCourses.LockCohortAsync(cohortId, token); - var cohort = await CohortForTransfer.SingleOrDefaultAsync(x => x.Id == cohortId, token); + var cohort = await CohortWithSchedulingDetails.SingleOrDefaultAsync(x => x.Id == cohortId, token); Rule(cohort is not null, "COHORT_NOT_FOUND", "Không tìm thấy lớp.", HttpStatusCode.NotFound); if (cohort!.MentorId != Actor.Id) throw new UnauthorizedAccessException(); diff --git a/RikiPath.Application/Services/StudyCohortMentorAssignmentHistoryService.cs b/RikiPath.Application/Services/StudyCohortMentorAssignmentHistoryService.cs new file mode 100644 index 0000000..46ca0d0 --- /dev/null +++ b/RikiPath.Application/Services/StudyCohortMentorAssignmentHistoryService.cs @@ -0,0 +1,33 @@ +using System.Net; +using Microsoft.EntityFrameworkCore; +using RikiPath.Application.Responses; +using RikiPath.Domain.Enums; + +namespace RikiPath.Application.Services; + +public sealed partial class StudyCourseService +{ + public Task> MentorAssignmentsAsync(int cohortId, CancellationToken ct) => Run(async () => + { + var cohort = await uow.StudyCohorts.Query().AsNoTracking().SingleOrDefaultAsync(x => x.Id == cohortId, ct); + Rule(cohort is not null, "REPLACEMENT_COHORT_NOT_FOUND", "Không tìm thấy lớp.", HttpStatusCode.NotFound); + var rows = await uow.StudyCohortMentorAssignments.Query().AsNoTracking() + .Where(x => x.CohortId == cohortId).OrderBy(x => x.Id).ToListAsync(ct); + if (Actor.Role != Role.Admin && !(Actor.Role == Role.Mentor + && (cohort!.MentorId == Actor.Id || rows.Any(x => x.MentorId == Actor.Id || x.PreviousMentorId == Actor.Id)))) + throw new UnauthorizedAccessException(); + return rows.Select(history => new + { + history.Id, + history.PreviousMentorId, + history.MentorId, + history.EffectiveFromSessionNumber, + history.EffectiveFromUtc, + history.AffectedSessionCount, + Reason = Actor.Role == Role.Admin ? history.Reason : null, + history.AssignedById, + history.PolicyVersionSnapshot, + history.CreatedAtUtc, + }).ToList(); + }); +} diff --git a/RikiPath.Application/Services/StudyCohortMentorReplacementService.cs b/RikiPath.Application/Services/StudyCohortMentorReplacementService.cs deleted file mode 100644 index 071eea7..0000000 --- a/RikiPath.Application/Services/StudyCohortMentorReplacementService.cs +++ /dev/null @@ -1,251 +0,0 @@ -using System.Net; -using System.Text.Json; -using Microsoft.EntityFrameworkCore; -using RikiPath.Application.Common; -using RikiPath.Application.IServices; -using RikiPath.Application.Requests.StudyCourses; -using RikiPath.Application.Responses; -using RikiPath.Domain.Entities; -using RikiPath.Domain.Enums; - -namespace RikiPath.Application.Services; - -// Admin thay Mentor chính cho phần còn lại của lớp (khác với Mentor dạy thay một buổi riêng lẻ). -// Buổi đã diễn ra/đang diễn ra giữ nguyên khung giờ và Mentor thực dạy; chỉ các buổi tương lai được chuyển. -public sealed partial class StudyCourseService -{ - private sealed record ReplacementEvaluation(StudyCohort? Cohort, UserAccount? Mentor, MentorGroupPolicy Policy, int FromSessionNumber, - List Retained, List Affected, List Checks, List Conflicts) - { - public bool Eligible => Checks.All(c => c.Passed); - public TransferCheck? FirstFailure => Checks.FirstOrDefault(c => !c.Passed); - } - - private async Task EvaluateReplacementAsync(int cohortId, int mentorId, int? fromSessionNumber, CancellationToken ct) - { - var now = DateTime.UtcNow; - var policy = await CurrentPolicyAsync(ct); - var checks = new List(); - var conflicts = new List(); - void Check(string code, bool passed, string message, HttpStatusCode status = HttpStatusCode.UnprocessableEntity) - => checks.Add(new TransferCheck(code, passed, message, (int)status)); - - Check("REPLACEMENT_DISABLED_BY_POLICY", policy.MentorReplacementEnabled, "Chính sách hiện hành chưa cho phép thay Giáo viên phụ trách."); - var cohort = await CohortForTransfer.SingleOrDefaultAsync(x => x.Id == cohortId, ct); - Check("REPLACEMENT_COHORT_NOT_FOUND", cohort is not null, "Không tìm thấy lớp.", HttpStatusCode.NotFound); - if (cohort is null) return new ReplacementEvaluation(null, null, policy, 0, [], [], checks, conflicts); - Check("REPLACEMENT_COHORT_NOT_ACTIVE", cohort.Status is "Published" or "Draft", "Lớp đã đóng; không thể thay Giáo viên.", HttpStatusCode.Conflict); - Check("REPLACEMENT_SAME_MENTOR", cohort.MentorId != mentorId, "Giáo viên thay thế phải khác Giáo viên hiện tại."); - - var mentor = await uow.UserAccounts.Query().Include(x => x.MentorProfile).SingleOrDefaultAsync(x => x.Id == mentorId, ct); - Check("REPLACEMENT_MENTOR_NOT_ELIGIBLE", mentor is { Role: Role.Mentor, IsDeleted: false } - && mentor.MentorProfile?.VerificationStatus == MentorVerificationStatus.Approved, - "Giáo viên thay thế chưa được phê duyệt hồ sơ hoặc không còn hoạt động."); - var qualCodes = uow.MentorTeachingQualifications is null - ? new List() - : await uow.MentorTeachingQualifications.Query().AsNoTracking() - .Include(q => q.CertificateLevel) - .Where(q => q.MentorUserId == mentorId && q.IsActive && q.RevokedAtUtc == null) - .Select(q => q.CertificateLevel.Code) - .ToListAsync(ct); - var highestRank = qualCodes - .Append(mentor?.MentorProfile?.JlptLevel) - .Select(RikiPath.Domain.MentorScheduling.MentorSlotPolicy.GetJlptRank) - .DefaultIfEmpty(0) - .Max(); - var targetLevelCode = cohort.Plan.CertificateLevel?.Code; - var hasDirectQualification = uow.MentorTeachingQualifications is not null && await uow.MentorTeachingQualifications.Query() - .AnyAsync(q => q.MentorUserId == mentorId && q.CertificateLevelId == cohort.Plan.CertificateLevelId && q.IsActive && q.RevokedAtUtc == null, ct); - var qualified = hasDirectQualification || RikiPath.Domain.MentorScheduling.MentorSlotPolicy.CanMentorTeachLevel(highestRank, targetLevelCode); - Check("REPLACEMENT_LEVEL_NOT_QUALIFIED", qualified, $"Giáo viên thay thế chưa được cấp quyền giảng dạy cấp độ {targetLevelCode}."); - - var earliest = now.AddHours(policy.MentorReplacementLeadHours); - var ordered = cohort.Sessions.OrderBy(s => s.Number).ToList(); - var from = fromSessionNumber ?? ordered.FirstOrDefault(s => s.Availability.StartTime >= earliest)?.Number ?? 0; - var affected = ordered.Where(s => from > 0 && s.Number >= from).ToList(); - var retained = ordered.Where(s => from <= 0 || s.Number < from).ToList(); - Check("REPLACEMENT_NO_FUTURE_SESSIONS", affected.Count > 0, "Lớp không còn buổi học sắp tới đáp ứng đủ thời gian báo trước để chuyển cho Giáo viên mới.", HttpStatusCode.Conflict); - Check("REPLACEMENT_LEAD_TIME", affected.All(s => s.Availability.StartTime >= earliest), - $"Buổi học đầu tiên chuyển cho Giáo viên mới phải bắt đầu sau ít nhất {policy.MentorReplacementLeadHours} giờ; các buổi đã hoặc sắp diễn ra vẫn do Giáo viên hiện tại phụ trách."); - Check("REPLACEMENT_SESSION_LOCKED", affected.All(s => s.Availability.IsApproved && !s.Availability.IsDeleted - && s.Availability.RejectedAt == null && s.Availability.ChangeRequestedAt == null && s.Availability.MentorId == cohort.MentorId), - "Có buổi học đang chờ điều chỉnh lịch hoặc không còn thuộc Giáo viên hiện tại.", HttpStatusCode.Conflict); - var affectedIds = affected.Select(s => s.AvailabilityId).ToList(); - Check("REPLACEMENT_PENDING_CHANGE_REQUEST", !await uow.CourseScheduleRequests.Query().AnyAsync(x => x.Status == "Pending" - && x.Course.CohortId == cohortId && x.Course.Sessions.Any(s => s.Id == x.SessionId && s.AvailabilityId.HasValue && affectedIds.Contains(s.AvailabilityId.Value)), ct), - "Có yêu cầu dời/hủy buổi học đang chờ xử lý trong phạm vi thay Giáo viên.", HttpStatusCode.Conflict); - - if (mentor is not null && affected.Count > 0) - { - // Kiểm tra chuẩn cho Mentor thay thế: chỉ cam kết dạy thật (lớp đã công bố, lịch 1-1 đã xác nhận, buổi khóa 1-1) - // là xung đột; khung giờ rảnh chưa có người đặt không còn bị tính. - var report = await TeachingConflicts.CheckAsync(mentorId, - affected.Select(s => new ProposedTeachingInterval(s.Availability.StartTime, s.Availability.EndTime, s.Number)).ToList(), - new TeachingConflictOptions - { - ExcludeCohortId = cohort.Id, - RestMinutes = policy.Version == 0 ? null : policy.RestMinutes, - // Các buổi của chính lớp đã được xếp hợp lệ; chỉ xét va chạm với lịch hiện có của Giáo viên mới. - IncludeOwnIntervals = false - }, ct); - foreach (var x in report.Conflicts) - conflicts.Add(new - { - x.SessionNumber, Kind = x.CommitmentKind, x.Code, x.CohortId, x.CohortName, - StartTime = x.CommitmentStartUtc ?? x.ProposedStartUtc, EndTime = x.CommitmentEndUtc ?? x.ProposedEndUtc, x.Message - }); - Check("REPLACEMENT_MENTOR_SCHEDULE_CONFLICT", report.IsValid, - report.IsValid ? "Giáo viên thay thế không bị trùng lịch dạy." - : $"Giáo viên thay thế bị trùng lịch hoặc không đủ thời gian nghỉ ở buổi {report.Conflicts[0].SessionNumber}: {report.Conflicts[0].Message}", - HttpStatusCode.Conflict); - } - return new ReplacementEvaluation(cohort, mentor, policy, from, retained, affected, checks, conflicts); - } - - private static object ReplacementSession(StudyCohortSession s) => new - { - s.Number, s.AvailabilityId, s.Availability.StartTime, s.Availability.EndTime, ActualMentorId = s.Availability.MentorId - }; - - public Task> PreviewMentorReplacementAsync(int cohortId, int mentorId, int? fromSessionNumber, CancellationToken ct) => Run(async () => - { - Admin(); - var e = await EvaluateReplacementAsync(cohortId, mentorId, fromSessionNumber, ct); - Rule(e.Cohort is not null, "REPLACEMENT_COHORT_NOT_FOUND", "Không tìm thấy lớp.", HttpStatusCode.NotFound); - var now = DateTime.UtcNow; - var history = await uow.StudyCohortMentorAssignments.Query().AsNoTracking().Where(x => x.CohortId == cohortId) - .OrderByDescending(x => x.Id).ToListAsync(ct); - var activeLearners = e.Cohort!.Enrollments.Count(x => x.Status == "Active" && x.PaymentStatus is "Paid" or "PartiallyRefunded"); - return new - { - CohortId = e.Cohort.Id, e.Cohort.Name, e.Cohort.Revision, e.Cohort.Capacity, - CurrentMentorId = e.Cohort.MentorId, CurrentMentorName = $"{e.Cohort.Mentor?.FirstName} {e.Cohort.Mentor?.LastName}".Trim(), - ReplacementMentorId = mentorId, ReplacementMentorName = e.Mentor is null ? null : $"{e.Mentor.FirstName} {e.Mentor.LastName}".Trim(), - Level = e.Cohort.Plan.CertificateLevel?.Code, PolicyVersion = e.Policy.Version, LeadHours = e.Policy.MentorReplacementLeadHours, - e.FromSessionNumber, e.Eligible, - Impact = new - { - RetainedSessionCount = e.Retained.Count, AffectedSessionCount = e.Affected.Count, - ActiveLearnerCount = activeLearners, EnrolledCount = e.Cohort.Enrollments.Count(x => ReservesSeat(x, now)), - CapacityUnchanged = true, EnrollmentsUnchanged = true - }, - RetainedSessions = e.Retained.Select(ReplacementSession), - AffectedSessions = e.Affected.Select(ReplacementSession), - e.Conflicts, - Checks = e.Checks.Select(c => new { c.Code, c.Passed, c.Message }), - History = history.Select(h => new { h.Id, h.PreviousMentorId, h.MentorId, h.EffectiveFromSessionNumber, h.EffectiveFromUtc, h.AffectedSessionCount, h.Reason, h.AssignedById, h.CreatedAtUtc }) - }; - }); - - public Task> MentorAssignmentsAsync(int cohortId, CancellationToken ct) => Run(async () => - { - var cohort = await uow.StudyCohorts.Query().AsNoTracking().SingleOrDefaultAsync(x => x.Id == cohortId, ct); - Rule(cohort is not null, "REPLACEMENT_COHORT_NOT_FOUND", "Không tìm thấy lớp.", HttpStatusCode.NotFound); - var rows = await uow.StudyCohortMentorAssignments.Query().AsNoTracking().Where(x => x.CohortId == cohortId).OrderBy(x => x.Id).ToListAsync(ct); - if (Actor.Role != Role.Admin && !(Actor.Role == Role.Mentor - && (cohort!.MentorId == Actor.Id || rows.Any(x => x.MentorId == Actor.Id || x.PreviousMentorId == Actor.Id)))) - throw new UnauthorizedAccessException(); - return rows.Select(h => new - { - h.Id, h.PreviousMentorId, h.MentorId, h.EffectiveFromSessionNumber, h.EffectiveFromUtc, h.AffectedSessionCount, - Reason = Actor.Role == Role.Admin ? h.Reason : null, h.AssignedById, h.PolicyVersionSnapshot, h.CreatedAtUtc - }).ToList(); - }); - - public Task> ReplaceCohortMentorAsync(int cohortId, ReplaceCohortMentorRequest r, CancellationToken ct) => Run(async () => - { - Admin(); - Rule(r.IdempotencyKey != Guid.Empty, "REPLACEMENT_IDEMPOTENCY_KEY_REQUIRED", "Thiếu mã chống gửi trùng."); - var reason = r.Reason?.Trim() ?? ""; - Rule(reason.Length is >= 10 and <= 1000, "REPLACEMENT_REASON_REQUIRED", "Vui lòng nhập lý do thay Giáo viên từ 10 đến 1000 ký tự."); - object result = new { }; - await uow.ExecuteInTransactionAsync(async token => - { - var existing = await uow.StudyCohortMentorAssignments.Query().AsNoTracking().SingleOrDefaultAsync(x => x.IdempotencyKey == r.IdempotencyKey, token); - if (existing is not null) - { - Rule(existing.CohortId == cohortId && existing.MentorId == r.MentorId, "REPLACEMENT_IDEMPOTENCY_KEY_REUSED", - "Mã chống gửi trùng đã dùng cho thao tác khác.", HttpStatusCode.Conflict); - result = new { AssignmentId = existing.Id, existing.CohortId, existing.MentorId, existing.EffectiveFromSessionNumber, existing.AffectedSessionCount, Idempotent = true }; - return; - } - await uow.StudyCourses.LockCohortAsync(cohortId, token); - var currentMentorId = await uow.StudyCohorts.Query().AsNoTracking().Where(x => x.Id == cohortId).Select(x => (int?)x.MentorId).SingleOrDefaultAsync(token); - Rule(currentMentorId.HasValue, "REPLACEMENT_COHORT_NOT_FOUND", "Không tìm thấy lớp.", HttpStatusCode.NotFound); - // Cùng khóa lịch với luồng tạo lớp/đặt lịch để không ai chen vào lịch của hai Mentor trong lúc chuyển. - await uow.StudyCourses.LockScheduleAsync(r.MentorId, currentMentorId!.Value, token); - var e = await EvaluateReplacementAsync(cohortId, r.MentorId, r.FromSessionNumber, token); - var failure = e.FirstFailure; - if (failure is not null) throw new CourseRuleException(failure.Message, (HttpStatusCode)failure.Status, failure.Code); - var cohort = e.Cohort!; - Rule(cohort.Revision == r.ExpectedCohortRevision, "REPLACEMENT_COHORT_STALE", "Lớp vừa thay đổi; hãy xem lại tác động trước khi xác nhận.", HttpStatusCode.Conflict); - var now = DateTime.UtcNow; - var previousMentorId = cohort.MentorId; - var capacityBefore = cohort.Capacity; - var enrollmentIds = cohort.Enrollments.Select(x => x.Id).OrderBy(x => x).ToList(); - var assignment = new StudyCohortMentorAssignment - { - CohortId = cohort.Id, PreviousMentorId = previousMentorId, MentorId = r.MentorId, - EffectiveFromSessionNumber = e.FromSessionNumber, EffectiveFromUtc = e.Affected.Min(s => s.Availability.StartTime), - AffectedSessionCount = e.Affected.Count, Reason = reason, AssignedById = Actor.Id, IdempotencyKey = r.IdempotencyKey, - PolicyId = e.Policy.Id == 0 ? null : e.Policy.Id, PolicyVersionSnapshot = e.Policy.Version == 0 ? null : e.Policy.Version, - CreatedAtUtc = now, - ImpactSnapshot = JsonSerializer.Serialize(new - { - Retained = e.Retained.Select(s => new { s.Number, s.AvailabilityId, s.Availability.MentorId }), - Affected = e.Affected.Select(s => new { s.Number, FromAvailabilityId = s.AvailabilityId }) - }) - }; - await uow.StudyCohortMentorAssignments.AddAsync(assignment, token); - - var enrollments = await uow.StudyCourses.Query().Include(x => x.Sessions).Include(x => x.Audit) - .Where(x => x.CohortId == cohort.Id).ToListAsync(token); - foreach (var session in e.Affected) - { - var old = session.Availability; - // Khung giờ mới thuộc Mentor thay thế, giữ nguyên giờ/sức chứa/snapshot chính sách; phòng họp mới. - var replacement = new MentorAvailability - { - MentorId = r.MentorId, StartTime = old.StartTime, EndTime = old.EndTime, RoomId = Guid.NewGuid(), - AttendanceTrackingEnabled = old.AttendanceTrackingEnabled, MaxLearners = old.MaxLearners, BookedCount = 0, - IsApproved = true, AdminName = "Quản trị viên (thay Giáo viên phụ trách)", PublishedAt = now, - GroupPolicyId = old.GroupPolicyId, PolicyVersion = old.PolicyVersion, - SessionMinutesSnapshot = old.SessionMinutesSnapshot, RestMinutesSnapshot = old.RestMinutesSnapshot, - LocalBusinessDate = old.LocalBusinessDate, MentorScheduleRuleId = old.MentorScheduleRuleId, - GenerationKey = old.GenerationKey is null ? null : $"mentor-replacement:{old.Id}:{r.MentorId}", - ChangeResolution = $"Nhận buổi {session.Number} của lớp {cohort.Name}.", - CreatedDate = now - }; - old.IsDeleted = true; old.ModifiedDate = now; - old.ChangeResolution = $"Chuyển cho Giáo viên mới (thay Giáo viên phụ trách lớp {cohort.Name})."; - session.Availability = replacement; - foreach (var learnerSession in enrollments.Where(x => x.Status == "Active" && x.PaymentStatus is "Paid" or "PartiallyRefunded") - .SelectMany(x => x.Sessions).Where(x => x.AvailabilityId == old.Id && x.Status == "Scheduled")) - { - learnerSession.Availability = replacement; - learnerSession.MeetingUrl = $"/meeting-room/{replacement.RoomId}"; - } - } - foreach (var enrollment in enrollments.Where(x => x.Status is "Active" or "PendingPayment" or "Ready")) - { - // Mentor phụ trách hiện tại của ghi danh đang học; buổi đã dạy vẫn gắn khung giờ của Mentor cũ. - enrollment.MentorId = r.MentorId; - Audit(enrollment, "CohortMentorReplaced", $"Thay Giáo viên phụ trách từ buổi {e.FromSessionNumber}. {reason}"); - } - cohort.MentorId = r.MentorId; - cohort.Revision++; - await uow.SaveChangesAsync(token); - Rule(cohort.Capacity == capacityBefore && cohort.Enrollments.Select(x => x.Id).OrderBy(x => x).SequenceEqual(enrollmentIds), - "REPLACEMENT_INVARIANT", "Sĩ số hoặc ghi danh bị thay đổi ngoài dự kiến.", HttpStatusCode.Conflict); - var learnerIds = enrollments.Where(x => x.Status == "Active" && x.PaymentStatus is "Paid" or "PartiallyRefunded").Select(x => x.LearnerId).ToList(); - QueueNotifications($"cohort-mentor-replacement:{assignment.Id}", "StudyCohort", cohort.Id.ToString(), - learnerIds.Select(id => (id, "Lớp học có Giáo viên mới", $"Từ buổi {e.FromSessionNumber}, {NotificationDisplayNormalizer.ClassSubject(cohort.Name, lowercasePrefix: true)} sẽ do Giáo viên mới phụ trách.", "CohortMentorReplaced", (string?)"/my-courses")) - .Append((r.MentorId, "Bạn được phân công lớp mới", $"Bạn phụ trách {NotificationDisplayNormalizer.ClassSubject(cohort.Name, lowercasePrefix: true)} từ buổi {e.FromSessionNumber}.", "CohortMentorReplaced", (string?)$"/mentor/cohorts/{cohort.Id}")) - .Append((previousMentorId, "Thay đổi phân công lớp", $"{NotificationDisplayNormalizer.ClassSubject(cohort.Name)} đã được chuyển cho Giáo viên khác phụ trách từ buổi {e.FromSessionNumber}.", "CohortMentorReplaced", (string?)"/mentor/cohorts"))); - await uow.SaveChangesAsync(token); - result = new { AssignmentId = assignment.Id, CohortId = cohort.Id, assignment.MentorId, assignment.PreviousMentorId, - assignment.EffectiveFromSessionNumber, assignment.AffectedSessionCount, CohortRevision = cohort.Revision, Idempotent = false }; - }, ct); - return result; - }); -} diff --git a/RikiPath.Application/Services/StudyCohortService.cs b/RikiPath.Application/Services/StudyCohortService.cs index c08b8ed..b2ef95c 100644 --- a/RikiPath.Application/Services/StudyCohortService.cs +++ b/RikiPath.Application/Services/StudyCohortService.cs @@ -411,7 +411,9 @@ public Task> CohortsAsync(CohortDiscoveryFilter? filter, Can CanEnd = isSlotMentor && isWorkspaceOpen && s.Status == "InProgress", CanMarkAttendance = isSlotMentor && isWorkspaceOpen && s.Status == "InProgress", + // A completed class locks its learning records: no supplementary attendance afterwards. CanSupplementAttendance = isSlotMentor && isWorkspaceOpen + && !string.Equals(statusNormalized, "Completed", StringComparison.OrdinalIgnoreCase) && s.Status == "Completed" && pendingAttendanceCount > 0, PendingAttendanceCount = pendingAttendanceCount, s.Number, @@ -527,7 +529,7 @@ public Task> SaveCohortAsync(int? id, SaveStudyCohort r, Can else { Rule(false, "COHORT_SCHEDULE_LOCKED_BY_PROPOSAL", - "Không thể chỉnh sửa trực tiếp gói học, giáo viên, sĩ số, lịch đã duyệt hoặc trạng thái mở lớp. Vui lòng sử dụng quy trình dời lịch, đổi giáo viên hoặc hủy lớp chuyên biệt.", + "Không thể chỉnh sửa trực tiếp gói học, giáo viên, sĩ số, lịch đã duyệt hoặc trạng thái mở lớp. Vui lòng gửi yêu cầu hỗ trợ nếu cần điều chỉnh lớp.", HttpStatusCode.Conflict); } diff --git a/RikiPath.Application/Services/StudyCohortTransferService.cs b/RikiPath.Application/Services/StudyCohortTransferService.cs deleted file mode 100644 index 7f1801b..0000000 --- a/RikiPath.Application/Services/StudyCohortTransferService.cs +++ /dev/null @@ -1,499 +0,0 @@ -using System.Net; -using System.Text.Json; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using RikiPath.Application.Common; -using RikiPath.Application.IClients; -using RikiPath.Application.IServices; -using RikiPath.Application.Requests.StudyCourses; -using RikiPath.Application.Responses; -using RikiPath.Domain.Entities; -using RikiPath.Domain.Enums; - -namespace RikiPath.Application.Services; - -// Chuyển lớp có kiểm soát: Học viên gửi yêu cầu -> Admin xem xét -> Duyệt/Từ chối -> cập nhật ghi danh -> thông báo. -// Học viên không bao giờ tự đổi lớp/Mentor; điểm đánh giá Mentor thấp không tự tạo yêu cầu. -public sealed partial class StudyCourseService -{ - public const string CohortNotificationEvent = "CohortLearningNotification"; - - internal sealed record TransferCheck(string Code, bool Passed, string Message, int Status); - - private sealed record TransferEvaluation(StudyCohort? Target, MentorGroupPolicy Policy, List Checks) - { - public bool Eligible => Checks.All(c => c.Passed); - public TransferCheck? FirstFailure => Checks.FirstOrDefault(c => !c.Passed); - } - - private static readonly HashSet AllowedEvidenceTypes = ["application/pdf", "image/png", "image/jpeg"]; - - private void AddTransferEvent(CohortTransferRequest request, string action, string detail) - => request.History.Add(new CohortTransferRequestEvent - { - Action = action, ActorId = Actor.Id, ActorRole = Actor.Role.ToString(), - Detail = detail.Length > 2000 ? detail[..2000] : detail, AtUtc = DateTime.UtcNow - }); - - private void QueueNotifications(string eventKey, string aggregateType, string aggregateId, - IEnumerable<(int UserId, string Title, string Message, string Type, string? LinkUrl)> items) - { - var list = items.Where(x => x.UserId > 0).DistinctBy(x => x.UserId).ToList(); - if (list.Count == 0) return; - // Outbox ghi cùng giao dịch; dispatcher gửi SAU khi commit và tự thử lại khi gửi lỗi. - uow.AddMentorOutboxEvent(new MentorOutboxEvent - { - EventKey = eventKey, AggregateType = aggregateType, AggregateId = aggregateId, - EventType = CohortNotificationEvent, EventVersion = 1, - PayloadJson = JsonSerializer.Serialize(new - { - Notifications = list.Select(x => new { x.UserId, x.Title, x.Message, x.Type, x.LinkUrl }) - }), - CreatedAtUtc = DateTime.UtcNow, AvailableAtUtc = DateTime.UtcNow - }); - } - - private async Task CurrentPolicyAsync(CancellationToken ct) - { - if (groupPolicies is null) - return new MentorGroupPolicy { Version = 0 }; - var effective = await groupPolicies.GetEffectiveAsync(DateTime.UtcNow, ct); - Rule(effective is not null, "GROUP_POLICY_UNAVAILABLE", - "Hệ thống chưa có chính sách lớp học nhóm đang có hiệu lực. Vui lòng liên hệ Quản trị viên.", - HttpStatusCode.ServiceUnavailable); - return effective!; - } - - private static DateTime? FirstSessionStartUtc(StudyCohort cohort) - => cohort.Sessions.Count == 0 ? null : cohort.Sessions.Min(s => s.Availability.StartTime); - - private const string SourceStartedMessage = "Lớp hiện tại đã bắt đầu; không thể chuyển lớp sau khi khóa học đã bắt đầu."; - - private static bool SourceStarted(StudyCohort sourceCohort, DateTime now) - => (FirstSessionStartUtc(sourceCohort) ?? sourceCohort.StartsAt) <= now; - - private IQueryable CohortForTransfer =>uow.StudyCohorts.Query() - .Include(x => x.Plan).ThenInclude(x => x.CertificateLevel) - .Include(x => x.Mentor) - .Include(x => x.Sessions).ThenInclude(x => x.Availability).ThenInclude(x => x.GroupPolicy) - .Include(x => x.Enrollments).AsSplitQuery(); - - // Toàn bộ điều kiện chuyển lớp; được gọi khi xem trước và gọi lại trong giao dịch khi duyệt. - private async Task EvaluateTransferAsync(StudyCourse source, StudyCohort sourceCohort, - int? targetCohortId, CancellationToken ct) - { - var now = DateTime.UtcNow; - var policy = await CurrentPolicyAsync(ct); - var checks = new List(); - void Check(string code, bool passed, string message, HttpStatusCode status = HttpStatusCode.UnprocessableEntity) - => checks.Add(new TransferCheck(code, passed, message, (int)status)); - - Check("TRANSFER_DISABLED_BY_POLICY", policy.LearnerTransferEnabled, - "Chính sách hiện hành chưa cho phép chuyển lớp."); - Check("TRANSFER_SOURCE_NOT_ACTIVE", source.CohortId == sourceCohort.Id && source.Status == "Active" && source.PaymentStatus == "Paid", - "Ghi danh nguồn không còn hoạt động hoặc chưa thanh toán.", HttpStatusCode.Conflict); - Check("TRANSFER_RETAKE_UNSUPPORTED", source.RetakeOfId is null, - "Ghi danh học lại miễn phí chưa có chính sách chuyển lớp."); - // Quyết định chính thức của Product Owner: KHÔNG chuyển lớp sau khi khóa học đã bắt đầu, bất kể cờ chính sách - // (dữ liệu lịch sử) hay cấu hình phê duyệt. - Check("TRANSFER_SOURCE_STARTED", !SourceStarted(sourceCohort, now), SourceStartedMessage); - - StudyCohort? target = null; - if (!targetCohortId.HasValue) - { - Check("TRANSFER_TARGET_REQUIRED", false, "Chọn lớp đích để kiểm tra điều kiện chuyển."); - return new TransferEvaluation(null, policy, checks); - } - target = await CohortForTransfer.SingleOrDefaultAsync(x => x.Id == targetCohortId.Value, ct); - Check("TRANSFER_TARGET_NOT_FOUND", target is not null, "Không tìm thấy lớp đích.", HttpStatusCode.NotFound); - if (target is null) return new TransferEvaluation(null, policy, checks); - - Check("TRANSFER_TARGET_SAME_COHORT", target.Id != sourceCohort.Id, "Lớp đích phải khác lớp hiện tại."); - Check("TRANSFER_TARGET_NOT_PUBLISHED", target.Status == "Published", "Lớp đích chưa mở đăng ký."); - var targetStart = FirstSessionStartUtc(target) ?? target.StartsAt; - // Chuyển vào lớp đã khai giảng KHÔNG được hỗ trợ khi chưa có quyết định của Product Owner. - Check("TRANSFER_TARGET_STARTED", targetStart > now, - "Lớp đích đã bắt đầu; chưa hỗ trợ chuyển vào lớp đang học."); - Check("TRANSFER_TARGET_CUTOFF", EnrollmentCutoffUtc(target) > now, - "Lớp đích đã qua hạn khóa đăng ký theo chính sách."); - Check("TRANSFER_LEVEL_MISMATCH", target.Plan.CertificateLevelId == source.CertificateLevelId, - "Lớp đích khác cấp độ JLPT của khóa đã mua."); - Check("TRANSFER_CURRICULUM_MISMATCH", target.Plan.SessionType == "Group" - && target.Plan.TotalSessions == source.TotalSessions && target.Plan.SessionMinutes == source.SessionMinutes - && target.Sessions.Count == target.Plan.TotalSessions, - "Lớp đích khác chương trình (số buổi/thời lượng) của khóa đã mua."); - var sourcePlanPrice = await uow.StudyCoursePlans.Query().Where(p => p.Id == source.PlanId) - .Select(p => (decimal?)p.Price).SingleOrDefaultAsync(ct); - var effectiveSourceTuition = sourceCohort.TotalTuitionSnapshot is decimal srcSnap && srcSnap > 0 - ? srcSnap - : (source.Amount > 0 ? source.Amount : (sourcePlanPrice ?? 0m)); - var effectiveTargetTuition = target.TotalTuitionSnapshot is decimal dstSnap && dstSnap > 0 - ? dstSnap - : target.Plan.Price; - Check("TRANSFER_PAYMENT_POLICY_REQUIRED", target.PlanId == source.PlanId || effectiveTargetTuition == effectiveSourceTuition, - "Lớp đích có học phí khác; chưa có chính sách thu thêm/hoàn tiền nên không thể chuyển."); - Check("TRANSFER_TARGET_SCHEDULE_PENDING", target.Sessions.All(s => s.Availability.IsApproved && !s.Availability.IsDeleted - && s.Availability.RejectedAt == null && s.Availability.ChangeRequestedAt == null), - "Lịch lớp đích đang chờ xử lý điều chỉnh.", HttpStatusCode.Conflict); - var targetCapacity = target.CapacitySnapshot ?? target.Capacity; - var targetPolicy = target.Sessions.Select(s => s.Availability.GroupPolicy).FirstOrDefault(p => p is not null); - Check("TRANSFER_TARGET_POLICY_CAPACITY", targetPolicy is null || targetCapacity <= targetPolicy.MaxLearners, - "Sĩ số lớp đích vượt giới hạn chính sách.", HttpStatusCode.Conflict); - var seatsTaken = target.Enrollments.Count(x => ReservesSeat(x, now)); - Check("TRANSFER_TARGET_FULL", seatsTaken < targetCapacity, "Lớp đích đã hết chỗ.", HttpStatusCode.Conflict); - Check("TRANSFER_DUPLICATE_ENROLLMENT", !target.Enrollments.Any(x => x.LearnerId == source.LearnerId && ReservesSeat(x, now)), - "Học viên đã có ghi danh hoặc giữ chỗ ở lớp đích.", HttpStatusCode.Conflict); - var conflict = await HasLearnerConflictAsync(source.LearnerId, target.Sessions.Select(s => s.Availability).ToList(), source.Id, ct); - Check("TRANSFER_SCHEDULE_CONFLICT", !conflict, "Lịch lớp đích trùng với lịch học/tư vấn khác của học viên."); - return new TransferEvaluation(target, policy, checks); - } - - private static object TransferCohortSummary(StudyCohort c, DateTime now) => new - { - c.Id, c.Name, c.Status, c.MentorId, MentorName = $"{c.Mentor?.FirstName} {c.Mentor?.LastName}".Trim(), - Level = c.Plan?.CertificateLevel?.Code, c.PlanId, c.StartsAt, c.EndsAt, - Capacity = c.CapacitySnapshot ?? c.Capacity, - EnrolledCount = c.Enrollments.Count(x => ReservesSeat(x, now)), - SeatsAvailable = Math.Max(0, (c.CapacitySnapshot ?? c.Capacity) - c.Enrollments.Count(x => ReservesSeat(x, now))), - EnrollmentClosesAtUtc = c.Sessions.Count == 0 ? c.StartsAt : EnrollmentCutoffUtc(c), - Sessions = c.Sessions.OrderBy(s => s.Number).Select(s => new { s.Number, s.Availability.StartTime, s.Availability.EndTime }) - }; - - private static object TransferView(CohortTransferRequest x) => new - { - x.Id, x.Status, x.LearnerId, LearnerName = $"{x.Learner?.FirstName} {x.Learner?.LastName}".Trim(), - x.SourceCourseId, x.SourceCohortId, SourceCohortName = x.SourceCohort?.Name, - SourceMentorId = x.SourceCohort?.MentorId, - x.RequestedTargetCohortId, RequestedTargetCohortName = x.RequestedTargetCohort?.Name, - x.TargetCohortId, TargetCohortName = x.TargetCohort?.Name, - x.Reason, HasEvidence = !string.IsNullOrWhiteSpace(x.EvidenceUrl), - x.CreatedAtUtc, x.ReviewedAtUtc, x.DecisionNote, x.DestinationCourseId, x.PolicyVersionSnapshot, x.Revision, - History = x.History.OrderBy(h => h.Id).Select(h => new { h.Action, h.ActorRole, h.Detail, h.AtUtc }) - }; - - private IQueryable TransferDetails => uow.CohortTransferRequests.Query() - .Include(x => x.Learner).Include(x => x.SourceCohort).Include(x => x.RequestedTargetCohort) - .Include(x => x.TargetCohort).Include(x => x.History).AsSplitQuery(); - - public Task> RequestTransferAsync(int courseId, int? targetCohortId, string? reason, Guid idempotencyKey, - IFormFile? evidence, CancellationToken ct) => Run(async () => - { - if (Actor.Role != Role.Learner) throw new UnauthorizedAccessException(); - Rule(idempotencyKey != Guid.Empty, "TRANSFER_IDEMPOTENCY_KEY_REQUIRED", "Thiếu mã chống gửi trùng."); - var trimmed = reason?.Trim() ?? ""; - Rule(trimmed.Length is >= 10 and <= 1000, "TRANSFER_REASON_REQUIRED", "Nhập lý do chuyển lớp từ 10 đến 1000 ký tự."); - if (evidence is not null) - Rule(evidence.Length is > 0 and <= 10 * 1024 * 1024 && AllowedEvidenceTypes.Contains(evidence.ContentType), - "TRANSFER_EVIDENCE_INVALID", "Minh chứng phải là PDF/PNG/JPG tối đa 10 MB."); - object result = new { }; - string? evidenceUrl = null; - var uploaded = false; - var changed = false; - await uow.ExecuteInTransactionAsync(async token => - { - var locked = await uow.StudyCourses.LockAsync(courseId, token); - Rule(locked is not null, "TRANSFER_SOURCE_NOT_FOUND", "Không tìm thấy ghi danh.", HttpStatusCode.NotFound); - Rule(locked!.LearnerId == Actor.Id, "TRANSFER_FORBIDDEN", "Bạn chỉ được gửi yêu cầu cho ghi danh của mình.", HttpStatusCode.Forbidden); - var existing = await TransferDetails.SingleOrDefaultAsync(x => x.LearnerId == Actor.Id && x.IdempotencyKey == idempotencyKey, token); - if (existing is not null) - { - Rule(existing.SourceCourseId == courseId && existing.RequestedTargetCohortId == targetCohortId, - "TRANSFER_IDEMPOTENCY_KEY_REUSED", "Mã chống gửi trùng đã dùng cho yêu cầu khác.", HttpStatusCode.Conflict); - result = TransferView(existing); - return; - } - Rule(locked.CohortId.HasValue && locked.Status == "Active" && locked.PaymentStatus == "Paid", - "TRANSFER_SOURCE_NOT_ACTIVE", "Chỉ ghi danh lớp nhóm đang học mới được yêu cầu chuyển lớp.", HttpStatusCode.Conflict); - Rule(!await uow.CohortTransferRequests.AnyAsync(x => x.SourceCourseId == courseId && x.Status == CohortTransferRequest.Pending, token), - "TRANSFER_REQUEST_ALREADY_PENDING", "Đã có yêu cầu chuyển lớp đang chờ xử lý.", HttpStatusCode.Conflict); - var policy = await CurrentPolicyAsync(token); - Rule(policy.LearnerTransferEnabled, "TRANSFER_DISABLED_BY_POLICY", "Chính sách hiện hành chưa cho phép chuyển lớp."); - var sourceCohortForStart = await uow.StudyCohorts.Query().AsNoTracking() - .Include(x => x.Sessions).ThenInclude(x => x.Availability) - .SingleAsync(x => x.Id == locked.CohortId!.Value, token); - Rule(!SourceStarted(sourceCohortForStart, DateTime.UtcNow), "TRANSFER_SOURCE_STARTED", SourceStartedMessage); - if (targetCohortId.HasValue) - { - var sourceCohortId = locked.CohortId!.Value; - var target = await uow.StudyCohorts.Query().Include(x => x.Plan).Include(x => x.Sessions).ThenInclude(x => x.Availability) - .SingleOrDefaultAsync(x => x.Id == targetCohortId.Value, token); - Rule(target is not null, "TRANSFER_TARGET_NOT_FOUND", "Không tìm thấy lớp đích.", HttpStatusCode.NotFound); - Rule(target!.Id != sourceCohortId, "TRANSFER_TARGET_SAME_COHORT", "Lớp đích phải khác lớp hiện tại."); - Rule(target.Status == "Published", "TRANSFER_TARGET_NOT_PUBLISHED", "Lớp đích chưa mở đăng ký."); - Rule(target.Plan.CertificateLevelId == locked.CertificateLevelId, "TRANSFER_LEVEL_MISMATCH", "Lớp đích khác cấp độ JLPT của khóa đã mua."); - Rule((FirstSessionStartUtc(target) ?? target.StartsAt) > DateTime.UtcNow, "TRANSFER_TARGET_STARTED", - "Lớp đích đã bắt đầu; chưa hỗ trợ chuyển vào lớp đang học."); - } - if (evidence is not null && !uploaded) - { - await using var stream = evidence.OpenReadStream(); - evidenceUrl = (await storage.UploadPrivateVerificationAsync(stream, evidence.ContentType, Actor.Id, token)).Url; - uploaded = true; - } - var request = new CohortTransferRequest - { - LearnerId = Actor.Id, SourceCourseId = courseId, SourceCohortId = locked.CohortId!.Value, - RequestedTargetCohortId = targetCohortId, Reason = trimmed, EvidenceUrl = evidenceUrl, - IdempotencyKey = idempotencyKey, PolicyId = policy.Id == 0 ? null : policy.Id, - PolicyVersionSnapshot = policy.Version == 0 ? null : policy.Version, CreatedAtUtc = DateTime.UtcNow - }; - AddTransferEvent(request, "Requested", targetCohortId.HasValue - ? $"Học viên đề xuất chuyển sang lớp #{targetCohortId}." : "Học viên đề nghị Quản trị viên chọn lớp phù hợp."); - await uow.CohortTransferRequests.AddAsync(request, token); - var course = await uow.StudyCourses.Query().Include(x => x.Audit).SingleAsync(x => x.Id == courseId, token); - Audit(course, "CohortTransferRequested", "Học viên đã gửi yêu cầu chuyển lớp; đang chờ Quản trị viên xem xét."); - await uow.SaveChangesAsync(token); - var admins = await uow.UserAccounts.Query().Where(u => u.Role == Role.Admin && !u.IsDeleted).Select(u => u.Id).ToListAsync(token); - QueueNotifications($"cohort-transfer:{request.Id}:requested", "CohortTransferRequest", request.Id.ToString(), - admins.Select(id => (id, "Yêu cầu chuyển lớp mới", "Có học viên gửi yêu cầu chuyển lớp cần xem xét.", - "CohortTransfer", (string?)$"/admin/study-courses?transferRequestId={request.Id}"))); - await uow.SaveChangesAsync(token); - changed = true; - result = TransferView(await TransferDetails.SingleAsync(x => x.Id == request.Id, token)); - }, ct); - if (changed) - await NotifyAdminsCounterAsync("cohort_transfer_updated", ct); - return result; - }); - - public Task> TransferRequestsAsync(string? status, CancellationToken ct) => Run(async () => - { - if (Actor.Role is not (Role.Admin or Role.Learner)) throw new UnauthorizedAccessException(); - var actor = Actor; - var query = TransferDetails.Where(x => actor.Role == Role.Admin || x.LearnerId == actor.Id); - if (!string.IsNullOrWhiteSpace(status)) query = query.Where(x => x.Status == status); - var rows = await query.OrderByDescending(x => x.Id).Take(500).ToListAsync(ct); - return rows.Select(TransferView).ToList(); - }); - - public Task> TransferRequestDetailAsync(int requestId, CancellationToken ct) => Run(async () => - { - var request = await TransferDetails.SingleOrDefaultAsync(x => x.Id == requestId, ct); - Rule(request is not null, "TRANSFER_REQUEST_NOT_FOUND", "Không tìm thấy yêu cầu chuyển lớp.", HttpStatusCode.NotFound); - if (Actor.Role == Role.Learner) - { - // Không tiết lộ yêu cầu của Học viên khác. - Rule(request!.LearnerId == Actor.Id, "TRANSFER_REQUEST_NOT_FOUND", "Không tìm thấy yêu cầu chuyển lớp.", HttpStatusCode.NotFound); - return TransferView(request); - } - if (Actor.Role != Role.Admin) throw new UnauthorizedAccessException(); - var now = DateTime.UtcNow; - var source = await uow.StudyCourses.Query().AsNoTracking().Include(x => x.Sessions).Include(x => x.Homework) - .SingleAsync(x => x.Id == request!.SourceCourseId, ct); - var sourceCohort = await CohortForTransfer.AsNoTracking().SingleAsync(x => x.Id == request!.SourceCohortId, ct); - var assignments = await uow.HomeworkAssignments.Query().AsNoTracking().Include(h => h.Submission) - .Where(h => !h.IsDeleted && h.StudyCourseId == source.Id).ToListAsync(ct); - var candidates = await CohortForTransfer.AsNoTracking() - .Where(x => x.Id != sourceCohort.Id && x.Status == "Published" && x.Plan.CertificateLevelId == source.CertificateLevelId) - .ToListAsync(ct); - var targetId = request!.TargetCohortId ?? request.RequestedTargetCohortId; - var evaluation = request.Status == CohortTransferRequest.Pending - ? await EvaluateTransferAsync(source, sourceCohort, targetId, ct) : null; - return new - { - Request = TransferView(request), - SourceEnrollment = new - { - source.Id, source.Status, source.PaymentStatus, source.StartsAt, source.EndsAt, source.MentorId, - Progress = new - { - source.TotalSessions, - Attended = source.Sessions.Count(s => s.Status == "Present"), - Absent = source.Sessions.Count(s => s.Status is "Absent" or "ExcusedAbsent"), - Upcoming = source.Sessions.Count(s => s.Status == "Scheduled" && s.ScheduledAt > now), - HomeworkAssigned = assignments.Count + source.Homework.Count, - HomeworkSubmitted = assignments.Count(h => h.Submission is { IsDeleted: false }) + source.Homework.Count(h => h.SubmittedAt.HasValue) - } - }, - SourceCohort = TransferCohortSummary(sourceCohort, now), - CandidateCohorts = candidates.Where(c => (FirstSessionStartUtc(c) ?? c.StartsAt) > now) - .OrderBy(c => c.StartsAt).Select(c => TransferCohortSummary(c, now)).ToList(), - Eligibility = evaluation is null ? null : new - { - TargetCohortId = targetId, evaluation.Eligible, PolicyVersion = evaluation.Policy.Version, - Checks = evaluation.Checks.Select(c => new { c.Code, c.Passed, c.Message }) - } - }; - }); - - public Task> TransferEligibilityAsync(int requestId, int targetCohortId, CancellationToken ct) => Run(async () => - { - Admin(); - var request = await uow.CohortTransferRequests.Query().AsNoTracking().SingleOrDefaultAsync(x => x.Id == requestId, ct); - Rule(request is not null, "TRANSFER_REQUEST_NOT_FOUND", "Không tìm thấy yêu cầu chuyển lớp.", HttpStatusCode.NotFound); - var source = await uow.StudyCourses.Query().AsNoTracking().SingleAsync(x => x.Id == request!.SourceCourseId, ct); - var sourceCohort = await CohortForTransfer.AsNoTracking().SingleAsync(x => x.Id == request!.SourceCohortId, ct); - var evaluation = await EvaluateTransferAsync(source, sourceCohort, targetCohortId, ct); - return new - { - TargetCohortId = targetCohortId, evaluation.Eligible, PolicyVersion = evaluation.Policy.Version, - Target = evaluation.Target is null ? null : TransferCohortSummary(evaluation.Target, DateTime.UtcNow), - Checks = evaluation.Checks.Select(c => new { c.Code, c.Passed, c.Message }) - }; - }); - - public Task> ApproveTransferAsync(int requestId, ApproveCohortTransfer r, CancellationToken ct) => Run(async () => - { - Admin(); - Rule(r.Note is null || r.Note.Trim().Length <= 1000, "TRANSFER_NOTE_TOO_LONG", "Ghi chú tối đa 1000 ký tự."); - object result = new { }; - var changed = false; - await uow.ExecuteInTransactionAsync(async token => - { - var header = await uow.CohortTransferRequests.Query().AsNoTracking() - .Select(x => new { x.Id, x.SourceCourseId, x.LearnerId }).SingleOrDefaultAsync(x => x.Id == requestId, token); - Rule(header is not null, "TRANSFER_REQUEST_NOT_FOUND", "Không tìm thấy yêu cầu chuyển lớp.", HttpStatusCode.NotFound); - // Khóa hàng ghi danh nguồn: tuần tự hóa mọi quyết định trên cùng yêu cầu/ghi danh. - await uow.StudyCourses.LockAsync(header!.SourceCourseId, token); - var request = await uow.CohortTransferRequests.Query().Include(x => x.History).SingleAsync(x => x.Id == requestId, token); - if (request.Status == CohortTransferRequest.Approved) - { - Rule(!r.TargetCohortId.HasValue || r.TargetCohortId == request.TargetCohortId, "TRANSFER_REQUEST_NOT_PENDING", - "Yêu cầu đã được duyệt sang lớp khác.", HttpStatusCode.Conflict); - result = new { request.Id, request.Status, request.TargetCohortId, request.DestinationCourseId, Idempotent = true }; - return; - } - Rule(request.Status == CohortTransferRequest.Pending, "TRANSFER_REQUEST_NOT_PENDING", "Yêu cầu đã được xử lý.", HttpStatusCode.Conflict); - Rule(!r.ExpectedRevision.HasValue || r.ExpectedRevision == request.Revision, "TRANSFER_REQUEST_STALE", - "Yêu cầu vừa thay đổi. Hãy tải lại.", HttpStatusCode.Conflict); - var targetId = r.TargetCohortId ?? request.RequestedTargetCohortId; - Rule(targetId.HasValue, "TRANSFER_TARGET_REQUIRED", "Chọn lớp đích trước khi duyệt."); - await uow.StudyCourses.LockScheduleAsync(request.LearnerId, request.LearnerId, token); - foreach (var cohortId in new[] { request.SourceCohortId, targetId!.Value }.Distinct().OrderBy(x => x)) - await uow.StudyCourses.LockCohortAsync(cohortId, token); - - var source = await uow.StudyCourses.Query().Include(x => x.Sessions).Include(x => x.Audit).SingleAsync(x => x.Id == request.SourceCourseId, token); - var sourceCohort = await CohortForTransfer.SingleAsync(x => x.Id == request.SourceCohortId, token); - // Kiểm tra lại toàn bộ điều kiện tại thời điểm duyệt (sau khi giữ khóa). - var evaluation = await EvaluateTransferAsync(source, sourceCohort, targetId, token); - var failure = evaluation.FirstFailure; - if (failure is not null) throw new CourseRuleException(failure.Message, (HttpStatusCode)failure.Status, failure.Code); - var target = evaluation.Target!; - var now = DateTime.UtcNow; - - source.Status = "Transferred"; - source.TransferredAtUtc = now; - foreach (var s in source.Sessions.Where(s => s.Status == "Scheduled" && s.ScheduledAt > now)) - { - // Buổi tương lai của lớp nguồn: thu hồi quyền vào phòng, KHÔNG xóa; buổi đã diễn ra giữ nguyên điểm danh. - s.Status = "TransferredOut"; s.Note = $"Chuyển sang lớp #{target.Id} theo yêu cầu #{request.Id}."; - s.ConfirmedById = Actor.Id; s.ConfirmedAt = now; - } - var targetPolicy = target.Sessions.Select(s => s.Availability.GroupPolicy).FirstOrDefault(p => p is not null); - var destination = new StudyCourse - { - CohortId = target.Id, MentorId = target.MentorId, StartsAt = target.StartsAt, EndsAt = target.EndsAt, - SessionType = "Group", TargetExamDate = target.Plan.TargetExamDate, LearnerId = source.LearnerId, - PurchaseKey = Guid.NewGuid(), PlanId = target.PlanId, Name = target.Plan.Name, - CertificateLevelId = target.Plan.CertificateLevelId, PlanRevision = target.Plan.Revision, - DurationMonths = target.Plan.DurationMonths, SessionsPerWeek = target.Plan.SessionsPerWeek, - TotalSessions = target.Plan.TotalSessions!.Value, SessionMinutes = target.Plan.SessionMinutes!.Value, - // Giữ nguyên điều kiện quyền lợi đã đóng băng khi mua ở ghi danh nguồn. - RetakeClaimDays = source.RetakeClaimDays, MinimumHomeworkPercent = source.MinimumHomeworkPercent, - MaximumAbsencePercent = source.MaximumAbsencePercent, - GroupPolicyId = targetPolicy?.Id ?? target.GroupPolicyId, PolicyVersionSnapshot = targetPolicy?.Version ?? target.PolicyVersionSnapshot, - CapacitySnapshot = target.CapacitySnapshot ?? target.Capacity, - // Không thu thêm, không hoàn tiền, không tiêu thụ thêm quyền học: quyền đã thanh toán ở nguồn được chuyển sang. - Amount = 0, PaymentStatus = "Paid", Status = "Active", PaymentReference = $"TRANSFER:{source.Id}", - TransferredFromCourseId = source.Id, TransferredAtUtc = now - }; - AddCohortSessions(destination, target); - Audit(destination, "CohortTransferIn", $"Chuyển từ ghi danh #{source.Id} (lớp #{sourceCohort.Id}) theo yêu cầu #{request.Id}."); - Audit(source, "CohortTransferOut", $"Đã chuyển sang lớp {target.Name}; lịch sử điểm danh và bài tập về nhà được giữ nguyên."); - await uow.StudyCourses.AddAsync(destination, token); - await uow.SaveChangesAsync(token); - - request.Status = CohortTransferRequest.Approved; request.TargetCohortId = target.Id; - request.DestinationCourseId = destination.Id; request.ReviewedById = Actor.Id; request.ReviewedAtUtc = now; - request.DecisionNote = string.IsNullOrWhiteSpace(r.Note) ? null : r.Note.Trim(); - request.PolicyId = evaluation.Policy.Id == 0 ? request.PolicyId : evaluation.Policy.Id; - request.PolicyVersionSnapshot = evaluation.Policy.Version == 0 ? request.PolicyVersionSnapshot : evaluation.Policy.Version; - request.EligibilitySnapshot = JsonSerializer.Serialize(evaluation.Checks.Select(c => new { c.Code, c.Passed })); - request.Revision++; - AddTransferEvent(request, "Approved", $"Quản trị viên đã phê duyệt chuyển sang lớp {target.Name}."); - QueueNotifications($"cohort-transfer:{request.Id}:approved", "CohortTransferRequest", request.Id.ToString(), - [ - (request.LearnerId, "Yêu cầu chuyển lớp đã được duyệt", $"Bạn đã được chuyển sang {NotificationDisplayNormalizer.ClassSubject(target.Name, lowercasePrefix: true)}.", "CohortTransfer", $"/my-courses/{destination.Id}"), - (sourceCohort.MentorId, "Thay đổi danh sách lớp", $"Một học viên đã chuyển khỏi {NotificationDisplayNormalizer.ClassSubject(sourceCohort.Name, lowercasePrefix: true)}.", "CohortRoster", $"/mentor/cohorts/{sourceCohort.Id}"), - (target.MentorId, "Thay đổi danh sách lớp", $"Một học viên mới chuyển vào {NotificationDisplayNormalizer.ClassSubject(target.Name, lowercasePrefix: true)}.", "CohortRoster", $"/mentor/cohorts/{target.Id}") - ]); - await uow.SaveChangesAsync(token); - changed = true; - result = new { request.Id, request.Status, request.TargetCohortId, request.DestinationCourseId, Idempotent = false }; - }, ct); - if (changed) - await NotifyAdminsCounterAsync("cohort_transfer_updated", ct); - return result; - }); - - public Task> RejectTransferAsync(int requestId, RejectCohortTransfer r, CancellationToken ct) => Run(async () => - { - Admin(); - var reason = r.Reason?.Trim() ?? ""; - Rule(reason.Length is >= 1 and <= 1000, "TRANSFER_REJECTION_REASON_REQUIRED", "Nhập lý do từ chối (tối đa 1000 ký tự)."); - object result = new { }; - var changed = false; - await uow.ExecuteInTransactionAsync(async token => - { - var header = await uow.CohortTransferRequests.Query().AsNoTracking().Select(x => new { x.Id, x.SourceCourseId }) - .SingleOrDefaultAsync(x => x.Id == requestId, token); - Rule(header is not null, "TRANSFER_REQUEST_NOT_FOUND", "Không tìm thấy yêu cầu chuyển lớp.", HttpStatusCode.NotFound); - await uow.StudyCourses.LockAsync(header!.SourceCourseId, token); - var request = await uow.CohortTransferRequests.Query().Include(x => x.History).SingleAsync(x => x.Id == requestId, token); - if (request.Status == CohortTransferRequest.Rejected) - { - result = new { request.Id, request.Status, request.DecisionNote, Idempotent = true }; - return; - } - Rule(request.Status == CohortTransferRequest.Pending, "TRANSFER_REQUEST_NOT_PENDING", "Yêu cầu đã được xử lý.", HttpStatusCode.Conflict); - Rule(!r.ExpectedRevision.HasValue || r.ExpectedRevision == request.Revision, "TRANSFER_REQUEST_STALE", - "Yêu cầu vừa thay đổi. Hãy tải lại.", HttpStatusCode.Conflict); - request.Status = CohortTransferRequest.Rejected; request.DecisionNote = reason; - request.ReviewedById = Actor.Id; request.ReviewedAtUtc = DateTime.UtcNow; request.Revision++; - AddTransferEvent(request, "Rejected", reason); - var source = await uow.StudyCourses.Query().Include(x => x.Audit).SingleAsync(x => x.Id == request.SourceCourseId, token); - Audit(source, "CohortTransferRejected", $"Yêu cầu #{request.Id} bị từ chối: {reason}"); - QueueNotifications($"cohort-transfer:{request.Id}:rejected", "CohortTransferRequest", request.Id.ToString(), - [(request.LearnerId, "Yêu cầu chuyển lớp bị từ chối", reason, "CohortTransfer", $"/my-courses/{request.SourceCourseId}")]); - await uow.SaveChangesAsync(token); - changed = true; - result = new { request.Id, request.Status, request.DecisionNote, Idempotent = false }; - }, ct); - if (changed) - await NotifyAdminsCounterAsync("cohort_transfer_updated", ct); - return result; - }); - - public Task> WithdrawTransferAsync(int requestId, CancellationToken ct) => Run(async () => - { - if (Actor.Role != Role.Learner) throw new UnauthorizedAccessException(); - object result = new { }; - var changed = false; - await uow.ExecuteInTransactionAsync(async token => - { - var header = await uow.CohortTransferRequests.Query().AsNoTracking().Select(x => new { x.Id, x.SourceCourseId, x.LearnerId }) - .SingleOrDefaultAsync(x => x.Id == requestId, token); - Rule(header is not null && header.LearnerId == Actor.Id, "TRANSFER_REQUEST_NOT_FOUND", "Không tìm thấy yêu cầu chuyển lớp.", HttpStatusCode.NotFound); - await uow.StudyCourses.LockAsync(header!.SourceCourseId, token); - var request = await uow.CohortTransferRequests.Query().Include(x => x.History).SingleAsync(x => x.Id == requestId, token); - if (request.Status == CohortTransferRequest.Withdrawn) { result = new { request.Id, request.Status, Idempotent = true }; return; } - Rule(request.Status == CohortTransferRequest.Pending, "TRANSFER_REQUEST_NOT_PENDING", "Yêu cầu đã được xử lý.", HttpStatusCode.Conflict); - request.Status = CohortTransferRequest.Withdrawn; request.Revision++; - AddTransferEvent(request, "Withdrawn", "Học viên rút yêu cầu."); - await uow.SaveChangesAsync(token); - changed = true; - result = new { request.Id, request.Status, Idempotent = false }; - }, ct); - if (changed) - await NotifyAdminsCounterAsync("cohort_transfer_updated", ct); - return result; - }); - - public async Task TransferEvidenceAsync(int requestId, CancellationToken ct) - { - var request = await uow.CohortTransferRequests.Query().AsNoTracking().SingleOrDefaultAsync(x => x.Id == requestId, ct); - if (request is null || string.IsNullOrWhiteSpace(request.EvidenceUrl) - || (Actor.Role != Role.Admin && !(Actor.Role == Role.Learner && request.LearnerId == Actor.Id))) return null; - return await storage.OpenPrivateVerificationAsync(request.EvidenceUrl, ct); - } -} diff --git a/RikiPath.Application/Services/StudyCourseService.cs b/RikiPath.Application/Services/StudyCourseService.cs index 9c97ee1..56e4465 100644 --- a/RikiPath.Application/Services/StudyCourseService.cs +++ b/RikiPath.Application/Services/StudyCourseService.cs @@ -37,7 +37,7 @@ private sealed class CourseRuleException(string message, HttpStatusCode status = public HttpStatusCode Status { get; } = status; public string? Code { get; } = code; } - // Quy tắc nghiệp vụ có mã lỗi miền ổn định (dùng cho chuyển lớp/thay Mentor). + // Quy tắc nghiệp vụ có mã lỗi miền ổn định. private static void Rule(bool condition, string code, string message, HttpStatusCode status = HttpStatusCode.UnprocessableEntity) { if (!condition) throw new CourseRuleException(message, status, code); @@ -260,7 +260,7 @@ private async Task EffectiveGroupPolicyAsync(DateTime atUtc, MinimumPreparationDays = 1, MinimumPublishedEnrollmentDays = 7, CancellationLeadHours = 24, ReschedulingLeadHours = 24, MentorReplacementLeadHours = 24, CheckoutHoldMinutes = 10, HomeworkDeadlineDays = 7, PlacementAttemptLimit = 2, - RemediationCompletionThresholdPercent = 90m, RemediationThresholdComparison = ">", KpiReportingPeriodDays = 30 + KpiReportingPeriodDays = 30 }; public Task> SavePlanAsync(int? id, SaveCoursePlan r, CancellationToken ct) => Run(() => @@ -343,9 +343,7 @@ public Task> DetailAsync(int id, CancellationToken ct) => Ru if (c.CohortId.HasValue) { var nowUtc = DateTime.UtcNow; - effectivePolicy ??= groupPolicies is null - ? null - : await groupPolicies.GetEffectiveAsync(c.StartsAt ?? c.Cohort?.StartsAt ?? nowUtc, ct); + effectivePolicy ??= await RetakeEligibilityEvaluator.ResolvePolicyAsync(uow, groupPolicies, c, ct); cohortAssignments = await uow.HomeworkAssignments.Query().AsNoTracking() .Include(h => h.Submission) .Where(h => !h.IsDeleted && h.StudyCourseId == c.Id) @@ -713,12 +711,12 @@ await uow.ExecuteInTransactionAsync(async token => grantDirectEntitlement ? "AdminEntitlement" : "PayOS", grantDirectEntitlement ? null : holdMinutes) }; if (grantDirectEntitlement && cohort is not null) AddCohortSessions(course, cohort); - var retakeThresholdOp = holdPolicy?.RemediationThresholdComparison ?? ">"; - var retakeThresholdPct = holdPolicy?.RemediationCompletionThresholdPercent ?? 90m; + var retakeHomeworkPct = holdPolicy?.RemediationCompletionThresholdPercent ?? MentorGroupPolicy.DefaultRetakeHomeworkThresholdPercent; + var retakeAttendancePct = holdPolicy?.RemediationAttendanceThresholdPercent ?? MentorGroupPolicy.DefaultRetakeAttendanceThresholdPercent; Audit(course, grantDirectEntitlement ? "CohortEnrolled" : "PurchaseCreated", grantDirectEntitlement ? $"Ghi danh lớp #{cohort!.Id} theo quyền học được duyệt ({entitlementMode.EntitlementReference ?? "entitlement"})." - : $"Đã lưu thông tin gói học. Quyền học lại một lần xét minh chứng nộp bài tập về nhà đúng hạn ({retakeThresholdOp} {retakeThresholdPct:0.##}%); không xét tỷ lệ nghỉ."); + : $"Đã lưu thông tin gói học. Hỗ trợ ôn lại JLPT xét hoàn thành bài tập ≥ {retakeHomeworkPct:0.##}% và chuyên cần ≥ {retakeAttendancePct:0.##}% theo chính sách lớp học."); await uow.StudyCourses.AddAsync(course, token); await uow.SaveChangesAsync(token); if (grantDirectEntitlement && cohort is not null && !string.IsNullOrWhiteSpace(entitlementMode.EntitlementReference) @@ -867,10 +865,10 @@ await uow.ExecuteInTransactionAsync(async token => return; } - // Học viên không thể tự hủy ghi danh sau khi đã thanh toán và ghi danh có hiệu lực; Admin xử lý chuyển lớp/hoàn tiền/ngoại lệ. + // Học viên không thể tự hủy ghi danh sau khi đã thanh toán và ghi danh có hiệu lực; Admin xử lý hoàn tiền hoặc ngoại lệ. Rule(Actor.Role == Role.Admin, "LEARNER_SELF_CANCEL_DISABLED", - "Học viên không thể tự hủy ghi danh sau khi đã thanh toán. Vui lòng gửi yêu cầu hỗ trợ hoặc chuyển lớp để Quản trị viên xem xét.", + "Học viên không thể tự hủy ghi danh sau khi đã thanh toán. Vui lòng gửi yêu cầu qua Khiếu nại & hỗ trợ để Quản trị viên xem xét.", HttpStatusCode.Forbidden); RequireConflict(course.Status is "Active" or "Ready" && course.PaymentStatus is "Paid" or "PartiallyRefunded", @@ -1010,7 +1008,7 @@ await uow.ExecuteInTransactionAsync(async token => c.PaymentReviewReason = reviewReason; enteredPaymentReview = true; Audit(c, "PaidEnrollmentUnresolved", - "Đã nhận thanh toán nhưng suất học không còn hợp lệ; chuyển Quản trị viên xem xét hoàn tiền hoặc chuyển lớp."); + "Đã nhận thanh toán nhưng suất học không còn hợp lệ; chuyển Quản trị viên xem xét hoàn tiền hoặc hỗ trợ học viên."); await QueuePaymentReviewNotificationsAsync(c, token); } else @@ -1361,65 +1359,37 @@ public Task> RequestRetakeAsync(int id, DateTime examDate, D { Learner(c); var normalizedReason = reason?.Trim() ?? string.Empty; - Require(normalizedReason.Length <= 1000, "Lý do yêu cầu ôn lại tối đa 1000 ký tự."); - if (c.CohortId.HasValue) - Require(!string.IsNullOrWhiteSpace(normalizedReason), "Vui lòng nhập lý do/tường trình kết quả thi JLPT chính thức."); - var effectivePolicy = c.GroupPolicy ?? (groupPolicies is null ? null : await groupPolicies.GetEffectiveAsync(c.StartsAt ?? c.Cohort?.StartsAt ?? DateTime.UtcNow, ct)); - var cohortAssignments = c.CohortId.HasValue - ? await uow.HomeworkAssignments.Query().AsNoTracking() - .Include(h => h.Submission) - .Where(h => !h.IsDeleted && h.StudyCourseId == c.Id) - .ToListAsync(ct) - : []; - var eligibility = CourseRetakePolicy.Evaluate(c, await uow.StudyCourses.Query().AnyAsync(x => x.RetakeOfId == id, ct), effectivePolicy, cohortAssignments); - Require(c.Status == "Completed" && c.PaymentStatus is "Paid" or "PartiallyRefunded" && c.RetakeOfId is null - && !await uow.StudyCourses.Query().AnyAsync(x => x.RetakeOfId == id, ct), "Khóa chưa hoàn thành hoặc đã dùng quyền học lại."); - Require(!c.RetakeRequests.Any(x => x.Status == "Pending"), "Đã có yêu cầu đang chờ duyệt."); + Require(normalizedReason.Length <= 1000, "Nội dung yêu cầu tối đa 1000 ký tự."); + var eligibility = await RetakeEligibilityEvaluator.EvaluateAsync(uow, groupPolicies, c, ct); + Rule(eligibility.Status == RetakeEligibilityStatus.Eligible, "RETAKE_NOT_ELIGIBLE", + eligibility.Reasons.FirstOrDefault() ?? "Bạn chưa đủ điều kiện gửi yêu cầu hỗ trợ ôn lại JLPT.", HttpStatusCode.Conflict); + Rule(!c.RetakeRequests.Any(x => x.Status is "Pending" or "Approved"), "RETAKE_REQUEST_EXISTS", + "Bạn đã có yêu cầu hỗ trợ ôn lại JLPT đang xử lý hoặc đã được phê duyệt.", HttpStatusCode.Conflict); var courseStartDate = (c.StartsAt ?? c.Cohort?.StartsAt)?.Date; - Require(courseStartDate.HasValue && examDate.Kind == DateTimeKind.Utc && resultPublishedAt.Kind == DateTimeKind.Utc - && examDate.Date >= courseStartDate.Value && examDate <= resultPublishedAt && resultPublishedAt <= DateTime.UtcNow, "Kiểm tra ngày thi và ngày công bố kết quả JLPT."); - Require(!c.RetakeClaimDays.HasValue || DateTime.UtcNow <= resultPublishedAt.AddDays(c.RetakeClaimDays.Value), "Đã quá hạn gửi yêu cầu theo chính sách khi mua."); - var requireOfficialEvidence = effectivePolicy?.RequireOfficialExamEvidence ?? true; - string evidenceUrl = string.Empty; - if (requireOfficialEvidence || evidence is not null) - { - Require(evidence is not null && evidence.Length is > 0 and <= 10 * 1024 * 1024 - && evidence.ContentType is "application/pdf" or "image/png" or "image/jpeg", "Minh chứng phải là PDF/PNG/JPG tối đa 10 MB."); - await using var stream = evidence!.OpenReadStream(); - var file = await storage.UploadPrivateVerificationAsync(stream, evidence.ContentType, Actor.Id, ct); - evidenceUrl = file.Url; - } + Require(courseStartDate.HasValue && examDate.Kind == DateTimeKind.Utc && resultPublishedAt.Kind == DateTimeKind.Utc, + "Ngày thi và ngày công bố kết quả không hợp lệ."); + Require(examDate.Date >= courseStartDate!.Value, "Ngày thi JLPT phải sau ngày bắt đầu khóa học."); + Require(resultPublishedAt.Date >= examDate.Date, "Ngày công bố kết quả không được trước ngày thi."); + Require(resultPublishedAt <= DateTime.UtcNow, "Ngày công bố kết quả không được ở tương lai."); + Require(!c.RetakeClaimDays.HasValue || DateTime.UtcNow <= resultPublishedAt.AddDays(c.RetakeClaimDays.Value), + "Đã quá hạn gửi yêu cầu theo chính sách khi ghi danh."); + Rule(!c.RetakeRequests.Any(x => x.ExamDate.Date == examDate.Date && x.Status is "Pending" or "Approved"), "RETAKE_REQUEST_EXISTS", + "Kết quả thi này đã có yêu cầu hỗ trợ.", HttpStatusCode.Conflict); + // Official JLPT evidence is always required (CK_MentorGroupPolicy_Evidence) and stored privately. + Require(evidence is not null && evidence.Length is > 0 and <= 10 * 1024 * 1024 + && evidence.ContentType is "application/pdf" or "image/png" or "image/jpeg", "Minh chứng phải là PDF/PNG/JPG tối đa 10 MB."); + await using var stream = evidence!.OpenReadStream(); + var file = await storage.UploadPrivateVerificationAsync(stream, evidence.ContentType, Actor.Id, ct); var retakeRequest = new CourseRetakeRequest { ExamDate = examDate, ResultPublishedAt = resultPublishedAt, - EvidenceUrl = evidenceUrl, + EvidenceUrl = file.Url, Reason = normalizedReason, EligibilitySnapshot = JsonSerializer.Serialize(eligibility) }; c.RetakeRequests.Add(retakeRequest); - var requireAdminReview = effectivePolicy?.RequireAdminRemediationReview ?? true; - if (!requireAdminReview && eligibility.CanClaim && c.SessionType == "Individual") - { - retakeRequest.Status = "Approved"; - retakeRequest.ReviewedAt = DateTime.UtcNow; - retakeRequest.Response = "Tự động duyệt theo chính sách học lại."; - var retake = new StudyCourse - { - LearnerId = c.LearnerId, PurchaseKey = Guid.NewGuid(), PlanId = c.PlanId, RetakeOfId = c.Id, - SessionType = c.SessionType, Name = c.Name, CertificateLevelId = c.CertificateLevelId, PlanRevision = c.PlanRevision, - DurationMonths = c.DurationMonths, SessionsPerWeek = c.SessionsPerWeek, SessionMinutes = c.SessionMinutes, - TotalSessions = c.TotalSessions, RetakeClaimDays = c.RetakeClaimDays, MinimumHomeworkPercent = c.MinimumHomeworkPercent, - MaximumAbsencePercent = c.MaximumAbsencePercent, GroupPolicyId = effectivePolicy?.Id, - PolicyVersionSnapshot = effectivePolicy?.Version, Amount = 0, PaymentStatus = "Paid", Status = "Ready" - }; - Audit(retake, "FreeRetakeAutoApproved", $"Học lại một lần của khóa {c.Id} theo chính sách không cần Quản trị viên phê duyệt."); - await uow.StudyCourses.AddAsync(retake, ct); - await uow.SaveChangesAsync(ct); - Audit(c, "RetakeAutoApproved", "Đủ điều kiện học lại theo chính sách hiện hành."); - return new { c.Id, NewCourseId = retake.Id, AutoApproved = true }; - } - Audit(c, "RetakeRequested", "Học viên đã gửi minh chứng kết quả JLPT; đang chờ Quản trị viên xác minh danh tính, cấp độ và kết quả."); + Audit(c, "RetakeRequested", $"Học viên gửi yêu cầu hỗ trợ ôn lại JLPT (chính sách v{eligibility.PolicyVersion}; bài tập {eligibility.PassedOnTimeHomework}/{eligibility.RequiredHomework} ≥ {eligibility.HomeworkThresholdPercent:0.##}%; chuyên cần {eligibility.AttendedSessions}/{eligibility.ValidSessions} ≥ {eligibility.AttendanceThresholdPercent:0.##}%)."); return new { c.Id, AutoApproved = false }; }, ct, () => NotifyAdminsCounterAsync("retake_request_updated", ct)); @@ -1427,67 +1397,50 @@ public Task> ReviewRetakeAsync(int id, int requestId, Review { Admin(); var request = c.RetakeRequests.SingleOrDefault(x => x.Id == requestId); - Require(request is { Status: "Pending" }, "Yêu cầu đã xử lý hoặc không tồn tại."); - Require(!string.IsNullOrWhiteSpace(r.Response) && r.Response.Length <= 2000, "Cần ghi lý do/quyết định, tối đa 2000 ký tự."); - int? newCourseId = null; + Rule(request is { Status: "Pending" }, "RETAKE_REQUEST_ALREADY_REVIEWED", "Yêu cầu đã được xử lý hoặc không tồn tại.", HttpStatusCode.Conflict); + var response = r.Response?.Trim() ?? string.Empty; + Require(!string.IsNullOrWhiteSpace(response) && response.Length <= 2000, "Cần nhập phản hồi hoặc lý do, tối đa 2000 ký tự."); + // Re-evaluate against the policy version pinned to this enrollment, never the latest one. + var eligibility = await RetakeEligibilityEvaluator.EvaluateAsync(uow, groupPolicies, c, ct); if (r.Approve) { - var effectivePolicy = c.GroupPolicy ?? (c.GroupPolicyId.HasValue && groupPolicies is not null - ? await groupPolicies.GetEffectiveAsync(c.StartsAt ?? c.Cohort?.StartsAt ?? DateTime.UtcNow, ct) - : null); - var cohortAssignments = c.CohortId.HasValue - ? await uow.HomeworkAssignments.Query().AsNoTracking() - .Include(h => h.Submission) - .Where(h => !h.IsDeleted && h.StudyCourseId == c.Id) - .ToListAsync(ct) - : []; - var eligibility = CourseRetakePolicy.Evaluate(c, false, effectivePolicy, cohortAssignments); - var requireOfficial = effectivePolicy?.RequireOfficialExamEvidence ?? true; - if (requireOfficial) - Require(r.OfficialFailureVerified, "Quản trị viên cần xác nhận minh chứng kết quả JLPT khớp với học viên và cấp độ của khóa học."); - Require(c.Status == "Completed" && c.PaymentStatus is "Paid" or "PartiallyRefunded" && c.RetakeOfId is null - && !await uow.StudyCourses.Query().AnyAsync(x => x.RetakeOfId == id, ct), "Khóa không còn quyền học lại."); - if (effectivePolicy is null) - { - var fallbackPercent = c.MinimumHomeworkPercent > 0m ? c.MinimumHomeworkPercent : 90m; - Require(r.OnTimeHomeworkEvidenceVerified, - $"Quản trị viên cần xác nhận minh chứng học viên đã nộp đúng hạn đạt ngưỡng {fallbackPercent:0.##}% bài tập về nhà."); - } - else + Require(r.OfficialFailureVerified, "Cần xác nhận minh chứng kết quả JLPT chính thức khớp với học viên và cấp độ khóa học."); + Rule(eligibility.Status == RetakeEligibilityStatus.Eligible, "RETAKE_NOT_ELIGIBLE", + eligibility.Reasons.FirstOrDefault() ?? "Học viên chưa đủ điều kiện hỗ trợ ôn lại JLPT.", HttpStatusCode.Conflict); + } + request!.Status = r.Approve ? "Approved" : "Rejected"; + request.Response = response; + request.ReviewedById = Actor.Id; + request.ReviewedAt = DateTime.UtcNow; + request.EligibilitySnapshot = JsonSerializer.Serialize(eligibility); + var reviewLabel = r.Approve ? "Đã phê duyệt" : "Đã từ chối"; + Audit(c, "RetakeReviewed", $"Yêu cầu hỗ trợ ôn lại #{request.Id}: {reviewLabel} (chính sách v{eligibility.PolicyVersion}; bài tập {eligibility.PassedOnTimeHomework}/{eligibility.RequiredHomework}; chuyên cần {eligibility.AttendedSessions}/{eligibility.ValidSessions}). {response}"); + var learnerLink = $"/my-courses/{c.Id}/?section=support&retakeRequestId={request.Id}"; + var notifications = new List + { + new { - Require(eligibility.HomeworkMet || r.OnTimeHomeworkEvidenceVerified, - $"Học viên chưa đạt điều kiện nộp bài tập về nhà đúng hạn ({effectivePolicy.RemediationThresholdComparison} {effectivePolicy.RemediationCompletionThresholdPercent:0.##}%)."); + UserId = c.LearnerId, + Title = r.Approve ? "Yêu cầu hỗ trợ ôn lại JLPT đã được phê duyệt" : "Yêu cầu hỗ trợ ôn lại JLPT bị từ chối", + Message = c.Cohort?.Name ?? c.Name, + Type = r.Approve ? "RetakeSupportApproved" : "RetakeSupportRejected", + LinkUrl = learnerLink } - var retake = new StudyCourse { LearnerId = c.LearnerId, PurchaseKey = Guid.NewGuid(), PlanId = c.PlanId, - RetakeOfId = c.Id, SessionType = c.SessionType, Name = c.Name, CertificateLevelId = c.CertificateLevelId, PlanRevision = c.PlanRevision, - DurationMonths = c.DurationMonths, SessionsPerWeek = c.SessionsPerWeek, SessionMinutes = c.SessionMinutes, - TotalSessions = c.TotalSessions, RetakeClaimDays = c.RetakeClaimDays, MinimumHomeworkPercent = c.MinimumHomeworkPercent, - MaximumAbsencePercent = c.MaximumAbsencePercent, GroupPolicyId = effectivePolicy?.Id, - PolicyVersionSnapshot = effectivePolicy?.Version, Amount = 0, PaymentStatus = "Paid", Status = "Ready" }; - if (c.SessionType == "Group") + }; + var mentorId = c.MentorId ?? c.Cohort?.MentorId; + if (r.Approve && mentorId is int mid) + notifications.Add(new { - Require(r.CohortId.HasValue, "Chọn lớp đợt kế tiếp cho gói học lại nhóm."); - await uow.StudyCourses.LockCohortAsync(r.CohortId!.Value, ct); - var cohort = await uow.StudyCohorts.Query().Include(x => x.Plan).Include(x => x.Enrollments) - .Include(x => x.Sessions).ThenInclude(x => x.Availability).SingleOrDefaultAsync(x => x.Id == r.CohortId.Value, ct); - Require(cohort is not null && cohort.Status == "Published" && cohort.StartsAt > DateTime.UtcNow - && cohort.Plan.CertificateLevelId == c.CertificateLevelId && cohort.Plan.TotalSessions >= c.TotalSessions - && cohort.Plan.SessionMinutes >= c.SessionMinutes - && cohort.Enrollments.Count(x => ReservesSeat(x, DateTime.UtcNow)) < (cohort.CapacitySnapshot ?? cohort.Capacity), - "Lớp học lại phải còn chỗ, cùng cấp độ, đủ số buổi/thời lượng tương đương và chưa bắt đầu."); - retake.CohortId = cohort!.Id; retake.PlanId = cohort.PlanId; retake.MentorId = cohort.MentorId; - retake.StartsAt = cohort.StartsAt; retake.EndsAt = cohort.EndsAt; retake.CapacitySnapshot = cohort.CapacitySnapshot ?? cohort.Capacity; - retake.TotalSessions = cohort.Sessions.Count; retake.SessionMinutes = cohort.Plan.SessionMinutes!.Value; - AddCohortSessions(retake, cohort); - } - Audit(retake, "FreeRetakeCreated", $"Học lại một lần của khóa {c.Id}; không phát sinh quyền học lại tiếp."); - await uow.StudyCourses.AddAsync(retake, ct); await uow.SaveChangesAsync(ct); newCourseId = retake.Id; - } - request!.Status = r.Approve ? "Approved" : "Rejected"; request.Response = r.Response.Trim(); - request.ReviewedById = Actor.Id; request.ReviewedAt = DateTime.UtcNow; - var reviewLabel = r.Approve ? "Đã chấp thuận" : "Đã từ chối"; - Audit(c, "RetakeReviewed", $"Yêu cầu ôn lại: {reviewLabel}. {r.Response.Trim()}"); - return new { NewCourseId = newCourseId }; + UserId = mid, + Title = "Cần lập kế hoạch ôn lại JLPT", + Message = $"{c.Learner?.FirstName} {c.Learner?.LastName}".Trim() is { Length: > 0 } name ? name : (c.Cohort?.Name ?? c.Name), + Type = "RetakeSupportPlanRequired", + LinkUrl = c.CohortId.HasValue + ? $"/mentor-study-courses/{c.CohortId}/?section=support&retakeRequestId={request.Id}" + : $"/mentor-study-courses/?retakeRequestId={request.Id}" + }); + EnqueueLearningNotifications($"retake-reviewed:{request.Id}", c.Id, notifications); + return new { request.Id, request.Status }; }, ct, () => NotifyAdminsCounterAsync("retake_request_updated", ct)); public Task> SaveRetakeSupportPlanAsync(int id, int requestId, SaveRetakeSupportPlan r, CancellationToken ct) => Change(id, c => @@ -1495,13 +1448,26 @@ public Task> SaveRetakeSupportPlanAsync(int id, int requestI Teacher(c); var request = c.RetakeRequests.SingleOrDefault(x => x.Id == requestId); RequireConflict(request is not null, "Không tìm thấy yêu cầu hỗ trợ ôn lại JLPT."); - RequireConflict(request!.Status == "Approved", "Chỉ Giáo viên mới được lập kế hoạch hỗ trợ sau khi Quản trị viên đã phê duyệt yêu cầu."); - var plan = r.SupportPlan?.Trim() ?? string.Empty; - Require(!string.IsNullOrWhiteSpace(plan) && plan.Length <= 2000, "Cần nhập lộ trình hỗ trợ ôn lại tối đa 2000 ký tự."); + RequireConflict(request!.Status == "Approved", "Chỉ lập kế hoạch ôn lại sau khi Quản trị viên đã phê duyệt yêu cầu."); + var plan = RetakeSupportPlanFormat.Normalize(r); + Require(plan is not null, "Cần nhập mục tiêu củng cố và nội dung ôn tập."); + Require(plan!.Length <= 2000, "Kế hoạch ôn lại quá dài, vui lòng rút gọn (tối đa 2000 ký tự)."); + var firstPublish = string.IsNullOrWhiteSpace(request.MentorSupportPlan); request.MentorSupportPlan = plan; request.MentorSupportPlanById = Actor.Id; request.MentorSupportPlanAtUtc = DateTime.UtcNow; - Audit(c, "RetakeSupportPlanSaved", $"Giáo viên đã lập kế hoạch hỗ trợ ôn tập cho yêu cầu #{requestId}."); + Audit(c, "RetakeSupportPlanSaved", $"Giáo viên đã {(firstPublish ? "công bố" : "cập nhật")} kế hoạch ôn lại cho yêu cầu #{requestId}."); + EnqueueLearningNotifications($"retake-plan:{request.Id}:{request.MentorSupportPlanAtUtc:yyyyMMddHHmmss}", c.Id, + [ + new + { + UserId = c.LearnerId, + Title = firstPublish ? "Giáo viên đã công bố kế hoạch ôn lại JLPT" : "Kế hoạch ôn lại JLPT đã được cập nhật", + Message = c.Cohort?.Name ?? c.Name, + Type = "RetakeSupportPlanPublished", + LinkUrl = $"/my-courses/{c.Id}/?section=support&retakeRequestId={request.Id}" + } + ]); return Task.FromResult(new { request.Id, @@ -1511,6 +1477,23 @@ public Task> SaveRetakeSupportPlanAsync(int id, int requestI }); }, ct); + /// Learning notifications through the existing transactional outbox (same channel as class completion). + private void EnqueueLearningNotifications(string eventKey, int courseId, IReadOnlyCollection notifications) + { + if (notifications.Count == 0) return; + uow.AddMentorOutboxEvent(new MentorOutboxEvent + { + EventKey = eventKey, + AggregateType = "StudyCourse", + AggregateId = courseId.ToString(System.Globalization.CultureInfo.InvariantCulture), + EventType = "CohortLearningNotification", + EventVersion = 1, + PayloadJson = JsonSerializer.Serialize(new { Notifications = notifications }), + CreatedAtUtc = DateTime.UtcNow, + AvailableAtUtc = DateTime.UtcNow + }); + } + public async Task EvidenceAsync(int id, int requestId, CancellationToken ct) { var c = await Details.SingleOrDefaultAsync(x => x.Id == id, ct); diff --git a/RikiPath.Application/Services/StudyCourseSharedHelpers.cs b/RikiPath.Application/Services/StudyCourseSharedHelpers.cs new file mode 100644 index 0000000..1d98638 --- /dev/null +++ b/RikiPath.Application/Services/StudyCourseSharedHelpers.cs @@ -0,0 +1,53 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using RikiPath.Domain.Entities; + +namespace RikiPath.Application.Services; + +public sealed partial class StudyCourseService +{ + public const string CohortNotificationEvent = "CohortLearningNotification"; + private static readonly HashSet AllowedEvidenceTypes = ["application/pdf", "image/png", "image/jpeg"]; + + internal sealed record CohortOperationCheck(string Code, bool Passed, string Message, int Status); + + private void QueueNotifications(string eventKey, string aggregateType, string aggregateId, + IEnumerable<(int UserId, string Title, string Message, string Type, string? LinkUrl)> items) + { + var list = items.Where(x => x.UserId > 0).DistinctBy(x => x.UserId).ToList(); + if (list.Count == 0) return; + // Outbox ghi cùng giao dịch; dispatcher gửi sau khi commit và tự thử lại khi gửi lỗi. + uow.AddMentorOutboxEvent(new MentorOutboxEvent + { + EventKey = eventKey, + AggregateType = aggregateType, + AggregateId = aggregateId, + EventType = CohortNotificationEvent, + EventVersion = 1, + PayloadJson = JsonSerializer.Serialize(new + { + Notifications = list.Select(x => new { x.UserId, x.Title, x.Message, x.Type, x.LinkUrl }), + }), + CreatedAtUtc = DateTime.UtcNow, + AvailableAtUtc = DateTime.UtcNow, + }); + } + + private async Task CurrentPolicyAsync(CancellationToken ct) + { + if (groupPolicies is null) + return new MentorGroupPolicy { Version = 0 }; + var effective = await groupPolicies.GetEffectiveAsync(DateTime.UtcNow, ct); + Rule(effective is not null, "GROUP_POLICY_UNAVAILABLE", + "Hệ thống chưa có chính sách lớp học nhóm đang có hiệu lực. Vui lòng liên hệ Quản trị viên.", + HttpStatusCode.ServiceUnavailable); + return effective!; + } + + private IQueryable CohortWithSchedulingDetails => uow.StudyCohorts.Query() + .Include(x => x.Plan).ThenInclude(x => x.CertificateLevel) + .Include(x => x.Mentor) + .Include(x => x.Sessions).ThenInclude(x => x.Availability).ThenInclude(x => x.GroupPolicy) + .Include(x => x.Enrollments).AsSplitQuery(); +} diff --git a/RikiPath.Domain/AppSettings.cs b/RikiPath.Domain/AppSettings.cs index 3fa072a..f0c4e19 100644 --- a/RikiPath.Domain/AppSettings.cs +++ b/RikiPath.Domain/AppSettings.cs @@ -21,7 +21,6 @@ public class AppSettings public GoogleAuthSettings Google { get; set; } = new(); public AzureSpeechSettings AzureSpeechSettings { get; set; } = new(); public QaPaymentSimulatorSettings QaPaymentSimulator { get; set; } = new(); - public GroupLearningSettings GroupLearning { get; set; } = new(); public EmailVerificationSettings EmailVerification { get; set; } = new(); } @@ -32,14 +31,6 @@ public sealed class EmailVerificationSettings public int MaxResendsPerHour { get; set; } = 5; } - public sealed class GroupLearningSettings - { - /// - /// Cổng an toàn: chuyển lớp sau khai giảng chỉ được bật khi Product Owner đã phê duyệt quyền lợi - /// (buổi đã học, hoàn/thu chênh lệch). Mặc định TẮT. - /// - public bool PostStartTransferProductApproved { get; set; } - } public class GoogleAuthSettings { public string? ClientId { get; set; } diff --git a/RikiPath.Domain/CourseRetakePolicy.cs b/RikiPath.Domain/CourseRetakePolicy.cs index 5dd19fa..f678707 100644 --- a/RikiPath.Domain/CourseRetakePolicy.cs +++ b/RikiPath.Domain/CourseRetakePolicy.cs @@ -2,55 +2,171 @@ namespace RikiPath.Domain; -public sealed record CourseEligibility(int RequiredHomework, int PassedOnTimeHomework, int CountedSessions, - int AttendedSessions, int AbsentSessions, bool HomeworkMet, bool AttendanceMet, bool CanClaim, string[] Reasons); +/// Criterion outcome of the JLPT retake-support check (Backend is the only source of truth). +public static class RetakeCriterionState +{ + public const string Met = "Met"; + public const string NotMet = "NotMet"; + /// Not enough recorded data (no homework assigned, attendance not fully marked) — never a "not met". + public const string Undetermined = "Undetermined"; +} + +/// Overall retake-support status shown to Learner, Mentor and Admin. +public static class RetakeEligibilityStatus +{ + public const string CourseNotCompleted = "CourseNotCompleted"; + public const string PolicyDisabled = "PolicyDisabled"; + public const string Undetermined = "Undetermined"; + public const string NotMet = "NotMet"; + public const string Eligible = "Eligible"; + public const string RetakeCourse = "RetakeCourse"; +} + +/// +/// Single result shape for retake-support eligibility. The first nine members keep their historical meaning so stored +/// EligibilitySnapshot JSON and older readers stay valid; the rest describe the exact policy used. +/// +public sealed record CourseEligibility( + int RequiredHomework, + int PassedOnTimeHomework, + int CountedSessions, + int AttendedSessions, + int AbsentSessions, + bool HomeworkMet, + bool AttendanceMet, + bool CanClaim, + string[] Reasons, + string Status, + string HomeworkState, + string AttendanceState, + decimal? HomeworkRatePercent, + decimal? AttendanceRatePercent, + int ValidSessions, + int UnmarkedSessions, + decimal HomeworkThresholdPercent, + decimal AttendanceThresholdPercent, + string ThresholdComparison, + bool SupportEnabled, + int? PolicyId, + int? PolicyVersion, + bool CourseCompleted, + DateTime EvaluatedAtUtc); public static class CourseRetakePolicy { + /// Only comparison used for retake support: the rate must be at least the configured threshold. + public const string Comparison = ">="; + + private static readonly HashSet NonRequiredSessionStatuses = new(StringComparer.Ordinal) + { + "CancelledByMentor", "CancelledByLearner", "Cancelled", "TransferredOut", "Rescheduled", + }; + + /// Exact check without rounding: numerator / denominator × 100 ≥ threshold. + public static bool MeetsThreshold(int numerator, int denominator, decimal thresholdPercent) + => denominator > 0 && (decimal)numerator * 100m >= (decimal)denominator * thresholdPercent; + public static CourseEligibility Evaluate( StudyCourse course, bool alreadyRetaken, MentorGroupPolicy? policy = null, - IReadOnlyCollection? cohortAssignments = null) + IReadOnlyCollection? cohortAssignments = null, + DateTime? nowUtc = null) { - var required = course.Homework.Where(x => x.Required).ToList(); - var requiredCount = required.Count; - var passed = required.Count(x => x.SubmittedAt.HasValue && x.SubmittedAt <= x.DueAt); + var effectivePolicy = policy ?? course.GroupPolicy; + var homeworkThreshold = effectivePolicy?.RemediationCompletionThresholdPercent + ?? (course.MinimumHomeworkPercent > 0m ? course.MinimumHomeworkPercent : MentorGroupPolicy.DefaultRetakeHomeworkThresholdPercent); + var attendanceThreshold = effectivePolicy?.RemediationAttendanceThresholdPercent + ?? MentorGroupPolicy.DefaultRetakeAttendanceThresholdPercent; + var supportEnabled = effectivePolicy?.RetakeSupportEnabled ?? true; + // Homework: valid on-time submissions / homework assigned to this enrollment (quizzes are separate entities). + var legacyRequired = course.Homework.Where(x => x.Required).ToList(); + var requiredCount = legacyRequired.Count; + var passed = legacyRequired.Count(x => x.SubmittedAt.HasValue && x.SubmittedAt <= x.DueAt); if (cohortAssignments is { Count: > 0 }) { - var scopedAssignments = cohortAssignments - .Where(a => !a.IsDeleted && a.StudyCourseId == course.Id) - .ToList(); - requiredCount += scopedAssignments.Count; - passed += scopedAssignments.Count(a => a.Submission is { IsDeleted: false } sub + var scoped = cohortAssignments.Where(a => !a.IsDeleted && a.StudyCourseId == course.Id).ToList(); + requiredCount += scoped.Count; + passed += scoped.Count(a => a.Submission is { IsDeleted: false } sub && (!a.DueAt.HasValue || sub.SubmittedAt <= a.DueAt.Value)); } - var logicalSessions = course.Sessions.GroupBy(x => x.Number).ToList(); - var counted = logicalSessions.Count(g => g.Any(x => x.Status is "Present" or "Absent" or "ExcusedAbsent")); - var attended = logicalSessions.Count(g => g.Any(x => x.Status == "Present")); - var absent = counted - attended; + var homeworkState = requiredCount == 0 + ? RetakeCriterionState.Undetermined + : MeetsThreshold(passed, requiredCount, homeworkThreshold) ? RetakeCriterionState.Met : RetakeCriterionState.NotMet; + + // Attendance: present / required class sessions; latest attempt per logical session; cancelled or moved slots excluded. + var logical = course.Sessions + .GroupBy(x => x.Number) + .Select(g => g.OrderByDescending(x => x.Attempt).First()) + .Where(s => !NonRequiredSessionStatuses.Contains(s.Status)) + .ToList(); + var validSessions = logical.Count; + var attended = logical.Count(s => s.Status is "Present" or "Completed"); + var absent = logical.Count(s => s.Status is "Absent" or "ExcusedAbsent"); + var counted = attended + absent; + var unmarked = validSessions - counted; + string attendanceState; + if (validSessions == 0) attendanceState = RetakeCriterionState.Undetermined; + else if (MeetsThreshold(attended, validSessions, attendanceThreshold)) attendanceState = RetakeCriterionState.Met; + else if (unmarked > 0) attendanceState = RetakeCriterionState.Undetermined; // Missing marks are never absences. + else attendanceState = RetakeCriterionState.NotMet; + + var courseCompleted = course.Status == "Completed" + && course.PaymentStatus is "Paid" or "PartiallyRefunded"; + var homeworkMet = homeworkState == RetakeCriterionState.Met; + var attendanceMet = attendanceState == RetakeCriterionState.Met; - var effectivePolicy = policy ?? course.GroupPolicy; - var thresholdPercent = effectivePolicy?.RemediationCompletionThresholdPercent ?? course.MinimumHomeworkPercent; - var strictGreater = string.Equals(effectivePolicy?.RemediationThresholdComparison, ">", StringComparison.Ordinal); - var homeworkMet = requiredCount > 0 && (strictGreater - ? (decimal)passed * 100m > (decimal)requiredCount * thresholdPercent - : (decimal)passed * 100m >= (decimal)requiredCount * thresholdPercent); - var attendanceMet = true; // Absence is not an eligibility condition. var reasons = new List(); - if (course.RetakeOfId.HasValue) reasons.Add("Khóa học lại không phát sinh quyền học lại tiếp."); - if (course.PaymentStatus is not ("Paid" or "PartiallyRefunded") || course.Status != "Completed") reasons.Add("Khóa phải đã thanh toán và hoàn thành."); - if (alreadyRetaken) reasons.Add("Khóa gốc đã sử dụng quyền học lại."); - if (!homeworkMet) + string status; + if (course.RetakeOfId.HasValue) + { + status = RetakeEligibilityStatus.RetakeCourse; + reasons.Add("Khóa học lại không phát sinh quyền hỗ trợ ôn lại tiếp."); + } + else if (!courseCompleted) + { + status = RetakeEligibilityStatus.CourseNotCompleted; + reasons.Add("Khóa học cần được hoàn thành trước khi xét hỗ trợ ôn lại JLPT."); + } + else if (!supportEnabled) + { + status = RetakeEligibilityStatus.PolicyDisabled; + reasons.Add("Chính sách lớp học áp dụng cho bạn không bao gồm hỗ trợ ôn lại JLPT."); + } + else if (homeworkState == RetakeCriterionState.NotMet || attendanceState == RetakeCriterionState.NotMet) + { + status = RetakeEligibilityStatus.NotMet; + if (homeworkState == RetakeCriterionState.NotMet) + reasons.Add($"Hoàn thành bài tập chưa đạt ≥ {homeworkThreshold:0.##}%."); + if (attendanceState == RetakeCriterionState.NotMet) + reasons.Add($"Chuyên cần chưa đạt ≥ {attendanceThreshold:0.##}%."); + } + else if (homeworkState == RetakeCriterionState.Undetermined || attendanceState == RetakeCriterionState.Undetermined) { - var op = strictGreater ? ">" : ">="; - reasons.Add($"Chưa có đủ dữ liệu xác nhận {op} {thresholdPercent:0.##}% bài tập về nhà nộp đúng hạn; chờ Quản trị viên kiểm tra minh chứng."); + status = RetakeEligibilityStatus.Undetermined; + reasons.Add("Chưa thể xác định điều kiện vì dữ liệu bài tập hoặc điểm danh chưa được ghi nhận đầy đủ."); } + else + { + status = RetakeEligibilityStatus.Eligible; + } + + if (alreadyRetaken) + reasons.Add("Khóa học đã sử dụng quyền học lại trước đây."); - if (logicalSessions.Count != course.TotalSessions || course.Sessions.Any(x => x.Status == "Scheduled")) - reasons.Add("Chưa chốt toàn bộ buổi học của khóa."); - return new(requiredCount, passed, counted, attended, absent, homeworkMet, attendanceMet, reasons.Count == 0, reasons.ToArray()); + return new CourseEligibility( + requiredCount, passed, counted, attended, absent, + homeworkMet, attendanceMet, + status == RetakeEligibilityStatus.Eligible && !alreadyRetaken, + reasons.ToArray(), + status, homeworkState, attendanceState, + requiredCount > 0 ? Math.Round((decimal)passed * 100m / requiredCount, 2) : null, + validSessions > 0 ? Math.Round((decimal)attended * 100m / validSessions, 2) : null, + validSessions, unmarked, + homeworkThreshold, attendanceThreshold, Comparison, + supportEnabled, effectivePolicy?.Id, effectivePolicy?.Version, + courseCompleted, nowUtc ?? DateTime.UtcNow); } } diff --git a/RikiPath.Domain/Entities/ClassQuiz.cs b/RikiPath.Domain/Entities/ClassQuiz.cs new file mode 100644 index 0000000..0eca130 --- /dev/null +++ b/RikiPath.Domain/Entities/ClassQuiz.cs @@ -0,0 +1,51 @@ +namespace RikiPath.Domain.Entities; + +/// +/// In-class skill quiz a Mentor gives to a class (Stage 5). Auto-graded, reported on 0–100% per skill. +/// The question set is frozen in when the quiz is published, so later +/// question-bank edits never change attempts already started or submitted. Separate from Homework and +/// from the end-of-course assessment. +/// +public sealed class ClassQuiz +{ + public int Id { get; set; } + public int CohortId { get; set; } + public StudyCohort Cohort { get; set; } = null!; + public int MentorId { get; set; } + public UserAccount Mentor { get; set; } = null!; + public int CertificateLevelId { get; set; } + public CertificateLevel CertificateLevel { get; set; } = null!; + public string Title { get; set; } = string.Empty; + public int TimeLimitMinutes { get; set; } + public DateTime DueAtUtc { get; set; } + /// Comma-separated assessed skill codes in canonical order (vocabulary,grammar,reading,listening). + public string SkillCodes { get; set; } = string.Empty; + public int QuestionCount { get; set; } + /// Frozen question version incl. answer key (never sent to learners before results are released). + public string QuestionSnapshotJson { get; set; } = string.Empty; + /// Questions per skill, e.g. "grammar:10,listening:4,reading:10,vocabulary:10"; quizzes with the same level + /// and structure are treated as comparable for in-course skill tracking. + public string StructureKey { get; set; } = string.Empty; + public string Status { get; set; } = "Published"; + public DateTime PublishedAtUtc { get; set; } + public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow; + public bool IsDeleted { get; set; } + public int Revision { get; set; } = 1; + public List Assignments { get; set; } = []; +} + +/// One learner (class enrollment) who must take a ; one attempt per assignment. +public sealed class ClassQuizAssignment +{ + public int Id { get; set; } + public int QuizId { get; set; } + public ClassQuiz Quiz { get; set; } = null!; + public int LearnerId { get; set; } + public UserAccount Learner { get; set; } = null!; + public int EnrollmentId { get; set; } + public StudyCourse Enrollment { get; set; } = null!; + public int? AttemptId { get; set; } + public MockTestAttempt? Attempt { get; set; } + public DateTime AssignedAtUtc { get; set; } + public DateTime? CompletedAtUtc { get; set; } +} diff --git a/RikiPath.Domain/Entities/MentorGroupPolicy.cs b/RikiPath.Domain/Entities/MentorGroupPolicy.cs index 3ba1e16..7431e03 100644 --- a/RikiPath.Domain/Entities/MentorGroupPolicy.cs +++ b/RikiPath.Domain/Entities/MentorGroupPolicy.cs @@ -37,12 +37,21 @@ public sealed class MentorGroupPolicy // Nhóm E — Đào tạo & đánh giá public int HomeworkDeadlineDays { get; set; } = 7; public int PlacementAttemptLimit { get; set; } = 2; - public decimal RemediationCompletionThresholdPercent { get; set; } = 90m; - public string RemediationThresholdComparison { get; set; } = ">"; + public decimal RemediationCompletionThresholdPercent { get; set; } = DefaultRetakeHomeworkThresholdPercent; + /// Historical operator kept for audit only; retake support is always evaluated with ">=" (CourseRetakePolicy). + public string RemediationThresholdComparison { get; set; } = ">="; public bool RequireOfficialExamEvidence { get; set; } = true; public bool RequireAdminRemediationReview { get; set; } = true; public int KpiReportingPeriodDays { get; set; } = 30; + // Nhóm F — Hỗ trợ ôn lại JLPT + public bool RetakeSupportEnabled { get; set; } = true; + public decimal RemediationAttendanceThresholdPercent { get; set; } = DefaultRetakeAttendanceThresholdPercent; + + /// Central defaults for a new policy version (the only place the 90% default lives). + public const decimal DefaultRetakeHomeworkThresholdPercent = 90m; + public const decimal DefaultRetakeAttendanceThresholdPercent = 90m; + // Đơn giá học phí trên mỗi học viên cho mỗi buổi học (VND) theo cấp độ JLPT N5–N2. public decimal TuitionPerSessionN5 { get; set; } = 60_000m; public decimal TuitionPerSessionN4 { get; set; } = 75_000m; diff --git a/RikiPath.Domain/Entities/MentorKpiPolicy.cs b/RikiPath.Domain/Entities/MentorKpiPolicy.cs new file mode 100644 index 0000000..fa33fd3 --- /dev/null +++ b/RikiPath.Domain/Entities/MentorKpiPolicy.cs @@ -0,0 +1,79 @@ +namespace RikiPath.Domain.Entities; + +/// +/// Chính sách chấm công & KPI Giáo viên (độc lập với Chính sách lớp học). Mỗi phiên bản đã ban hành là bất biến và +/// có hiệu lực từ ngày đầu của một tháng dương lịch; tháng báo cáo dùng phiên bản mới nhất có hiệu lực tại tháng đó. +/// Không chứa lương, thưởng, phạt hay trọng số KPI. +/// +public sealed class MentorKpiPolicy +{ + // Baseline cho phiên bản khởi tạo — nơi duy nhất chứa giá trị mặc định. + public const decimal DefaultMinimumPresencePercent = 80m; + public const decimal DefaultTeachingCompletionTargetPercent = 90m; + public const int DefaultHomeworkMinimumCount = 1; + public const int DefaultHomeworkPerSessionCount = 2; + public const decimal DefaultGradingCompletionTargetPercent = 90m; + public const int DefaultResponseSlaHours = 24; + public const decimal DefaultOnTimeResponseTargetPercent = 90m; + public const decimal DefaultAverageRatingTarget = 4m; + public const decimal DefaultPositiveReviewTargetPercent = 80m; + + /// Đánh giá tích cực = 4–5 sao (định nghĩa nghiệp vụ thống nhất, không phải tham số cấu hình). + public const int PositiveRatingMinimum = 4; + + public int Id { get; set; } + public int Version { get; set; } + + /// Ngày đầu tháng (giờ nghiệp vụ Việt Nam) bắt đầu có hiệu lực. + public DateOnly EffectiveFromMonth { get; set; } + + // A — Chấm công giảng dạy + public decimal MinimumPresencePercent { get; set; } = DefaultMinimumPresencePercent; + public decimal TeachingCompletionTargetPercent { get; set; } = DefaultTeachingCompletionTargetPercent; + + // B — Giao bài & chấm bài + public int HomeworkMinimumCount { get; set; } = DefaultHomeworkMinimumCount; + public int HomeworkPerSessionCount { get; set; } = DefaultHomeworkPerSessionCount; + public decimal GradingCompletionTargetPercent { get; set; } = DefaultGradingCompletionTargetPercent; + + // C — Tốc độ phản hồi + public int ResponseSlaHours { get; set; } = DefaultResponseSlaHours; + public decimal OnTimeResponseTargetPercent { get; set; } = DefaultOnTimeResponseTargetPercent; + + // D — Đánh giá học viên + public decimal AverageRatingTarget { get; set; } = DefaultAverageRatingTarget; + public decimal PositiveReviewTargetPercent { get; set; } = DefaultPositiveReviewTargetPercent; + + public string? Note { get; set; } + public int? CreatedByAdminId { get; set; } + public DateTime CreatedAtUtc { get; set; } + public bool IsDeleted { get; set; } + public DateTime? DeletedAtUtc { get; set; } + public int? DeletedByAdminId { get; set; } + + [System.Text.Json.Serialization.JsonIgnore] + public UserAccount? CreatedByAdmin { get; set; } +} + +/// +/// Lịch sử đối soát chấm công của Quản trị viên cho một buổi học của lớp. Không sửa dữ liệu gốc (buổi học, điểm danh, +/// Meeting Room); bản ghi mới nhất của buổi là kết quả đối soát đang áp dụng. +/// +public sealed class MentorTimesheetAdjustment +{ + public const string StatusTaught = "Taught"; + public const string StatusAbsent = "Absent"; + + public long Id { get; set; } + public int CohortSessionId { get; set; } + public StudyCohortSession CohortSession { get; set; } = null!; + public int MentorId { get; set; } + public string PreviousStatus { get; set; } = string.Empty; + public string NewStatus { get; set; } = string.Empty; + public int PreviousConfirmedMinutes { get; set; } + public int NewConfirmedMinutes { get; set; } + public string Reason { get; set; } = string.Empty; + public string? Evidence { get; set; } + public int AdminId { get; set; } + public DateTime CreatedAtUtc { get; set; } +} diff --git a/RikiPath.Domain/Enums/AttemptKind.cs b/RikiPath.Domain/Enums/AttemptKind.cs index 67dce0e..ddc3080 100644 --- a/RikiPath.Domain/Enums/AttemptKind.cs +++ b/RikiPath.Domain/Enums/AttemptKind.cs @@ -3,6 +3,12 @@ namespace RikiPath.Domain.Enums public enum AttemptKind { MockTest = 0, - Placement = 1 + Placement = 1, + /// + /// Competency assessment bound to one class enrollment (same engine and scale as Placement). + /// The snapshot Purpose tells it apart: "CourseBaseline" (pre-course result pinned to the class) + /// or "CourseFinal" (end-of-course assessment). Never part of the learner's global Placement history. + /// + CourseAssessment = 2 } } diff --git a/RikiPath.Domain/Enums/ImportEntityType.cs b/RikiPath.Domain/Enums/ImportEntityType.cs index 8a61cac..9e03ce5 100644 --- a/RikiPath.Domain/Enums/ImportEntityType.cs +++ b/RikiPath.Domain/Enums/ImportEntityType.cs @@ -12,5 +12,6 @@ public enum ImportEntityType QuestionBank, PracticeSet, Passage, + SrsCardTemplate, } } diff --git a/RikiPath.Infrastructure/AppDbContext.cs b/RikiPath.Infrastructure/AppDbContext.cs index ba0c851..04b46d8 100644 --- a/RikiPath.Infrastructure/AppDbContext.cs +++ b/RikiPath.Infrastructure/AppDbContext.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; using RikiPath.Infrastructure.Configuration; namespace RikiPath.Infrastructure @@ -10,6 +11,8 @@ public class AppDbContext(DbContextOptions options) : DbContext(op public DbSet StudyCourses { get; set; } public DbSet StudyCoursePlans { get; set; } public DbSet StudyCohorts { get; set; } + public DbSet ClassQuizzes { get; set; } + public DbSet ClassQuizAssignments { get; set; } public DbSet CohortEnrollmentEntitlements { get; set; } public DbSet CourseScheduleRequests { get; set; } public DbSet CohortTransferRequests { get; set; } @@ -86,6 +89,8 @@ public class AppDbContext(DbContextOptions options) : DbContext(op public DbSet MentorSchedules { get; set; } public DbSet MentorScheduleRules { get; set; } public DbSet MentorGroupPolicies { get; set; } + public DbSet MentorKpiPolicies { get; set; } + public DbSet MentorTimesheetAdjustments { get; set; } public DbSet MentorBookingIntents { get; set; } public DbSet MentorBookingTerms { get; set; } public DbSet MentorBookingReservations { get; set; } @@ -146,6 +151,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new MentorWeeklyAvailabilityConfig()); modelBuilder.ApplyConfiguration(new UserConfig()); + modelBuilder.ApplyConfiguration(new ClassQuizConfig()); + modelBuilder.ApplyConfiguration(new MentorKpiPolicyConfig()); + modelBuilder.ApplyConfiguration(new MentorTimesheetAdjustmentConfig()); + modelBuilder.ApplyConfiguration(new ClassQuizAssignmentConfig()); modelBuilder.ApplyConfiguration(new CertificateTypeConfig()); modelBuilder.ApplyConfiguration(new CertificateLevelConfig()); modelBuilder.ApplyConfiguration(new LanguageSkillConfig()); @@ -279,5 +288,102 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new AdminAuditLogConfig()); modelBuilder.ApplyConfiguration(new LearnerFeedbackConfig()); } + + public override int SaveChanges(bool acceptAllChangesOnSuccess) + { + SyncLegacyMockShadowProperties(); + return base.SaveChanges(acceptAllChangesOnSuccess); + } + + public override Task SaveChangesAsync( + bool acceptAllChangesOnSuccess, + CancellationToken cancellationToken = default) + { + SyncLegacyMockShadowProperties(); + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); + } + + private void SyncLegacyMockShadowProperties() + { + ChangeTracker.DetectChanges(); + + var nowUnspecified = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified); + + var trackedTests = ChangeTracker.Entries() + .Select(e => e.Entity) + .ToList(); + var testsById = trackedTests + .Where(t => t.Id > 0) + .ToDictionary(t => t.Id); + + var trackedSections = ChangeTracker.Entries() + .Select(e => e.Entity) + .ToList(); + var sectionsById = trackedSections + .Where(s => s.Id > 0) + .ToDictionary(s => s.Id); + + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State is not (EntityState.Added or EntityState.Modified)) + continue; + + var publishStatusProp = entry.Property("PublishStatus"); + if (publishStatusProp.CurrentValue == 0) + publishStatusProp.CurrentValue = (int)ContentStatus.Published; + + var publishedAtProp = entry.Property("PublishedAt"); + publishedAtProp.CurrentValue ??= nowUnspecified; + } + + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State is not (EntityState.Added or EntityState.Modified)) + continue; + + var publishStatusProp = entry.Property("PublishStatus"); + if (publishStatusProp.CurrentValue == 0) + publishStatusProp.CurrentValue = (int)ContentStatus.Published; + + var publishedAtProp = entry.Property("PublishedAt"); + publishedAtProp.CurrentValue ??= nowUnspecified; + } + + foreach (var entry in ChangeTracker.Entries()) + { + if (entry.State is not (EntityState.Added or EntityState.Modified)) + continue; + + var question = entry.Entity; + var section = question.MockTestSection + ?? (question.MockTestSectionId is int secId && sectionsById.TryGetValue(secId, out var secById) + ? secById + : null) + ?? trackedSections.FirstOrDefault(s => s.Questions?.Contains(question) == true); + + var mockTest = section?.MockTest + ?? (section is not null && section.MockTestId > 0 && testsById.TryGetValue(section.MockTestId, out var testById) + ? testById + : null) + ?? (section is not null + ? trackedTests.FirstOrDefault(t => t.Sections?.Contains(section) == true) + : null); + + var skillProp = entry.Property("LanguageSkillId"); + if (skillProp.CurrentValue <= 0 && section is not null && section.LanguageSkillId > 0) + skillProp.CurrentValue = section.LanguageSkillId; + + var levelProp = entry.Property("CertificateLevelId"); + if (levelProp.CurrentValue <= 0 && mockTest is not null && mockTest.CertificateLevelId > 0) + levelProp.CurrentValue = mockTest.CertificateLevelId; + + var publishStatusProp = entry.Property("PublishStatus"); + if (publishStatusProp.CurrentValue == 0) + publishStatusProp.CurrentValue = (int)ContentStatus.Published; + + var publishedAtProp = entry.Property("PublishedAt"); + publishedAtProp.CurrentValue ??= nowUnspecified; + } + } } } diff --git a/RikiPath.Infrastructure/Configuration/ClassQuizConfig.cs b/RikiPath.Infrastructure/Configuration/ClassQuizConfig.cs new file mode 100644 index 0000000..dc16475 --- /dev/null +++ b/RikiPath.Infrastructure/Configuration/ClassQuizConfig.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using RikiPath.Domain.Entities; + +namespace RikiPath.Infrastructure.Configuration; + +public sealed class ClassQuizConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("ClassQuizzes", t => + { + t.HasCheckConstraint("CK_ClassQuiz_TimeLimit", "\"TimeLimitMinutes\" BETWEEN 1 AND 240"); + t.HasCheckConstraint("CK_ClassQuiz_QuestionCount", "\"QuestionCount\" BETWEEN 1 AND 200"); + t.HasCheckConstraint("CK_ClassQuiz_Status", "\"Status\" IN ('Published','Cancelled')"); + }); + b.HasKey(x => x.Id); + b.Property(x => x.Title).HasMaxLength(200).IsRequired(); + b.Property(x => x.SkillCodes).HasMaxLength(100).IsRequired(); + b.Property(x => x.StructureKey).HasMaxLength(200).IsRequired(); + b.Property(x => x.Status).HasMaxLength(20).IsRequired(); + b.Property(x => x.QuestionSnapshotJson).HasColumnType("text").IsRequired(); + b.Property(x => x.DueAtUtc).HasColumnType("timestamp with time zone"); + b.Property(x => x.PublishedAtUtc).HasColumnType("timestamp with time zone"); + b.Property(x => x.CreatedAtUtc).HasColumnType("timestamp with time zone"); + b.Property(x => x.Revision).IsConcurrencyToken(); + b.HasIndex(x => new { x.CohortId, x.IsDeleted, x.DueAtUtc }); + b.HasOne(x => x.Cohort).WithMany().HasForeignKey(x => x.CohortId).OnDelete(DeleteBehavior.Restrict); + b.HasOne(x => x.Mentor).WithMany().HasForeignKey(x => x.MentorId).OnDelete(DeleteBehavior.Restrict); + b.HasOne(x => x.CertificateLevel).WithMany().HasForeignKey(x => x.CertificateLevelId).OnDelete(DeleteBehavior.Restrict); + } +} + +public sealed class ClassQuizAssignmentConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("ClassQuizAssignments"); + b.HasKey(x => x.Id); + b.Property(x => x.AssignedAtUtc).HasColumnType("timestamp with time zone"); + b.Property(x => x.CompletedAtUtc).HasColumnType("timestamp with time zone"); + b.HasIndex(x => new { x.QuizId, x.LearnerId }).IsUnique(); + b.HasIndex(x => new { x.LearnerId, x.EnrollmentId }); + b.HasIndex(x => x.AttemptId).IsUnique().HasFilter("\"AttemptId\" IS NOT NULL"); + b.HasOne(x => x.Quiz).WithMany(x => x.Assignments).HasForeignKey(x => x.QuizId).OnDelete(DeleteBehavior.Cascade); + b.HasOne(x => x.Learner).WithMany().HasForeignKey(x => x.LearnerId).OnDelete(DeleteBehavior.Restrict); + b.HasOne(x => x.Enrollment).WithMany().HasForeignKey(x => x.EnrollmentId).OnDelete(DeleteBehavior.Restrict); + b.HasOne(x => x.Attempt).WithMany().HasForeignKey(x => x.AttemptId).OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/RikiPath.Infrastructure/Configuration/MentorGroupPolicyConfig.cs b/RikiPath.Infrastructure/Configuration/MentorGroupPolicyConfig.cs index 0b34df7..f73ba8a 100644 --- a/RikiPath.Infrastructure/Configuration/MentorGroupPolicyConfig.cs +++ b/RikiPath.Infrastructure/Configuration/MentorGroupPolicyConfig.cs @@ -13,6 +13,7 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_MentorGroupPolicy_Capacity", "\"MaxLearners\" BETWEEN 1 AND 50"); t.HasCheckConstraint("CK_MentorGroupPolicy_Positive", "\"Version\" > 0 AND \"SessionMinutes\" > 0 AND \"RestMinutes\" >= 0 AND \"MinimumPreparationDays\" >= 1 AND \"CancellationLeadHours\" >= 0 AND \"ReschedulingLeadHours\" >= 0 AND \"HomeworkDeadlineDays\" > 0 AND \"PlacementAttemptLimit\" > 0 AND \"KpiReportingPeriodDays\" > 0"); t.HasCheckConstraint("CK_MentorGroupPolicy_Remediation", "\"RemediationCompletionThresholdPercent\" > 0 AND \"RemediationCompletionThresholdPercent\" <= 100"); + t.HasCheckConstraint("CK_MentorGroupPolicy_RemediationAttendance", "\"RemediationAttendanceThresholdPercent\" > 0 AND \"RemediationAttendanceThresholdPercent\" <= 100"); t.HasCheckConstraint("CK_MentorGroupPolicy_Evidence", "\"RequireOfficialExamEvidence\" AND \"RequireAdminRemediationReview\""); t.HasCheckConstraint("CK_MentorGroupPolicy_Comparison", "\"RemediationThresholdComparison\" IN ('>', '>=')"); t.HasCheckConstraint("CK_MentorGroupPolicy_ReplacementLead", "\"MentorReplacementLeadHours\" BETWEEN 0 AND 720"); @@ -40,6 +41,9 @@ public void Configure(EntityTypeBuilder b) b.Property(x => x.DeletedAtUtc).HasColumnType("timestamp with time zone"); b.Property(x => x.RemediationThresholdComparison).HasMaxLength(2).IsRequired(); b.Property(x => x.RemediationCompletionThresholdPercent).HasPrecision(5, 2); + b.Property(x => x.RemediationAttendanceThresholdPercent).HasPrecision(5, 2) + .HasDefaultValue(MentorGroupPolicy.DefaultRetakeAttendanceThresholdPercent); + b.Property(x => x.RetakeSupportEnabled).HasDefaultValue(true); b.Property(x => x.TuitionPerSessionN5).HasPrecision(18, 0); b.Property(x => x.TuitionPerSessionN4).HasPrecision(18, 0); b.Property(x => x.TuitionPerSessionN3).HasPrecision(18, 0); diff --git a/RikiPath.Infrastructure/Configuration/MentorKpiPolicyConfig.cs b/RikiPath.Infrastructure/Configuration/MentorKpiPolicyConfig.cs new file mode 100644 index 0000000..c99a0dd --- /dev/null +++ b/RikiPath.Infrastructure/Configuration/MentorKpiPolicyConfig.cs @@ -0,0 +1,69 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using RikiPath.Domain.Entities; + +namespace RikiPath.Infrastructure.Configuration; + +public sealed class MentorKpiPolicyConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("MentorKpiPolicies", t => + { + t.HasCheckConstraint("CK_MentorKpiPolicy_Percents", + "\"MinimumPresencePercent\" > 0 AND \"MinimumPresencePercent\" <= 100" + + " AND \"TeachingCompletionTargetPercent\" > 0 AND \"TeachingCompletionTargetPercent\" <= 100" + + " AND \"GradingCompletionTargetPercent\" > 0 AND \"GradingCompletionTargetPercent\" <= 100" + + " AND \"OnTimeResponseTargetPercent\" > 0 AND \"OnTimeResponseTargetPercent\" <= 100" + + " AND \"PositiveReviewTargetPercent\" > 0 AND \"PositiveReviewTargetPercent\" <= 100"); + t.HasCheckConstraint("CK_MentorKpiPolicy_Homework", "\"HomeworkMinimumCount\" >= 0 AND \"HomeworkPerSessionCount\" > 0"); + t.HasCheckConstraint("CK_MentorKpiPolicy_Sla", "\"ResponseSlaHours\" > 0"); + t.HasCheckConstraint("CK_MentorKpiPolicy_Rating", "\"AverageRatingTarget\" >= 1 AND \"AverageRatingTarget\" <= 5"); + t.HasCheckConstraint("CK_MentorKpiPolicy_Month", "EXTRACT(DAY FROM \"EffectiveFromMonth\") = 1"); + }); + b.HasKey(x => x.Id); + b.HasIndex(x => x.Version).IsUnique(); + b.HasIndex(x => x.EffectiveFromMonth).IsUnique().HasFilter("\"IsDeleted\" = FALSE"); + b.Property(x => x.MinimumPresencePercent).HasPrecision(5, 2); + b.Property(x => x.TeachingCompletionTargetPercent).HasPrecision(5, 2); + b.Property(x => x.GradingCompletionTargetPercent).HasPrecision(5, 2); + b.Property(x => x.OnTimeResponseTargetPercent).HasPrecision(5, 2); + b.Property(x => x.PositiveReviewTargetPercent).HasPrecision(5, 2); + b.Property(x => x.AverageRatingTarget).HasPrecision(3, 2); + b.Property(x => x.Note).HasMaxLength(500); + b.Property(x => x.CreatedAtUtc).HasColumnType("timestamp with time zone"); + b.Property(x => x.DeletedAtUtc).HasColumnType("timestamp with time zone"); + b.HasOne(x => x.CreatedByAdmin).WithMany().HasForeignKey(x => x.CreatedByAdminId).OnDelete(DeleteBehavior.Restrict); + + // Phiên bản khởi tạo (baseline) — hiệu lực từ đầu năm 2026. + b.HasData(new MentorKpiPolicy + { + Id = 1, + Version = 1, + EffectiveFromMonth = new DateOnly(2026, 1, 1), + Note = "Phiên bản khởi tạo", + CreatedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), + }); + } +} + +public sealed class MentorTimesheetAdjustmentConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("MentorTimesheetAdjustments", t => + { + t.HasCheckConstraint("CK_MentorTimesheetAdjustment_Minutes", "\"NewConfirmedMinutes\" >= 0 AND \"PreviousConfirmedMinutes\" >= 0"); + t.HasCheckConstraint("CK_MentorTimesheetAdjustment_Status", "\"NewStatus\" IN ('Taught', 'Absent')"); + }); + b.HasKey(x => x.Id); + b.HasIndex(x => new { x.CohortSessionId, x.CreatedAtUtc }); + b.HasIndex(x => x.MentorId); + b.Property(x => x.PreviousStatus).HasMaxLength(32).IsRequired(); + b.Property(x => x.NewStatus).HasMaxLength(32).IsRequired(); + b.Property(x => x.Reason).HasMaxLength(1000).IsRequired(); + b.Property(x => x.Evidence).HasMaxLength(1000); + b.Property(x => x.CreatedAtUtc).HasColumnType("timestamp with time zone"); + b.HasOne(x => x.CohortSession).WithMany().HasForeignKey(x => x.CohortSessionId).OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.Designer.cs b/RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.Designer.cs new file mode 100644 index 0000000..9c53d4c --- /dev/null +++ b/RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.Designer.cs @@ -0,0 +1,14429 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using RikiPath.Infrastructure; + +#nullable disable + +namespace RikiPath.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261201045335_AddClassQuizzes")] + partial class AddClassQuizzes + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("FeatureSubscriptionPlan", b => + { + b.Property("FeaturesId") + .HasColumnType("integer"); + + b.Property("SubscriptionPlansId") + .HasColumnType("integer"); + + b.HasKey("FeaturesId", "SubscriptionPlansId"); + + b.HasIndex("SubscriptionPlansId"); + + b.ToTable("FeatureSubscriptionPlan"); + + b.HasData( + new + { + FeaturesId = 1, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 7, + SubscriptionPlansId = 7 + }, + new + { + FeaturesId = 8, + SubscriptionPlansId = 7 + }, + new + { + FeaturesId = 13, + SubscriptionPlansId = 8101 + }, + new + { + FeaturesId = 14, + SubscriptionPlansId = 8102 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 8103 + }, + new + { + FeaturesId = 12, + SubscriptionPlansId = 8104 + }, + new + { + FeaturesId = 7, + SubscriptionPlansId = 8105 + }, + new + { + FeaturesId = 8, + SubscriptionPlansId = 8105 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AdminAuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ActorUserId") + .HasColumnType("integer"); + + b.Property("AfterJson") + .HasColumnType("text"); + + b.Property("BeforeJson") + .HasColumnType("text"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("EntityId") + .HasColumnType("integer"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("EntityType", "EntityId"); + + b.ToTable("AdminAuditLogs", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AiCreditTopUp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActivatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PaymentTransactionId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Quantity") + .HasColumnType("integer"); + + b.Property("TotalAmount") + .HasColumnType("decimal(18,2)"); + + b.Property("UnitPrice") + .HasColumnType("decimal(18,2)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "PaymentStatus"); + + b.ToTable("AiCreditTopUps"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateTypeId") + .HasColumnType("integer") + .HasColumnName("CertificationId"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateTypeId", "Code") + .IsUnique(); + + b.ToTable("CertificateLevels", null, t => + { + t.HasCheckConstraint("CK_CertificateLevels_SortOrder", "\"SortOrder\" >= 1"); + }); + + b.HasData( + new + { + Id = 1, + CertificateTypeId = 1, + Code = "N5", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N5", + IsDeleted = false, + Revision = 1, + SortOrder = 1 + }, + new + { + Id = 2, + CertificateTypeId = 1, + Code = "N4", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N4", + IsDeleted = false, + Revision = 1, + SortOrder = 2 + }, + new + { + Id = 3, + CertificateTypeId = 1, + Code = "N3", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N3", + IsDeleted = false, + Revision = 1, + SortOrder = 3 + }, + new + { + Id = 4, + CertificateTypeId = 1, + Code = "N2", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N2", + IsDeleted = false, + Revision = 1, + SortOrder = 4 + }, + new + { + Id = 5, + CertificateTypeId = 1, + Code = "N1", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N1", + IsDeleted = false, + Revision = 1, + SortOrder = 5 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DurationMinutes") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MaxScore") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PassingScore") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId", "Code") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.ToTable("CertificateSections"); + + b.HasData( + new + { + Id = 1, + CertificateLevelId = 1, + Code = "N5_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5285), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 1 + }, + new + { + Id = 2, + CertificateLevelId = 1, + Code = "N5_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5292), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 2 + }, + new + { + Id = 3, + CertificateLevelId = 1, + Code = "N5_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5294), + Description = "Phần thi nghe hiểu tình huống giao tiếp hàng ngày cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 4 + }, + new + { + Id = 16, + CertificateLevelId = 1, + Code = "N5_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5308), + Description = "Phần thi đọc hiểu văn bản, thông báo và đoạn hội thoại ngắn cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 3 + }, + new + { + Id = 4, + CertificateLevelId = 2, + Code = "N4_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5295), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 5, + CertificateLevelId = 2, + Code = "N4_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5296), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 6, + CertificateLevelId = 2, + Code = "N4_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5297), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 7, + CertificateLevelId = 2, + Code = "N4_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5298), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 8, + CertificateLevelId = 3, + Code = "N3_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5300), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 9, + CertificateLevelId = 3, + Code = "N3_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5301), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 10, + CertificateLevelId = 3, + Code = "N3_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5302), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 11, + CertificateLevelId = 3, + Code = "N3_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5303), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 12, + CertificateLevelId = 4, + Code = "N2_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5304), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 13, + CertificateLevelId = 4, + Code = "N2_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5305), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 14, + CertificateLevelId = 4, + Code = "N2_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5306), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 15, + CertificateLevelId = 4, + Code = "N2_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5307), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("CertificateTypes", null, t => + { + t.HasCheckConstraint("CK_CertificateTypes_SortOrder", "\"SortOrder\" >= 1"); + }); + + b.HasData( + new + { + Id = 1, + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese-Language Proficiency Test", + IsActive = true, + IsDeleted = false, + Name = "JLPT", + Revision = 1, + SortOrder = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DueAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PublishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("QuestionCount") + .HasColumnType("integer"); + + b.Property("QuestionSnapshotJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SkillCodes") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StructureKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("CohortId", "IsDeleted", "DueAtUtc"); + + b.ToTable("ClassQuizzes", null, t => + { + t.HasCheckConstraint("CK_ClassQuiz_QuestionCount", "\"QuestionCount\" BETWEEN 1 AND 200"); + + t.HasCheckConstraint("CK_ClassQuiz_Status", "\"Status\" IN ('Published','Cancelled')"); + + t.HasCheckConstraint("CK_ClassQuiz_TimeLimit", "\"TimeLimitMinutes\" BETWEEN 1 AND 240"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssignedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AttemptId") + .HasColumnType("integer"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("QuizId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AttemptId") + .IsUnique() + .HasFilter("\"AttemptId\" IS NOT NULL"); + + b.HasIndex("EnrollmentId"); + + b.HasIndex("LearnerId", "EnrollmentId"); + + b.HasIndex("QuizId", "LearnerId") + .IsUnique(); + + b.ToTable("ClassQuizAssignments", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Category") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecidedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecidedById") + .HasColumnType("integer"); + + b.Property("Decision") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorAccessGrantedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorDisclosure") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorEvidenceAllowed") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRespondedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorResponse") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RefundReviewRequested") + .HasColumnType("boolean"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Title") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CohortId"); + + b.HasIndex("CourseId"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("DecidedById"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.HasIndex("MentorId", "Status", "CreatedAtUtc"); + + b.ToTable("CohortComplaints", null, t => + { + t.HasCheckConstraint("CK_CohortComplaint_Category", "\"Category\" IN ('TeachingQuality', 'MentorConduct', 'Schedule', 'PaymentEnrollment', 'Other')"); + + t.HasCheckConstraint("CK_CohortComplaint_Decision", "(\"Status\" NOT IN ('Resolved', 'Rejected') OR (\"Decision\" IS NOT NULL AND length(btrim(\"Decision\")) > 0 AND \"DecidedById\" IS NOT NULL AND \"DecidedAtUtc\" IS NOT NULL))"); + + t.HasCheckConstraint("CK_CohortComplaint_Message", "length(btrim(\"Message\")) BETWEEN 10 AND 2000"); + + t.HasCheckConstraint("CK_CohortComplaint_RefundReview", "NOT \"RefundReviewRequested\" OR \"Category\" = 'PaymentEnrollment'"); + + t.HasCheckConstraint("CK_CohortComplaint_Status", "\"Status\" IN ('Open', 'UnderReview', 'NeedsInformation', 'Resolved', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaintEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ComplaintId") + .HasColumnType("integer"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("ComplaintId", "Id"); + + b.ToTable("CohortComplaintEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortEnrollmentEntitlement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ConsumedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ConsumedByCourseId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EntitlementReference") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("GrantedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("GrantedById") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("RevocationReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RevokedById") + .HasColumnType("integer"); + + b.Property("SourceType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("StudyCohortId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EntitlementReference") + .IsUnique(); + + b.HasIndex("LearnerId"); + + b.HasIndex("PlanId"); + + b.HasIndex("StudyCohortId", "LearnerId") + .IsUnique() + .HasFilter("\"Status\" = 'Active' AND \"IsDeleted\" = false"); + + b.ToTable("CohortEnrollmentEntitlements", null, t => + { + t.HasCheckConstraint("CK_CohortEnrollmentEntitlement_NoCredit", "\"SourceType\" NOT IN ('ConsultationCredit', 'Credit1on1', 'OneOnOneCredit')"); + + t.HasCheckConstraint("CK_CohortEnrollmentEntitlement_Status", "\"Status\" IN ('Active', 'Consumed', 'Revoked', 'Expired')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortLearningFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RespondedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RespondedById") + .HasColumnType("integer"); + + b.Property("Response") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("Topic") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("MentorId"); + + b.HasIndex("RespondedById"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.ToTable("CohortLearningFeedback", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortMentorReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("Comment") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHidden") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CohortId"); + + b.HasIndex("LearnerId"); + + b.HasIndex("CourseId", "MentorId") + .IsUnique(); + + b.HasIndex("MentorId", "IsHidden", "CreatedAtUtc"); + + b.ToTable("CohortMentorReviews", null, t => + { + t.HasCheckConstraint("CK_CohortMentorReview_Rating", "\"Rating\" BETWEEN 1 AND 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CohortRevisionSnapshot") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("ImpactSnapshot") + .IsRequired() + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RequestedById") + .HasColumnType("integer"); + + b.Property("RequestedByRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("ShiftWeeks") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("CohortId") + .IsUnique() + .HasDatabaseName("IX_CohortScheduleRequests_PendingCohort") + .HasFilter("\"Status\" = 'Pending'"); + + b.HasIndex("ReviewedById"); + + b.HasIndex("CohortId", "Id"); + + b.HasIndex("RequestedById", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.ToTable("CohortScheduleRequests", null, t => + { + t.HasCheckConstraint("CK_CohortScheduleRequest_Decision", "(\"Status\" NOT IN ('Approved', 'Rejected') OR (\"ReviewedById\" IS NOT NULL AND \"ReviewedAtUtc\" IS NOT NULL)) AND (\"Status\" <> 'Rejected' OR (\"DecisionNote\" IS NOT NULL AND length(btrim(\"DecisionNote\")) > 0))"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Kind", "\"Kind\" IN ('ShiftWeeks', 'CancelEmptyCohort')"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Reason", "length(btrim(\"Reason\")) BETWEEN 10 AND 1000"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_ShiftWeeks", "(\"Kind\" = 'ShiftWeeks' AND \"ShiftWeeks\" BETWEEN 1 AND 8) OR (\"Kind\" = 'CancelEmptyCohort' AND \"ShiftWeeks\" IS NULL)"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Status", "\"Status\" IN ('Pending', 'Approved', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequestEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("RequestId", "Id"); + + b.ToTable("CohortScheduleRequestEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DestinationCourseId") + .HasColumnType("integer"); + + b.Property("EligibilitySnapshot") + .HasColumnType("text"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("PolicyId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RequestedTargetCohortId") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SourceCohortId") + .HasColumnType("integer"); + + b.Property("SourceCourseId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TargetCohortId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DestinationCourseId") + .IsUnique() + .HasFilter("\"DestinationCourseId\" IS NOT NULL"); + + b.HasIndex("PolicyId"); + + b.HasIndex("RequestedTargetCohortId"); + + b.HasIndex("ReviewedById"); + + b.HasIndex("SourceCohortId"); + + b.HasIndex("SourceCourseId") + .IsUnique() + .HasDatabaseName("IX_CohortTransferRequests_PendingSource") + .HasFilter("\"Status\" = 'Pending'"); + + b.HasIndex("TargetCohortId"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.ToTable("CohortTransferRequests", null, t => + { + t.HasCheckConstraint("CK_CohortTransferRequest_Decision", "(\"Status\" <> 'Approved' OR (\"TargetCohortId\" IS NOT NULL AND \"DestinationCourseId\" IS NOT NULL AND \"ReviewedById\" IS NOT NULL)) AND (\"Status\" <> 'Rejected' OR (\"DecisionNote\" IS NOT NULL AND length(btrim(\"DecisionNote\")) > 0 AND \"ReviewedById\" IS NOT NULL))"); + + t.HasCheckConstraint("CK_CohortTransferRequest_Status", "\"Status\" IN ('Pending', 'Approved', 'Rejected', 'Withdrawn')"); + + t.HasCheckConstraint("CK_CohortTransferRequest_Target", "\"TargetCohortId\" IS NULL OR \"TargetCohortId\" <> \"SourceCohortId\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequestEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("RequestId", "Id"); + + b.ToTable("CohortTransferRequestEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAiReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentId") + .HasColumnType("integer"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ErrorCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IssuesJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("RequestedByUserId") + .HasColumnType("integer"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Summary") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Verdict") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("WarningCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContentType", "ContentId", "ReviewedAt"); + + b.ToTable("ContentAiReviews"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentApprovalRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("BatchId") + .HasColumnType("uuid"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DiffSummaryJson") + .HasColumnType("text"); + + b.Property("EntityType") + .HasColumnType("integer"); + + b.Property("IdempotencyKey") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReviewHistoryJson") + .HasColumnType("jsonb"); + + b.Property("ReviewNote") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByName") + .HasColumnType("text"); + + b.Property("RightsConfirmed") + .HasColumnType("boolean"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RowKey") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SourceFileName") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("character varying(260)"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceRowNumber") + .HasColumnType("integer"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("ImportExcel"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedByUserId") + .HasColumnType("integer"); + + b.Property("TargetEntityId") + .HasColumnType("integer"); + + b.Property("ValidationSummaryJson") + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("BatchId"); + + b.HasIndex("SubmittedByUserId"); + + b.HasIndex("EntityType", "Status"); + + b.HasIndex("SubmittedByUserId", "IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.ToTable("ContentApprovalRequests"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAudioTranscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AttemptCount") + .HasColumnType("integer"); + + b.Property("AudioUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("AudioUrlHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Confidence") + .HasColumnType("double precision"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("integer"); + + b.Property("ErrorCode") + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("ErrorMessage") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("LanguageCode") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("LeaseExpiresAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LeaseId") + .HasColumnType("uuid"); + + b.Property("NextAttemptAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RawTranscriptJson") + .HasColumnType("jsonb"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Transcript") + .HasColumnType("text"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("AudioUrlHash") + .IsUnique(); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("Status", "NextAttemptAtUtc", "LeaseExpiresAtUtc"); + + b.ToTable("ContentAudioTranscriptions", null, t => + { + t.HasCheckConstraint("CK_ContentAudioTranscription_Attempts", "\"AttemptCount\" >= 0"); + + t.HasCheckConstraint("CK_ContentAudioTranscription_Language", "\"LanguageCode\" = 'ja-JP'"); + + t.HasCheckConstraint("CK_ContentAudioTranscription_Status", "\"Status\" IN ('Pending', 'Processing', 'Completed', 'Failed')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentBankItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EntityType") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LatestBatchId") + .HasColumnType("uuid"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NaturalKey") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OwnerUserId") + .HasColumnType("integer"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TargetEntityId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EntityType", "TargetEntityId"); + + b.HasIndex("OwnerUserId", "EntityType", "NaturalKey") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.ToTable("ContentBankItems"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentLevelMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanjiId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("CertificateLevelId", "GrammarPatternId") + .IsUnique() + .HasFilter("\"GrammarPatternId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.HasIndex("CertificateLevelId", "KanjiId") + .IsUnique() + .HasFilter("\"KanjiId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.HasIndex("CertificateLevelId", "VocabularyId") + .IsUnique() + .HasFilter("\"VocabularyId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.ToTable("ContentLevelMappings", t => + { + t.HasCheckConstraint("CK_ContentLevelMappings_ExactlyOneContent", "(CASE WHEN \"KanjiId\" IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN \"VocabularyId\" IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN \"GrammarPatternId\" IS NOT NULL THEN 1 ELSE 0 END) = 1"); + }); + + b.HasData( + new + { + Id = 920001, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910001 + }, + new + { + Id = 920002, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910002 + }, + new + { + Id = 920003, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910003 + }, + new + { + Id = 920004, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910004 + }, + new + { + Id = 920005, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910005 + }, + new + { + Id = 920006, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910006 + }, + new + { + Id = 920007, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910007 + }, + new + { + Id = 920008, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910008 + }, + new + { + Id = 920009, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910009 + }, + new + { + Id = 920010, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910010 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("AudioTranscript") + .HasColumnType("text"); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("ContentFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("Instructions") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ListeningSection") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("MockTestSectionId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ParentPassageId") + .HasColumnType("integer"); + + b.Property("PassageCode") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("PassageIdentity") + .HasColumnType("uuid"); + + b.Property("PassageText") + .HasColumnType("text"); + + b.Property("PlaybackPolicyJson") + .HasColumnType("jsonb"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContentFingerprint"); + + b.HasIndex("MockTestSectionId"); + + b.HasIndex("PassageIdentity"); + + b.ToTable("ContentPassages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseAuditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("At") + .HasColumnType("timestamp without time zone"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.ToTable("CourseAuditEntries", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseRetakeRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("EligibilitySnapshot") + .HasColumnType("text"); + + b.Property("EvidenceUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorSupportPlan") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorSupportPlanAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorSupportPlanById") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("ResultPublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CourseId") + .IsUnique() + .HasFilter("\"Status\" = 'Pending'"); + + b.ToTable("CourseRetakeRequests", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseScheduleRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Reason") + .IsRequired() + .HasColumnType("text"); + + b.Property("RequestedById") + .HasColumnType("integer"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("SessionId") + .HasColumnType("integer"); + + b.Property("Status") + .IsConcurrencyToken() + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CourseId", "SessionId") + .IsUnique() + .HasFilter("\"Status\" = 'Pending'"); + + b.ToTable("CourseScheduleRequests", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.EmailVerification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsUsed") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("VerificationCode") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("EmailVerifications"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Feature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccessMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("FREE"); + + b.Property("Category") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("general"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditFeatureKey") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsCoreFree") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("RoutePrefixesJson") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("Features"); + + b.HasData( + new + { + Id = 1, + AccessMode = "PLAN_REQUIRED", + Category = "self_study", + Code = "LESSONS_CONTENT", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập kho bài học JLPT đầy đủ theo cấp độ kèm nghe hiểu, đọc hiểu và lưu tiến độ.", + IsCoreFree = false, + IsDeleted = false, + Name = "Thư viện bài học JLPT", + RoutePrefixesJson = "[\"/lessons\",\"/lesson-player\",\"/riki/listening\",\"/riki/reading\"]", + SortOrder = 10 + }, + new + { + Id = 2, + AccessMode = "FREE", + Category = "core_tools", + Code = "JAPANESE_LIBRARY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Tra cứu ngữ pháp, luyện viết Hiragana, Katakana và Kanji theo thứ tự nét miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Thư viện Kana, Kanji & Ngữ pháp", + RoutePrefixesJson = "[\"/grammar\",\"/kanji-writing\",\"/vocabulary-detail\"]", + SortOrder = 3 + }, + new + { + Id = 3, + AccessMode = "FREE", + Category = "practice_exam", + Code = "PRACTICE_EXERCISES", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Làm bài luyện tập củng cố kỹ năng và bộ đề theo cấp độ JLPT.", + IsCoreFree = false, + IsDeleted = false, + Name = "Bài luyện tập theo kỹ năng", + RoutePrefixesJson = "[\"/lesson-practice\",\"/practice-sets\"]", + SortOrder = 20 + }, + new + { + Id = 4, + AccessMode = "FREE", + Category = "practice_exam", + Code = "MOCK_TESTS", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Luyện đề thi thử JLPT mô phỏng đầy đủ 4 kỹ năng và theo dõi kết quả.", + IsCoreFree = false, + IsDeleted = false, + Name = "Đề thi thử JLPT", + RoutePrefixesJson = "[\"/mock-test\",\"/mock-tests\",\"/exam-result\"]", + SortOrder = 21 + }, + new + { + Id = 5, + AccessMode = "FREE", + Category = "self_study", + Code = "STANDARD_ROADMAP", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Xem lộ trình học JLPT tiêu chuẩn theo mục tiêu, kết quả đánh giá năng lực và tiến độ học.", + IsCoreFree = false, + IsDeleted = false, + Name = "Lộ trình tiêu chuẩn & Tiến độ học", + RoutePrefixesJson = "[\"/roadmap\"]", + SortOrder = 11 + }, + new + { + Id = 6, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_MOCK_EXPLANATION", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "mock_test_explanation", + Description = "Nhận phân tích chi tiết đáp án đề thi thử từ trợ lý AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Giải thích câu hỏi bằng AI", + SortOrder = 33 + }, + new + { + Id = 7, + AccessMode = "DISABLED", + Category = "mentor_legacy", + Code = "MENTOR_1ON1_LEGACY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Gói cũ bao gồm 12 buổi ôn luyện trực tiếp 1-1 với Mentor (đã thay bằng lớp học nhóm).", + IsCoreFree = false, + IsDeleted = false, + Name = "12 buổi meeting 1-1 với Mentor", + SortOrder = 90 + }, + new + { + Id = 8, + AccessMode = "DISABLED", + Category = "mentor_legacy", + Code = "MENTOR_ROOM_LEGACY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Cấu hình lịch 1-1 cũ (lớp học nhóm dùng cơ chế ghi danh khóa học riêng).", + IsCoreFree = false, + IsDeleted = false, + Name = "Đặt lịch và phòng học trực tuyến", + SortOrder = 91 + }, + new + { + Id = 9, + AccessMode = "FREE", + Category = "core_tools", + Code = "PERSONAL_NOTEBOOK", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Tạo thư mục, tệp ghi chú, trang bài học, highlight và mục đã lưu cá nhân miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Sổ tay cá nhân & Mini Notebook", + RoutePrefixesJson = "[\"/kanji-notebook\"]", + SortOrder = 1 + }, + new + { + Id = 10, + AccessMode = "FREE", + Category = "core_tools", + Code = "SRS_STUDY", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Ôn thẻ đến hạn, 4 chế độ ôn tự do, quản lý thẻ cá nhân và thư viện thẻ mẫu miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Ôn tập SRS & Thư viện thẻ mẫu", + RoutePrefixesJson = "[\"/daily-srs\"]", + SortOrder = 2 + }, + new + { + Id = 11, + AccessMode = "FREE", + Category = "practice_exam", + Code = "PLACEMENT_TEST", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Làm bài đánh giá trình độ JLPT đầu vào để xác định cấp độ học phù hợp.", + IsCoreFree = false, + IsDeleted = false, + Name = "Đánh giá năng lực đầu vào", + RoutePrefixesJson = "[\"/placement\"]", + SortOrder = 19 + }, + new + { + Id = 12, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_LEARNING_PATH", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "learning_path", + Description = "Tạo kế hoạch học tập chi tiết theo ngày bằng AI dựa trên điểm đánh giá và ngày thi.", + IsCoreFree = false, + IsDeleted = false, + Name = "Lộ trình học cá nhân hóa bằng AI", + SortOrder = 30 + }, + new + { + Id = 13, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_SPEAKING", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "speaking", + Description = "Thu âm tiếng Nhật và nhận điểm phát âm, ngữ điệu cùng nhận xét chi tiết từ AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Luyện nói & Chấm phát âm AI", + RoutePrefixesJson = "[\"/riki/speaking\",\"/speech\"]", + SortOrder = 31 + }, + new + { + Id = 14, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_WRITING", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "writing", + Description = "Viết câu và bài luận tiếng Nhật, nhận sửa lỗi ngữ pháp và chấm điểm từ AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Luyện viết & Chấm bài luận AI", + RoutePrefixesJson = "[\"/riki/essay\",\"/sentence-studio\"]", + SortOrder = 32 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GradingResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FeedbackJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("GradedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("HomeworkSubmissionId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OverallScore") + .HasColumnType("double precision"); + + b.Property("PracticeSubmissionId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HomeworkSubmissionId") + .IsUnique(); + + b.HasIndex("PracticeSubmissionId") + .IsUnique(); + + b.ToTable("GradingResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentenceMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("Structure") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UsageNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("Title"); + + b.HasIndex("UserAccountId"); + + b.ToTable("GrammarPatterns"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiDraftFeedback") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("AiDraftGeneratedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("AiDraftScore") + .HasColumnType("double precision"); + + b.Property("AiDraftUnavailableReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AssignmentScope") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("Booking1on1"); + + b.Property("AuthoredDefinitionJson") + .HasColumnType("text"); + + b.Property("CohortAssignmentGroupKey") + .HasColumnType("uuid"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DueAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Instructions") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorFeedback") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorScore") + .HasColumnType("double precision"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Passed") + .HasColumnType("boolean"); + + b.Property("PublishedByMentorId") + .HasColumnType("integer"); + + b.Property("PublishedFeedbackAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("StudyCourseId") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("MentorId"); + + b.HasIndex("StudyCourseId"); + + b.HasIndex("CohortId", "LearnerId"); + + b.HasIndex("LearnerId", "DueAt"); + + b.ToTable("HomeworkAssignments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentAttachment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileKey") + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StorageReference") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("FileKey"); + + b.HasIndex("HomeworkAssignmentId"); + + b.ToTable("HomeworkAssignmentAttachments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentExercise", b => + { + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.HasKey("HomeworkAssignmentId", "PracticeExerciseId"); + + b.HasIndex("PracticeExerciseId"); + + b.ToTable("HomeworkAssignmentExercises", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentLesson", b => + { + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.HasKey("HomeworkAssignmentId", "LessonId"); + + b.HasIndex("LessonId"); + + b.ToTable("HomeworkAssignmentLessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileUrl") + .HasColumnType("text"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastRevisedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PrivateAudioReference") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PrivateScanReference") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RevisionCount") + .HasColumnType("integer"); + + b.Property("ScanStorageUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SelectedOptionsJson") + .HasColumnType("text"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TextContent") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("HomeworkAssignmentId") + .IsUnique(); + + b.HasIndex("LearnerId"); + + b.HasIndex("LessonId"); + + b.ToTable("HomeworkSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmissionFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileKey") + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("HomeworkSubmissionId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StorageReference") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("FileKey"); + + b.HasIndex("HomeworkSubmissionId"); + + b.ToTable("HomeworkSubmissionFiles"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptExamSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExamDate") + .HasColumnType("date"); + + b.Property("ImportedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Location") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ReviewNote") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SourceUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("Status") + .IsConcurrencyToken() + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("SourceKey") + .IsUnique(); + + b.ToTable("JlptExamSchedules", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptLevelPayCoefficient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("Coefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ConfiguredByAdminId"); + + b.HasIndex("CertificateLevelId", "EffectiveFromUtc") + .IsUnique(); + + b.ToTable("JlptLevelPayCoefficients", t => + { + t.HasCheckConstraint("CK_JlptLevelPayCoefficient_Positive", "\"Coefficient\" > 0"); + + t.HasCheckConstraint("CK_JlptLevelPayCoefficient_Range", "\"EffectiveUntilUtc\" IS NULL OR \"EffectiveUntilUtc\" > \"EffectiveFromUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("Character") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Romaji") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StrokeCount") + .HasColumnType("integer"); + + b.Property("StrokeOrderImageUrl") + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("Character", "Type") + .IsUnique(); + + b.ToTable("KanaCharacters"); + + b.HasData( + new + { + Id = 1, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/22/Ja-a.ogg", + Character = "あ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1757), + IsDeleted = false, + Romaji = "a", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 2, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-i.ogg", + Character = "い", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1766), + IsDeleted = false, + Romaji = "i", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 3, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Ja-u.ogg", + Character = "う", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1768), + IsDeleted = false, + Romaji = "u", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 4, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/21/Ja-e.ogg", + Character = "え", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1770), + IsDeleted = false, + Romaji = "e", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 5, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/df/Ja-o.ogg", + Character = "お", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1771), + IsDeleted = false, + Romaji = "o", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 6, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Ja-ka.ogg", + Character = "か", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1774), + IsDeleted = false, + Romaji = "ka", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 7, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/87/Ja-ki.ogg", + Character = "き", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1775), + IsDeleted = false, + Romaji = "ki", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 8, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Ja-ku.ogg", + Character = "く", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1776), + IsDeleted = false, + Romaji = "ku", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 9, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b3/Ja-ke.ogg", + Character = "け", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1830), + IsDeleted = false, + Romaji = "ke", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 10, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/18/Ja-ko.ogg", + Character = "こ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1832), + IsDeleted = false, + Romaji = "ko", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 11, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Ja-sa.ogg", + Character = "さ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1833), + IsDeleted = false, + Romaji = "sa", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 12, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/80/Ja-shi.ogg", + Character = "し", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1834), + IsDeleted = false, + Romaji = "shi", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 13, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Ja-su.ogg", + Character = "す", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1835), + IsDeleted = false, + Romaji = "su", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 14, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a8/Ja-se.ogg", + Character = "せ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1836), + IsDeleted = false, + Romaji = "se", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 15, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/00/Ja-so.ogg", + Character = "そ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1837), + IsDeleted = false, + Romaji = "so", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 16, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/d2/Ja-ta.ogg", + Character = "た", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1838), + IsDeleted = false, + Romaji = "ta", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 17, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/38/Ja-chi.ogg", + Character = "ち", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1838), + IsDeleted = false, + Romaji = "chi", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 18, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/32/Ja-tsu.ogg", + Character = "つ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1840), + IsDeleted = false, + Romaji = "tsu", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 19, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/10/Ja-te.ogg", + Character = "て", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1841), + IsDeleted = false, + Romaji = "te", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 20, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a5/Ja-to.ogg", + Character = "と", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1842), + IsDeleted = false, + Romaji = "to", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 21, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/92/Ja-na.ogg", + Character = "な", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1843), + IsDeleted = false, + Romaji = "na", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 22, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b7/Ja-ni.ogg", + Character = "に", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1844), + IsDeleted = false, + Romaji = "ni", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 23, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b1/Ja-nu.ogg", + Character = "ぬ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1845), + IsDeleted = false, + Romaji = "nu", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 24, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/86/Ja-ne.ogg", + Character = "ね", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1845), + IsDeleted = false, + Romaji = "ne", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 25, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/54/Ja-no.ogg", + Character = "の", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1846), + IsDeleted = false, + Romaji = "no", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 26, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/Ja-ha.ogg", + Character = "は", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1847), + IsDeleted = false, + Romaji = "ha", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 27, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/99/Ja-hi.ogg", + Character = "ひ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1848), + IsDeleted = false, + Romaji = "hi", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 28, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/70/Ja-fu.ogg", + Character = "ふ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1849), + IsDeleted = false, + Romaji = "fu", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 29, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2a/Ja-he.ogg", + Character = "へ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1849), + IsDeleted = false, + Romaji = "he", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 30, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Ja-ho.ogg", + Character = "ほ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1850), + IsDeleted = false, + Romaji = "ho", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 31, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Ja-ma.ogg", + Character = "ま", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1851), + IsDeleted = false, + Romaji = "ma", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 32, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/16/Ja-mi.ogg", + Character = "み", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1852), + IsDeleted = false, + Romaji = "mi", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 33, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ja-mu.ogg", + Character = "む", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1852), + IsDeleted = false, + Romaji = "mu", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 34, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/8b/Ja-me.ogg", + Character = "め", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1913), + IsDeleted = false, + Romaji = "me", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 35, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Ja-mo.ogg", + Character = "も", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1915), + IsDeleted = false, + Romaji = "mo", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 36, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/e8/Ja-ya.ogg", + Character = "や", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1915), + IsDeleted = false, + Romaji = "ya", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 37, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/7b/Ja-yu.ogg", + Character = "ゆ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1916), + IsDeleted = false, + Romaji = "yu", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 38, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c9/Ja-yo.ogg", + Character = "よ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1917), + IsDeleted = false, + Romaji = "yo", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 39, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/04/Ja-ra.ogg", + Character = "ら", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1918), + IsDeleted = false, + Romaji = "ra", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 40, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/76/Ja-ri.ogg", + Character = "り", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1919), + IsDeleted = false, + Romaji = "ri", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 41, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/56/Ja-ru.ogg", + Character = "る", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1920), + IsDeleted = false, + Romaji = "ru", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 42, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/57/Ja-re.ogg", + Character = "れ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1920), + IsDeleted = false, + Romaji = "re", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 43, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Ja-ro.ogg", + Character = "ろ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1922), + IsDeleted = false, + Romaji = "ro", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 44, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Ja-wa.ogg", + Character = "わ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1922), + IsDeleted = false, + Romaji = "wa", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 45, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/77/Ja-wo.ogg", + Character = "を", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1923), + IsDeleted = false, + Romaji = "wo", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 46, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0c/Ja-n.ogg", + Character = "ん", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1924), + IsDeleted = false, + Romaji = "n", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 47, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/22/Ja-a.ogg", + Character = "ア", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1955), + IsDeleted = false, + Romaji = "a", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 48, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-i.ogg", + Character = "イ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1958), + IsDeleted = false, + Romaji = "i", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 49, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Ja-u.ogg", + Character = "ウ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1959), + IsDeleted = false, + Romaji = "u", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 50, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/21/Ja-e.ogg", + Character = "エ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1960), + IsDeleted = false, + Romaji = "e", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 51, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/df/Ja-o.ogg", + Character = "オ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1961), + IsDeleted = false, + Romaji = "o", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 52, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Ja-ka.ogg", + Character = "カ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1961), + IsDeleted = false, + Romaji = "ka", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 53, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/87/Ja-ki.ogg", + Character = "キ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1962), + IsDeleted = false, + Romaji = "ki", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 54, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Ja-ku.ogg", + Character = "ク", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1963), + IsDeleted = false, + Romaji = "ku", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 55, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b3/Ja-ke.ogg", + Character = "ケ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1964), + IsDeleted = false, + Romaji = "ke", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 56, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/18/Ja-ko.ogg", + Character = "コ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2006), + IsDeleted = false, + Romaji = "ko", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 57, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Ja-sa.ogg", + Character = "サ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2009), + IsDeleted = false, + Romaji = "sa", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 58, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/80/Ja-shi.ogg", + Character = "シ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2010), + IsDeleted = false, + Romaji = "shi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 59, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Ja-su.ogg", + Character = "ス", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2011), + IsDeleted = false, + Romaji = "su", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 60, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a8/Ja-se.ogg", + Character = "セ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2012), + IsDeleted = false, + Romaji = "se", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 61, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/00/Ja-so.ogg", + Character = "ソ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2014), + IsDeleted = false, + Romaji = "so", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 62, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/d2/Ja-ta.ogg", + Character = "タ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2015), + IsDeleted = false, + Romaji = "ta", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 63, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/38/Ja-chi.ogg", + Character = "チ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2016), + IsDeleted = false, + Romaji = "chi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 64, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/32/Ja-tsu.ogg", + Character = "ツ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2017), + IsDeleted = false, + Romaji = "tsu", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 65, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/10/Ja-te.ogg", + Character = "テ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2019), + IsDeleted = false, + Romaji = "te", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 66, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a5/Ja-to.ogg", + Character = "ト", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2022), + IsDeleted = false, + Romaji = "to", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 67, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/92/Ja-na.ogg", + Character = "ナ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2023), + IsDeleted = false, + Romaji = "na", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 68, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b7/Ja-ni.ogg", + Character = "ニ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2024), + IsDeleted = false, + Romaji = "ni", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 69, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b1/Ja-nu.ogg", + Character = "ヌ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2026), + IsDeleted = false, + Romaji = "nu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 70, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/86/Ja-ne.ogg", + Character = "ネ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2027), + IsDeleted = false, + Romaji = "ne", + StrokeCount = 4, + Type = "Katakana" + }, + new + { + Id = 71, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/54/Ja-no.ogg", + Character = "ノ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2028), + IsDeleted = false, + Romaji = "no", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 72, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/Ja-ha.ogg", + Character = "ハ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2029), + IsDeleted = false, + Romaji = "ha", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 73, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/99/Ja-hi.ogg", + Character = "ヒ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2030), + IsDeleted = false, + Romaji = "hi", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 74, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/70/Ja-fu.ogg", + Character = "フ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2032), + IsDeleted = false, + Romaji = "fu", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 75, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2a/Ja-he.ogg", + Character = "ヘ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2033), + IsDeleted = false, + Romaji = "he", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 76, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Ja-ho.ogg", + Character = "ホ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2034), + IsDeleted = false, + Romaji = "ho", + StrokeCount = 4, + Type = "Katakana" + }, + new + { + Id = 77, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Ja-ma.ogg", + Character = "マ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2036), + IsDeleted = false, + Romaji = "ma", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 78, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/16/Ja-mi.ogg", + Character = "ミ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2037), + IsDeleted = false, + Romaji = "mi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 79, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ja-mu.ogg", + Character = "ム", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2038), + IsDeleted = false, + Romaji = "mu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 80, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/8b/Ja-me.ogg", + Character = "メ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2039), + IsDeleted = false, + Romaji = "me", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 81, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Ja-mo.ogg", + Character = "モ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2086), + IsDeleted = false, + Romaji = "mo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 82, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/e8/Ja-ya.ogg", + Character = "ヤ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2087), + IsDeleted = false, + Romaji = "ya", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 83, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/7b/Ja-yu.ogg", + Character = "ユ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2088), + IsDeleted = false, + Romaji = "yu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 84, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c9/Ja-yo.ogg", + Character = "ヨ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2089), + IsDeleted = false, + Romaji = "yo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 85, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/04/Ja-ra.ogg", + Character = "ラ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2090), + IsDeleted = false, + Romaji = "ra", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 86, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/76/Ja-ri.ogg", + Character = "リ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2092), + IsDeleted = false, + Romaji = "ri", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 87, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/56/Ja-ru.ogg", + Character = "ル", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2093), + IsDeleted = false, + Romaji = "ru", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 88, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/57/Ja-re.ogg", + Character = "レ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2094), + IsDeleted = false, + Romaji = "re", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 89, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Ja-ro.ogg", + Character = "ロ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2096), + IsDeleted = false, + Romaji = "ro", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 90, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Ja-wa.ogg", + Character = "ワ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2097), + IsDeleted = false, + Romaji = "wa", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 91, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/77/Ja-wo.ogg", + Character = "ヲ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2098), + IsDeleted = false, + Romaji = "wo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 92, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0c/Ja-n.ogg", + Character = "ン", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2099), + IsDeleted = false, + Romaji = "n", + StrokeCount = 2, + Type = "Katakana" + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EaseFactor") + .HasColumnType("double precision"); + + b.Property("IntervalDays") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanaCharacterId") + .HasColumnType("integer"); + + b.Property("LastReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NextReviewDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Repetitions") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("KanaCharacterId"); + + b.HasIndex("UserId", "KanaCharacterId") + .IsUnique(); + + b.HasIndex("UserId", "NextReviewDate"); + + b.ToTable("KanaWritingPracticeCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanaWritingPracticeCardId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Quality") + .HasColumnType("integer"); + + b.Property("Rating") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalMistakes") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("KanaWritingPracticeCardId"); + + b.ToTable("KanaWritingPracticeHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("Character") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KunYomi") + .HasColumnType("text"); + + b.Property("Meaning") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OnYomi") + .HasColumnType("text"); + + b.Property("SinoVietnamese") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("StrokeCount") + .HasColumnType("integer"); + + b.Property("StrokeOrderImageUrl") + .HasColumnType("text"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("Character"); + + b.HasIndex("Status"); + + b.HasIndex("UserAccountId"); + + b.ToTable("Kanjis"); + + b.HasData( + new + { + Id = 910001, + Character = "日", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひ、か", + Meaning = "Mặt trời; ngày", + OnYomi = "ニチ、ジツ", + SinoVietnamese = "Nhật", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910002, + Character = "月", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "つき", + Meaning = "Mặt trăng; tháng", + OnYomi = "ゲツ、ガツ", + SinoVietnamese = "Nguyệt", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910003, + Character = "火", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひ、ほ", + Meaning = "Lửa", + OnYomi = "カ", + SinoVietnamese = "Hỏa", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910004, + Character = "水", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "みず", + Meaning = "Nước", + OnYomi = "スイ", + SinoVietnamese = "Thủy", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910005, + Character = "木", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "き、こ", + Meaning = "Cây; gỗ", + OnYomi = "モク、ボク", + SinoVietnamese = "Mộc", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910006, + Character = "金", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "かね、かな", + Meaning = "Vàng; tiền", + OnYomi = "キン、コン", + SinoVietnamese = "Kim", + Status = "Published", + StrokeCount = 8, + Version = 1 + }, + new + { + Id = 910007, + Character = "土", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "つち", + Meaning = "Đất", + OnYomi = "ド、ト", + SinoVietnamese = "Thổ", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910008, + Character = "山", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "やま", + Meaning = "Núi", + OnYomi = "サン", + SinoVietnamese = "Sơn", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910009, + Character = "川", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "かわ", + Meaning = "Sông", + OnYomi = "セン", + SinoVietnamese = "Xuyên", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910010, + Character = "人", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひと", + Meaning = "Người", + OnYomi = "ジン、ニン", + SinoVietnamese = "Nhân", + Status = "Published", + StrokeCount = 2, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LanguageSkill", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Code") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique() + .HasFilter("\"Code\" IS NOT NULL"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LanguageSkills"); + + b.HasData( + new + { + Id = 1, + Code = "VOCABULARY", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese vocabulary learning skill.", + IsDeleted = false, + Name = "Vocabulary" + }, + new + { + Id = 2, + Code = "KANJI", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese kanji learning skill.", + IsDeleted = false, + Name = "Kanji" + }, + new + { + Id = 3, + Code = "GRAMMAR", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese grammar learning skill.", + IsDeleted = false, + Name = "Grammar" + }, + new + { + Id = 4, + Code = "LISTENING", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese listening comprehension skill.", + IsDeleted = false, + Name = "Listening" + }, + new + { + Id = 5, + Code = "READING", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese reading comprehension skill.", + IsDeleted = false, + Name = "Reading" + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerEssay", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentText") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageStoragePath") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageUrl") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OcrLanguage") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("OriginalOcrText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedDate"); + + b.ToTable("LearnerEssays"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("TargetId") + .HasColumnType("integer"); + + b.Property("TargetTitle") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("UpdatedAtUtc", "Id"); + + b.HasIndex("LearnerId", "TargetType", "TargetId") + .IsUnique(); + + b.ToTable("LearnerFeedback", null, t => + { + t.HasCheckConstraint("CK_LearnerFeedback_Rating", "\"Rating\" BETWEEN 1 AND 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerHighlight", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AnchorPrefix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AnchorSuffix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Color") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ContentVersionHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EndOffset") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LinkedNoteEntryId") + .HasColumnType("integer"); + + b.Property("LinkedReviewCardId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SelectedText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("StartOffset") + .HasColumnType("integer"); + + b.Property("TargetId") + .HasColumnType("integer"); + + b.Property("TargetKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TargetType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TranslationSnapshot") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LinkedNoteEntryId"); + + b.HasIndex("LinkedReviewCardId"); + + b.HasIndex("UserId", "CreatedDate"); + + b.HasIndex("UserId", "TargetKey"); + + b.HasIndex("UserId", "TargetType", "TargetId"); + + b.ToTable("LearnerHighlights"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FolderId") + .HasColumnType("integer"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("FolderId"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_LearnerNotes_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("UserId", "Name"); + + b.HasIndex("UserId", "FolderId", "IsDeleted", "SortOrder"); + + b.ToTable("LearnerNotes"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContextSnippet") + .HasMaxLength(600) + .HasColumnType("character varying(600)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleMeaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExampleSentence") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("HighlightColor") + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("ItemKind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("manual"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.Property("LearnerNoteId") + .HasColumnType("integer") + .HasColumnName("VocabularyListId"); + + b.Property("ManualMeaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ManualReading") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ManualWord") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("NotebookPageId") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TagsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'[]'::jsonb"); + + b.Property("VocabularyId") + .HasColumnType("integer") + .HasColumnName("VocabularyEntryId"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("LearnerNoteId", "IsDeleted"); + + b.HasIndex("NotebookPageId", "IsDeleted", "SortOrder"); + + b.ToTable("LearnerNoteEntries"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerPracticeAnswer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseAttemptId") + .HasColumnType("integer"); + + b.Property("PracticeQuestionId") + .HasColumnType("integer"); + + b.Property("SelectedOptionId") + .HasColumnType("integer"); + + b.Property("TextAnswer") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("PracticeQuestionId"); + + b.HasIndex("SelectedOptionId"); + + b.HasIndex("PracticeExerciseAttemptId", "PracticeQuestionId") + .IsUnique(); + + b.ToTable("LearnerPracticeAnswers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("EstimatedMinutes") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(15); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer") + .HasColumnName("SkillId"); + + b.Property("LearningObjectives") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PrerequisiteLessonId") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceProvenance") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("TopicId") + .HasColumnType("integer"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("PrerequisiteLessonId"); + + b.HasIndex("Status"); + + b.HasIndex("TopicId"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("CertificateLevelId", "LanguageSkillId"); + + b.ToTable("Lessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonGrammar", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("GrammarPatternId") + .HasColumnType("integer") + .HasColumnName("GrammarPointId"); + + b.HasKey("LessonId", "GrammarPatternId"); + + b.HasIndex("GrammarPatternId"); + + b.ToTable("LessonGrammars"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonKanji", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.HasKey("LessonId", "KanjiId"); + + b.HasIndex("KanjiId"); + + b.ToTable("LessonKanjis"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonProgress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FirstViewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("InteractionCount") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastInteractedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LastPositionSeconds") + .HasColumnType("integer"); + + b.Property("LastWatchedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ProgressPercent") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LessonId"); + + b.HasIndex("UserId", "LessonId") + .IsUnique(); + + b.ToTable("LessonProgresses"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonVocabulary", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("VocabularyId") + .HasColumnType("integer") + .HasColumnName("VocabularyEntryId"); + + b.HasKey("LessonId", "VocabularyId"); + + b.HasIndex("VocabularyId"); + + b.ToTable("LessonVocabularies"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAbuseReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ReporterId") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetUserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("ReporterId") + .HasDatabaseName("IX_MentorAbuseReports_ReporterId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorAbuseReports_Status"); + + b.HasIndex("TargetUserId") + .HasDatabaseName("IX_MentorAbuseReports_TargetUserId"); + + b.ToTable("MentorAbuseReports", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceApproval", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionReason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceSummary") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("RawLearnerDurationSeconds") + .HasColumnType("integer"); + + b.Property("RawMentorDurationSeconds") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("ReviewedByAdminId"); + + b.ToTable("MentorAttendanceApprovals", t => + { + t.HasCheckConstraint("CK_MentorAttendanceApproval_Minutes", "\"ApprovedEligibleMinutes\" IS NULL OR (\"ApprovedEligibleMinutes\" > 0 AND \"ApprovedEligibleMinutes\" <= 90)"); + + t.HasCheckConstraint("CK_MentorAttendanceApproval_RawDuration", "\"RawMentorDurationSeconds\" >= 0 AND \"RawLearnerDurationSeconds\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("FirstJoinedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastJoinedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastSeenAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LeftAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ReconnectionCount") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("RoomId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TotalDurationSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("RoomId") + .HasDatabaseName("IX_MentorAttendanceRecords_RoomId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorAttendanceRecords_Status"); + + b.HasIndex("UserId") + .HasDatabaseName("IX_MentorAttendanceRecords_UserId"); + + b.HasIndex("MentorBookingId", "UserId") + .IsUnique() + .HasDatabaseName("IX_MentorAttendanceRecords_Booking_User"); + + b.HasIndex("RoomId", "UserId") + .IsUnique() + .HasFilter("\"MentorBookingId\" IS NULL"); + + b.ToTable("MentorAttendanceRecords", null, t => + { + t.HasCheckConstraint("CK_MentorAttendanceRecord_Duration", "\"TotalDurationSeconds\" >= 0"); + + t.HasCheckConstraint("CK_MentorAttendanceRecord_Reconnection", "\"ReconnectionCount\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminName") + .HasColumnType("text"); + + b.Property("AttendanceTrackingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("BookedCount") + .HasColumnType("integer"); + + b.Property("CancelReason") + .HasColumnType("text"); + + b.Property("CancelRejectedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CancelRejectionReason") + .HasColumnType("text"); + + b.Property("CancelRequestedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ChangeRequestReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ChangeRequestedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ChangeResolution") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EndTime") + .HasColumnType("timestamp without time zone"); + + b.Property("GenerationKey") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("IsApproved") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("MaxLearners") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorScheduleRuleId") + .HasColumnType("bigint"); + + b.Property("MentorWeeklyAvailabilityId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectionReason") + .HasColumnType("text"); + + b.Property("RestMinutesSnapshot") + .HasColumnType("integer"); + + b.Property("RoomId") + .HasColumnType("uuid"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SessionMinutesSnapshot") + .HasColumnType("integer"); + + b.Property("StartTime") + .HasColumnType("timestamp without time zone"); + + b.Property("TeachingProposalId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("GenerationKey") + .IsUnique() + .HasFilter("\"GenerationKey\" IS NOT NULL"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorScheduleRuleId"); + + b.HasIndex("MentorWeeklyAvailabilityId"); + + b.HasIndex("RoomId") + .IsUnique(); + + b.HasIndex("TeachingProposalId") + .HasFilter("\"TeachingProposalId\" IS NOT NULL"); + + b.HasIndex("MentorId", "StartTime", "EndTime"); + + b.ToTable("MentorAvailabilities", t => + { + t.HasCheckConstraint("CK_MentorAvailability_BookedCount", "\"BookedCount\" >= 0 AND \"BookedCount\" <= \"MaxLearners\""); + + t.HasCheckConstraint("CK_MentorAvailability_GeneratedSlot", "(\"GenerationKey\" IS NULL AND \"PolicyVersion\" IS NULL AND \"MentorScheduleRuleId\" IS NULL AND \"LocalBusinessDate\" IS NULL AND \"GroupPolicyId\" IS NULL AND \"SessionMinutesSnapshot\" IS NULL AND \"RestMinutesSnapshot\" IS NULL) OR (\"GenerationKey\" IS NOT NULL AND \"PolicyVersion\" IS NOT NULL AND \"PolicyVersion\" > 0 AND (\"MentorScheduleRuleId\" IS NOT NULL OR \"TeachingProposalId\" IS NOT NULL) AND \"LocalBusinessDate\" IS NOT NULL AND ((\"GroupPolicyId\" IS NULL AND \"SessionMinutesSnapshot\" IS NULL AND \"RestMinutesSnapshot\" IS NULL AND \"MaxLearners\" = 1 AND \"EndTime\" = \"StartTime\" + INTERVAL '90 minutes') OR (\"GroupPolicyId\" IS NOT NULL AND \"SessionMinutesSnapshot\" > 0 AND \"RestMinutesSnapshot\" >= 0 AND \"MaxLearners\" BETWEEN 1 AND 50 AND \"EndTime\" = \"StartTime\" + \"SessionMinutesSnapshot\" * INTERVAL '1 minute')))"); + }); + + b.HasData( + new + { + Id = 990001, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 1, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 2, 10, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900002, + RoomId = new Guid("a1000000-0000-0000-0000-000000990001"), + StartTime = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990002, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 3, 14, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900002, + RoomId = new Guid("a1000000-0000-0000-0000-000000990002"), + StartTime = new DateTime(2026, 10, 3, 13, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990003, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 4, 10, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900003, + RoomId = new Guid("a1000000-0000-0000-0000-000000990003"), + StartTime = new DateTime(2026, 10, 4, 9, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990004, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 5, 14, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900003, + RoomId = new Guid("a1000000-0000-0000-0000-000000990004"), + StartTime = new DateTime(2026, 10, 5, 13, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBankAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountHolderName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AccountNumberHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AccountVersion") + .HasColumnType("integer"); + + b.Property("BankCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("BankName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedAccountNumber") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsCurrent") + .HasColumnType("boolean"); + + b.Property("MaskedAccountNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("VerificationNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VerificationStatus") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedByAdminId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorUserId") + .IsUnique() + .HasDatabaseName("IX_MentorBankAccounts_MentorUserId_Current") + .HasFilter("\"IsCurrent\" = TRUE"); + + b.HasIndex("VerifiedByAdminId"); + + b.HasIndex("MentorUserId", "AccountVersion") + .IsUnique(); + + b.ToTable("MentorBankAccounts", t => + { + t.HasCheckConstraint("CK_MentorBankAccount_Version", "\"AccountVersion\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttendedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CancellationReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CancelledByRole") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CancelledByUserId") + .HasColumnType("integer"); + + b.Property("CompensationCurrency") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CompensationFormulaVersion") + .HasColumnType("integer"); + + b.Property("CompensationLevelId") + .HasColumnType("integer"); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditGrantId") + .HasColumnType("bigint"); + + b.Property("ExceptionApproved") + .HasColumnType("boolean"); + + b.Property("ExceptionReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExceptionRequested") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MeetingLink") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeFeedback") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PracticeFeedbackAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeScore") + .HasColumnType("integer"); + + b.Property("Question") + .HasColumnType("text"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ScheduledCompensationAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserSubscriptionId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CompensationLevelId"); + + b.HasIndex("CreditGrantId"); + + b.HasIndex("MentorAvailabilityId", "LearnerId") + .IsUnique() + .HasFilter("\"MentorAvailabilityId\" IS NOT NULL AND \"LearnerId\" IS NOT NULL AND NOT \"IsDeleted\" AND \"Status\" <> 'Cancelled'"); + + b.HasIndex("MentorAvailabilityId", "UserSubscriptionId") + .IsUnique() + .HasFilter("NOT \"IsDeleted\" AND \"Status\" <> 'Cancelled'"); + + b.HasIndex("UserSubscriptionId", "Status"); + + b.ToTable("MentorBookings"); + + b.HasData( + new + { + Id = 990001, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Meeting demo để kiểm thử phòng họp trên frontend.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990001, + Version = 0u + }, + new + { + Id = 990002, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Em muốn nhờ Mentor giải đáp phần ngữ pháp N3 bài 5.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990002, + Version = 0u + }, + new + { + Id = 990003, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Hỏi về cách phân biệt giữa ~てくる và ~ていく.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990003, + Version = 0u + }, + new + { + Id = 990004, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Tư vấn phương pháp luyện nghe JLPT N3 hiệu quả.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990004, + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingDayGuard", b => + { + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("ActiveBookingCount") + .HasColumnType("integer"); + + b.HasKey("MentorId", "LocalBusinessDate"); + + b.ToTable("MentorBookingDayGuards", null, t => + { + t.HasCheckConstraint("CK_MentorBookingDayGuard_Count", "\"ActiveBookingCount\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingIntent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IntentKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("RequestHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("LearnerId", "IntentKey") + .IsUnique(); + + b.ToTable("MentorBookingIntents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingReservation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EndUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("ReleasedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RestProtectedUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("StartUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MentorAvailabilityId") + .HasFilter("\"ReleasedAtUtc\" IS NULL"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("MentorAvailabilityId", "MentorId"); + + b.HasIndex("MentorId", "LocalBusinessDate", "ReleasedAtUtc"); + + b.ToTable("MentorBookingReservations", null, t => + { + t.HasCheckConstraint("CK_MentorBookingReservation_Interval", "\"EndUtc\" > \"StartUtc\""); + + t.HasCheckConstraint("CK_MentorBookingReservation_PolicyVersion", "\"PolicyVersion\" > 0"); + + t.HasCheckConstraint("CK_MentorBookingReservation_Rest", "\"RestProtectedUntilUtc\" >= \"EndUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingTerms", b => + { + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ConfirmedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("ScheduledEndUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduledStartUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MentorBookingId"); + + b.HasIndex("MentorAvailabilityId"); + + b.ToTable("MentorBookingTerms", null, t => + { + t.HasCheckConstraint("CK_MentorBookingTerms_Interval", "\"ScheduledEndUtc\" > \"ScheduledStartUtc\""); + + t.HasCheckConstraint("CK_MentorBookingTerms_PolicyVersion", "\"PolicyVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCalendarConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("LastSyncedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("ProtectedRefreshToken") + .HasColumnType("text"); + + b.Property("StateExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StateHash") + .HasColumnType("text"); + + b.Property("SyncedEventsJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("MentorId") + .IsUnique(); + + b.HasIndex("StateHash") + .IsUnique(); + + b.ToTable("MentorCalendarConnections", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorChatMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ReadAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderUserId") + .HasColumnType("integer"); + + b.Property("SentAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("SenderUserId"); + + b.HasIndex("MentorBookingId", "Id"); + + b.HasIndex("MentorBookingId", "ReadAt", "SenderUserId"); + + b.ToTable("MentorChatMessages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreditGrantId") + .HasColumnType("bigint"); + + b.Property("EntryType") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId"); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("CreditGrantId", "EntryType"); + + b.HasIndex("MentorBookingId", "EntryType"); + + b.ToTable("MentorCreditEntries", null, t => + { + t.HasCheckConstraint("CK_MentorCreditEntry_Amount", "\"Amount\" <> 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AvailableQuantity") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("InitialQuantity") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("UserSubscriptionId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserSubscriptionId") + .IsUnique(); + + b.HasIndex("LearnerId", "ExpiresAtUtc"); + + b.HasIndex("LearnerId", "CertificateLevelId", "ExpiresAtUtc"); + + b.ToTable("MentorCreditGrants", null, t => + { + t.HasCheckConstraint("CK_MentorCreditGrant_PolicyVersion", "\"PolicyVersion\" > 0"); + + t.HasCheckConstraint("CK_MentorCreditGrant_Quantity", "\"InitialQuantity\" > 0 AND \"AvailableQuantity\" >= 0 AND \"AvailableQuantity\" <= \"InitialQuantity\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminDecision") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("AdminNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Category") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditRefunded") + .HasColumnType("boolean"); + + b.Property("EvidenceUrls") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("IsRefundApproved") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRespondedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorResponse") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RefundOperationKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ResolvedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ResolvedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId") + .HasDatabaseName("IX_MentorDisputes_LearnerId"); + + b.HasIndex("MentorBookingId") + .HasDatabaseName("IX_MentorDisputes_MentorBookingId"); + + b.HasIndex("MentorId") + .HasDatabaseName("IX_MentorDisputes_MentorId"); + + b.HasIndex("ResolvedByAdminId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorDisputes_Status"); + + b.ToTable("MentorDisputes", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDisputeHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("DisputeId") + .HasColumnType("integer"); + + b.Property("NewStatus") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("PreviousStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DisputeId") + .HasDatabaseName("IX_MentorDisputeHistories_DisputeId"); + + b.ToTable("MentorDisputeHistories", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorEarningEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("AttendanceApprovalId") + .HasColumnType("bigint"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("FormulaVersion") + .HasColumnType("integer"); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("GrossAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("JlptLevelCode") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("AttendanceApprovalId") + .IsUnique(); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.HasIndex("MentorUserId", "Status"); + + b.ToTable("MentorEarningEntries", t => + { + t.HasCheckConstraint("CK_MentorEarningEntry_Positive", "\"FrozenHourlyRate\" > 0 AND \"FrozenLevelCoefficient\" > 0 AND \"ApprovedEligibleMinutes\" > 0 AND \"ApprovedEligibleMinutes\" <= 90 AND \"GrossAmount\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorGroupPolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CancellationLeadHours") + .HasColumnType("integer"); + + b.Property("CheckoutHoldMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("DeletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedByAdminId") + .HasColumnType("integer"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("HomeworkDeadlineDays") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsArchivedRevision") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KpiReportingPeriodDays") + .HasColumnType("integer"); + + b.Property("LastAppliedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedByAdminId") + .HasColumnType("integer"); + + b.Property("LearnerTransferEnabled") + .HasColumnType("boolean"); + + b.Property("MaxLearners") + .HasColumnType("integer"); + + b.Property("MentorReplacementEnabled") + .HasColumnType("boolean"); + + b.Property("MentorReplacementLeadHours") + .HasColumnType("integer"); + + b.Property("MinimumPreparationDays") + .HasColumnType("integer"); + + b.Property("MinimumPublishedEnrollmentDays") + .HasColumnType("integer"); + + b.Property("PlacementAttemptLimit") + .HasColumnType("integer"); + + b.Property("RemediationCompletionThresholdPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("RemediationThresholdComparison") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("RequireAdminRemediationReview") + .HasColumnType("boolean"); + + b.Property("RequireOfficialExamEvidence") + .HasColumnType("boolean"); + + b.Property("ReschedulingLeadHours") + .HasColumnType("integer"); + + b.Property("RestMinutes") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("TransferAllowedAfterSourceStart") + .HasColumnType("boolean"); + + b.Property("TuitionPerSessionN2") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN3") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN4") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN5") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedByAdminId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("DeletedByAdminId"); + + b.HasIndex("EffectiveFromUtc"); + + b.HasIndex("IsActive") + .IsUnique() + .HasDatabaseName("IX_MentorGroupPolicies_SingleActive") + .HasFilter("\"IsActive\" = TRUE"); + + b.HasIndex("LastAppliedByAdminId"); + + b.HasIndex("UpdatedByAdminId"); + + b.HasIndex("Version") + .IsUnique() + .HasDatabaseName("IX_MentorGroupPolicies_LiveVersion") + .HasFilter("\"IsArchivedRevision\" = FALSE"); + + b.ToTable("MentorGroupPolicies", null, t => + { + t.HasCheckConstraint("CK_MentorGroupPolicy_Capacity", "\"MaxLearners\" BETWEEN 1 AND 50"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_CheckoutHold", "\"CheckoutHoldMinutes\" BETWEEN 1 AND 60"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Comparison", "\"RemediationThresholdComparison\" IN ('>', '>=')"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_EnrollmentDays", "\"MinimumPublishedEnrollmentDays\" BETWEEN 1 AND 180"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Evidence", "\"RequireOfficialExamEvidence\" AND \"RequireAdminRemediationReview\""); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Positive", "\"Version\" > 0 AND \"SessionMinutes\" > 0 AND \"RestMinutes\" >= 0 AND \"MinimumPreparationDays\" >= 1 AND \"CancellationLeadHours\" >= 0 AND \"ReschedulingLeadHours\" >= 0 AND \"HomeworkDeadlineDays\" > 0 AND \"PlacementAttemptLimit\" > 0 AND \"KpiReportingPeriodDays\" > 0"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Remediation", "\"RemediationCompletionThresholdPercent\" > 0 AND \"RemediationCompletionThresholdPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_ReplacementLead", "\"MentorReplacementLeadHours\" BETWEEN 0 AND 720"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_State", "\"Revision\" > 0 AND NOT (\"IsActive\" AND (\"IsArchivedRevision\" OR \"IsDeleted\"))"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_TransferAfterStart", "\"LearnerTransferEnabled\" OR NOT \"TransferAllowedAfterSourceStart\""); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Tuition", "\"TuitionPerSessionN5\" >= 0 AND \"TuitionPerSessionN4\" >= 0 AND \"TuitionPerSessionN3\" >= 0 AND \"TuitionPerSessionN2\" >= 0"); + }); + + b.HasData( + new + { + Id = 1, + CancellationLeadHours = 24, + CheckoutHoldMinutes = 10, + CreatedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + EffectiveFromUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + HomeworkDeadlineDays = 7, + IsActive = true, + IsArchivedRevision = false, + IsDeleted = false, + KpiReportingPeriodDays = 30, + LastAppliedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + LearnerTransferEnabled = true, + MaxLearners = 4, + MentorReplacementEnabled = true, + MentorReplacementLeadHours = 24, + MinimumPreparationDays = 1, + MinimumPublishedEnrollmentDays = 7, + PlacementAttemptLimit = 2, + RemediationCompletionThresholdPercent = 90m, + RemediationThresholdComparison = ">", + RequireAdminRemediationReview = true, + RequireOfficialExamEvidence = true, + ReschedulingLeadHours = 24, + RestMinutes = 15, + Revision = 1, + SessionMinutes = 90, + TransferAllowedAfterSourceStart = false, + TuitionPerSessionN2 = 110000m, + TuitionPerSessionN3 = 90000m, + TuitionPerSessionN4 = 75000m, + TuitionPerSessionN5 = 60000m, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorHourlyRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountPerHour") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ConfiguredByAdminId"); + + b.HasIndex("MentorUserId", "EffectiveFromUtc") + .IsUnique(); + + b.ToTable("MentorHourlyRates", t => + { + t.HasCheckConstraint("CK_MentorHourlyRate_Positive", "\"AmountPerHour\" > 0"); + + t.HasCheckConstraint("CK_MentorHourlyRate_Range", "\"EffectiveUntilUtc\" IS NULL OR \"EffectiveUntilUtc\" > \"EffectiveFromUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorOutboxEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AggregateId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("AggregateType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("AvailableAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeliveredAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EventKey") + .IsRequired() + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("EventVersion") + .HasColumnType("integer"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("EventKey") + .IsUnique(); + + b.HasIndex("DeliveredAtUtc", "AvailableAtUtc", "CreatedAtUtc"); + + b.ToTable("MentorOutboxEvents", null, t => + { + t.HasCheckConstraint("CK_MentorOutbox_Attempts", "\"Attempts\" >= 0"); + + t.HasCheckConstraint("CK_MentorOutbox_EventVersion", "\"EventVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("AttemptNumber") + .HasColumnType("integer"); + + b.Property("BatchId") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ConfirmedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("ErrorCode") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ErrorMessage") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceStorageKey") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExecutionMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("IdempotencyKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("InitiatedByAdminId") + .HasColumnType("integer"); + + b.Property("InternalStatus") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("LockedBankAccountId") + .HasColumnType("bigint"); + + b.Property("PayoutObligationId") + .HasColumnType("bigint"); + + b.Property("ProviderPayoutId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProviderStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("TransferReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ConfirmedByAdminId"); + + b.HasIndex("IdempotencyKey") + .IsUnique(); + + b.HasIndex("InitiatedByAdminId"); + + b.HasIndex("LockedBankAccountId"); + + b.HasIndex("PayoutObligationId") + .IsUnique() + .HasDatabaseName("IX_MentorPayoutAttempts_OneSucceededPerObligation") + .HasFilter("\"InternalStatus\" = 'Succeeded'"); + + b.HasIndex("TransferReference") + .IsUnique() + .HasDatabaseName("IX_MentorPayoutAttempts_SucceededTransferReference") + .HasFilter("\"TransferReference\" IS NOT NULL AND \"InternalStatus\" = 'Succeeded'"); + + b.HasIndex("PayoutObligationId", "AttemptNumber") + .IsUnique(); + + b.ToTable("MentorPayoutAttempts", t => + { + t.HasCheckConstraint("CK_MentorPayoutAttempt_ManualEvidence", "(\"ExecutionMethod\" <> 'ManualBankTransfer' OR \"InternalStatus\" <> 'Succeeded') OR (\"TransferReference\" IS NOT NULL AND \"EvidenceStorageKey\" IS NOT NULL)"); + + t.HasCheckConstraint("CK_MentorPayoutAttempt_Positive", "\"Amount\" > 0 AND \"AttemptNumber\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActiveAttemptId") + .HasColumnType("bigint"); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("LockedBankAccountId") + .HasColumnType("bigint"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("OrganizationPayoutAccountId") + .HasColumnType("bigint"); + + b.Property("PayableAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("SelectedMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SettledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SettledAttemptId") + .HasColumnType("bigint"); + + b.Property("SettledReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("LockedBankAccountId"); + + b.HasIndex("MentorUserId"); + + b.HasIndex("OrganizationPayoutAccountId"); + + b.HasIndex("PayrollPeriodId") + .IsUnique(); + + b.ToTable("MentorPayoutObligations", t => + { + t.HasCheckConstraint("CK_MentorPayoutObligation_Positive", "\"PayableAmount\" > 0"); + + t.HasCheckConstraint("CK_MentorPayoutObligation_Settlement", "(\"Status\" <> 'Paid') OR (\"SettledAttemptId\" IS NOT NULL AND \"SettledReference\" IS NOT NULL AND \"SettledAtUtc\" IS NOT NULL)"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollAdjustment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RelatedBookingId") + .HasColumnType("integer"); + + b.Property("RelatedEarningEntryId") + .HasColumnType("bigint"); + + b.Property("SignedAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.ToTable("MentorPayrollAdjustments", t => + { + t.HasCheckConstraint("CK_MentorPayrollAdjustment_NonZero", "\"SignedAmount\" <> 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollLine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EarningEntryId") + .HasColumnType("bigint"); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("LineAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("EarningEntryId") + .IsUnique(); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.ToTable("MentorPayrollLines", t => + { + t.HasCheckConstraint("CK_MentorPayrollLine_Positive", "\"LineAmount\" > 0 AND \"ApprovedEligibleMinutes\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovalNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ApprovedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("ClosedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("GrossPayableAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("Month") + .HasColumnType("integer"); + + b.Property("PreparedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PreparedByAdminId") + .HasColumnType("integer"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SupplementalReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("TotalAdjustmentsAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("TotalEarningsAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.Property("Year") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("PreparedByAdminId"); + + b.HasIndex("MentorUserId", "Year", "Month", "SequenceNumber", "Currency") + .IsUnique(); + + b.ToTable("MentorPayrollPeriods", t => + { + t.HasCheckConstraint("CK_MentorPayrollPeriod_Payable", "\"TotalEarningsAmount\" >= 0 AND \"GrossPayableAmount\" >= 0"); + + t.HasCheckConstraint("CK_MentorPayrollPeriod_Period", "\"Year\" >= 2020 AND \"Year\" <= 2100 AND \"Month\" >= 1 AND \"Month\" <= 12 AND \"SequenceNumber\" >= 1"); + + t.HasCheckConstraint("CK_MentorPayrollPeriod_Supplemental", "\"SequenceNumber\" = 1 OR (\"SupplementalReason\" IS NOT NULL AND length(trim(\"SupplementalReason\")) > 0)"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorProfile", b => + { + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Bio") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Expertise") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IntroductionVideoUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectionReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("VerificationDocumentUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VerificationStatus") + .IsConcurrencyToken() + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Workplace") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("YearsOfExperience") + .HasColumnType("integer"); + + b.HasKey("MentorId"); + + b.ToTable("MentorProfiles", (string)null); + + b.HasData( + new + { + MentorId = 900002, + Bio = "Chuyên gia tiếng Nhật với 8 năm kinh nghiệm giảng dạy JLPT N1, N2 và tiếng Nhật doanh nghiệp.", + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + Expertise = "Luyện thi JLPT N1-N2, Tiếng Nhật thương mại, Phỏng vấn xin việc", + IsDeleted = false, + JlptLevel = "N1", + ReviewedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + ReviewedByAdminName = "Admin System", + SubmittedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + VerificationStatus = "Approved", + Workplace = "Riki Nihongo Academy", + YearsOfExperience = 8 + }, + new + { + MentorId = 900003, + Bio = "Giảng viên tiếng Nhật bản xứ, chuyên sâu về phát âm và giao tiếp Kaiwa thực tế.", + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + Expertise = "Giao tiếp Kaiwa tự nhiên, Luyện phát âm chuẩn Tokyo, JLPT N3-N2", + IsDeleted = false, + JlptLevel = "N1", + ReviewedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + ReviewedByAdminName = "Admin System", + SubmittedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + VerificationStatus = "Approved", + Workplace = "Riki Nihongo Academy", + YearsOfExperience = 5 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("IsPublic") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRepliedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorReply") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModerationStatus") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId") + .HasDatabaseName("IX_MentorReviews_LearnerId"); + + b.HasIndex("MentorBookingId") + .IsUnique() + .HasDatabaseName("IX_MentorReviews_MentorBookingId"); + + b.HasIndex("MentorId", "IsPublic", "ModerationStatus") + .HasDatabaseName("IX_MentorReviews_Mentor_Public_Status"); + + b.ToTable("MentorReviews", null, t => + { + t.HasCheckConstraint("CK_MentorReview_Rating_Range", "\"Rating\" >= 1 AND \"Rating\" <= 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AutoPublish") + .HasColumnType("boolean"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("GeneratedThrough") + .HasColumnType("date"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("TimeZoneId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("MentorId", "PolicyVersion") + .IsUnique(); + + b.ToTable("MentorSchedules", null, t => + { + t.HasCheckConstraint("CK_MentorSchedule_PolicyVersion", "\"PolicyVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorScheduleRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DaypartCode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("LocalEnd") + .HasColumnType("time without time zone"); + + b.Property("LocalStart") + .HasColumnType("time without time zone"); + + b.Property("ScheduleId") + .HasColumnType("bigint"); + + b.Property("Weekday") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId", "Weekday", "DaypartCode", "EffectiveFrom") + .IsUnique(); + + b.ToTable("MentorScheduleRules", null, t => + { + t.HasCheckConstraint("CK_MentorScheduleRule_Daypart", "\"DaypartCode\" IN ('Morning', 'Noon', 'Afternoon', 'Evening')"); + + t.HasCheckConstraint("CK_MentorScheduleRule_Time", "\"LocalEnd\" > \"LocalStart\""); + + t.HasCheckConstraint("CK_MentorScheduleRule_Weekday", "\"Weekday\" BETWEEN 0 AND 6"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CourseDurationWeeks") + .HasColumnType("integer"); + + b.Property("CourseObjective") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("CoursePlanId") + .HasColumnType("integer"); + + b.Property("CourseTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpectedStartDate") + .HasColumnType("date"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("HiddenFromMentorAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHiddenFromMentorHistory") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastSavedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("OpenEnrollmentIdempotencyKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OpenedClassAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OptionalAttachmentsJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("OptionalNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("ProgramType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ReviewReason") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionDurationMinutes") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("SubmissionIdempotencyKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("WeeklySessionsJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CoursePlanId"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("ReviewedByAdminId"); + + b.HasIndex("MentorId", "OpenEnrollmentIdempotencyKey") + .IsUnique() + .HasDatabaseName("IX_MentorTeachingProposals_MentorId_OpenEnrollmentIdempotencyKey") + .HasFilter("\"OpenEnrollmentIdempotencyKey\" IS NOT NULL"); + + b.HasIndex("MentorId", "SubmissionIdempotencyKey") + .IsUnique() + .HasDatabaseName("IX_MentorTeachingProposals_MentorId_SubmissionIdempotencyKey") + .HasFilter("\"SubmissionIdempotencyKey\" IS NOT NULL"); + + b.HasIndex("Status", "SubmittedAtUtc"); + + b.HasIndex("MentorId", "Status", "UpdatedAtUtc"); + + b.ToTable("MentorTeachingProposals", null, t => + { + t.HasCheckConstraint("CK_MentorTeachingProposal_Duration", "\"CourseDurationWeeks\" BETWEEN 1 AND 104 AND \"SessionDurationMinutes\" BETWEEN 30 AND 240"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_ProgramType", "\"ProgramType\" IN ('StandardJlpt', 'IntensiveJlpt', 'ExamPrepJlpt', 'CustomJlpt')"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_Revision", "\"Revision\" > 0"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_Status", "\"Status\" IN ('Draft', 'PendingReview', 'ChangesRequested', 'Approved', 'OpenedClass', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposalEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(48) + .HasColumnType("character varying(48)"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ActorUserId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("FromStatus") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ProposalId") + .HasColumnType("integer"); + + b.Property("Reason") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("RevisionAfter") + .HasColumnType("integer"); + + b.Property("SnapshotJson") + .HasColumnType("jsonb"); + + b.Property("ToStatus") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("ProposalId", "CreatedAtUtc"); + + b.ToTable("MentorTeachingProposalEvents", null, t => + { + t.HasCheckConstraint("CK_MentorTeachingProposalEvent_RevisionAfter", "\"RevisionAfter\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingQualification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedByAdminId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("VerifiedByAdminId"); + + b.HasIndex("MentorUserId", "CertificateLevelId") + .IsUnique() + .HasFilter("\"IsActive\" = TRUE"); + + b.ToTable("MentorTeachingQualifications", t => + { + t.HasCheckConstraint("CK_MentorTeachingQualification_Revoked", "\"RevokedAtUtc\" IS NULL OR \"RevokedAtUtc\" >= \"VerifiedAtUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Date") + .HasColumnType("date"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Period") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorId", "Date", "Period") + .IsUnique() + .HasFilter("NOT \"IsDeleted\""); + + b.ToTable("MentorWeeklyAvailabilities", t => + { + t.HasCheckConstraint("CK_MentorWeeklyAvailability_Period", "\"Period\" IN ('Morning', 'Afternoon', 'Evening')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("AnswerKeyJson") + .HasColumnType("jsonb"); + + b.Property("AudioTranscript") + .HasColumnType("text"); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("ContentFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Difficulty") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("GroupSortOrder") + .HasColumnType("integer"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("InteractionDataJson") + .HasColumnType("jsonb"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("MockTestSectionId") + .HasColumnType("integer") + .HasColumnName("PracticeTestSectionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionsJson") + .HasColumnType("jsonb"); + + b.Property("ParentQuestionId") + .HasColumnType("integer"); + + b.Property("PassageId") + .HasColumnType("integer"); + + b.Property("PlaybackPolicyJson") + .HasColumnType("jsonb"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("QuestionGroupTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("QuestionIdentity") + .HasColumnType("uuid"); + + b.Property("QuestionText") + .IsRequired() + .HasColumnType("text"); + + b.Property("QuestionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("SingleChoice"); + + b.Property("QuestionVersion") + .HasColumnType("integer"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SkillMetadataJson") + .HasColumnType("jsonb"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceQuestionId") + .HasColumnType("integer"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("Manual"); + + b.Property("TagsJson") + .HasColumnType("jsonb"); + + b.Property("TemplateKind") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Topic") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.HasKey("Id"); + + b.HasIndex("ContentFingerprint"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("PassageId"); + + b.HasIndex("QuestionIdentity"); + + b.HasIndex("SourceQuestionId"); + + b.HasIndex("MockTestSectionId", "IsArchivedVersion"); + + b.HasIndex("CertificateLevelId", "LanguageSkillId", "PublishStatus", "IsArchivedVersion"); + + b.ToTable("MockQuestions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestionOption", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockQuestionId") + .HasColumnType("integer") + .HasColumnName("PracticeQuestionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionText") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockQuestionId"); + + b.ToTable("MockQuestionOptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("BlueprintPolicyJson") + .HasColumnType("jsonb"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ExamKind") + .HasColumnType("integer"); + + b.Property("FocusSkillId") + .HasColumnType("integer"); + + b.Property("IncludedSkillsJson") + .HasColumnType("jsonb"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsManagedWorkflow") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ParentExamId") + .HasColumnType("integer"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TagsJson") + .HasColumnType("jsonb"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserAccountId"); + + b.ToTable("MockTests"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAnswer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiExplanationGeneratedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AiExplanationInputJson") + .HasColumnType("jsonb"); + + b.Property("AiExplanationJson") + .HasColumnType("jsonb"); + + b.Property("AiExplanationVersion") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockQuestionId") + .HasColumnType("integer") + .HasColumnName("PracticeQuestionId"); + + b.Property("MockTestAttemptId") + .HasColumnType("integer") + .HasColumnName("PracticeTestAttemptId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ResponseJson") + .HasColumnType("jsonb"); + + b.Property("SelectedOptionId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockQuestionId"); + + b.HasIndex("SelectedOptionId"); + + b.HasIndex("MockTestAttemptId", "MockQuestionId") + .IsUnique(); + + b.ToTable("MockTestAnswers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttemptKind") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsPlacementAssessment") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("QuestionSnapshotJson") + .HasColumnType("text"); + + b.Property("StartedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalScore") + .HasColumnType("double precision"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StartedAt"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "AttemptKind") + .IsUnique() + .HasFilter("\"AttemptKind\" = 1 AND \"IsCompleted\" = false AND \"IsDeleted\" = false"); + + b.ToTable("MockTestAttempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateSectionId") + .HasColumnType("integer") + .HasColumnName("CertificationSectionId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DurationMinutes") + .HasColumnType("integer"); + + b.Property("Instructions") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer") + .HasColumnName("SkillId"); + + b.Property("MockTestId") + .HasColumnType("integer") + .HasColumnName("MockTestId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SectionPolicyJson") + .HasColumnType("jsonb"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateSectionId"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("MockTestId", "CertificateSectionId"); + + b.ToTable("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSectionResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CorrectCount") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockTestAttemptId") + .HasColumnType("integer") + .HasColumnName("MockTestAttemptId"); + + b.Property("MockTestSectionId") + .HasColumnType("integer") + .HasColumnName("MockTestSectionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ScorePercent") + .HasColumnType("double precision"); + + b.Property("TotalCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockTestSectionId"); + + b.HasIndex("MockTestAttemptId", "MockTestSectionId") + .IsUnique(); + + b.ToTable("MockTestSectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Note", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AnsweredAt") + .HasColumnType("timestamp without time zone"); + + b.Property("AuthorRole") + .IsRequired() + .HasColumnType("text"); + + b.Property("Content") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("Notes"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("NormalizedName") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_NotebookFolders_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("UserId", "NormalizedName") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("UserId", "IsDeleted", "SortOrder"); + + b.ToTable("NotebookFolders", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChecklistCompletedCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ChecklistTotalCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ContentFormatVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ContentJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'{\"type\":\"doc\",\"version\":1,\"blocks\":[]}'::jsonb"); + + b.Property("ContentPlainText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue(""); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FavoritedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastAutosavedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerNoteId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_NotebookPages_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("LearnerNoteId", "IsDeleted", "SortOrder"); + + b.HasIndex("UserId", "IsDeleted", "IsFavorite"); + + b.ToTable("NotebookPages", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DeliveredTokens") + .HasColumnType("text"); + + b.Property("IdempotencyKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("LinkUrl") + .HasColumnType("text"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.OrganizationPayoutAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountHolderName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("BankCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("BankName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ChannelCode") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("MaskedAccountNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ProviderAccountReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProviderType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelCode") + .IsUnique(); + + b.HasIndex("ConfiguredByAdminId"); + + b.ToTable("OrganizationPayoutAccounts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PassingScorePercent") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(70.0); + + b.Property("Scope") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("LessonQuickCheck"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("TopicId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("TopicId"); + + b.HasIndex("LessonId", "LanguageSkillId"); + + b.HasIndex("Scope", "CertificateLevelId"); + + b.HasIndex("Scope", "TopicId"); + + b.ToTable("PracticeExercises"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.Property("ScorePercent") + .HasColumnType("double precision"); + + b.Property("StartedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeExerciseId"); + + b.HasIndex("HomeworkAssignmentId", "PracticeExerciseId") + .IsUnique(); + + b.HasIndex("UserId", "PracticeExerciseId", "StartedAt"); + + b.ToTable("PracticeExerciseAttempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.Property("QuestionText") + .IsRequired() + .HasColumnType("text"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeExerciseId"); + + b.ToTable("PracticeQuestions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestionOption", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("PracticeQuestionId") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeQuestionId"); + + b.ToTable("PracticeQuestionOptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TextContent") + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserId", "Type", "SubmittedAt"); + + b.ToTable("PracticeSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.RecommendedLearningPath", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BaseActivePathId") + .HasColumnType("integer"); + + b.Property("ConfirmedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("GeneratedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsViewed") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PreviewExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StartingCertificateLevelId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SuggestionJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Summary") + .HasColumnType("text"); + + b.Property("TargetCertificateLevelId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasFilter("\"Status\" = 'Active'"); + + b.HasIndex("UserId", "GeneratedAt"); + + b.HasIndex("UserId", "Version") + .IsUnique(); + + b.ToTable("RecommendedLearningPaths"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcceptedReadingsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ArchivedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("AudioUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("BackText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)") + .HasDefaultValue(""); + + b.Property("CardType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("Vocabulary"); + + b.Property("ContextSnippet") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CorrectCount") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EaseFactor") + .HasColumnType("double precision"); + + b.Property("ExampleMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FrontText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasDefaultValue(""); + + b.Property("GrammarPatternId") + .HasColumnType("integer") + .HasColumnName("GrammarPointId"); + + b.Property("IncorrectCount") + .HasColumnType("integer"); + + b.Property("IntervalDays") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.Property("Lapses") + .HasColumnType("integer"); + + b.Property("LastReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerNoteEntryId") + .HasColumnType("integer") + .HasColumnName("VocabularyNoteEntryId"); + + b.Property("LearningState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("New"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("MasteredAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Meaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Mode") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NextReviewDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NormalizedContentKey") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(300) + .HasColumnType("character varying(300)") + .HasDefaultValue(""); + + b.Property("PersonalNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Reading") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Repetitions") + .HasColumnType("integer"); + + b.Property("Revision") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourceLabel") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceLinksJson") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("Manual"); + + b.Property("SourceVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SrsCardTemplateId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Active"); + + b.Property("SuspendedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SynonymsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.Property("WritingCorrectStrokeCount") + .HasColumnType("integer"); + + b.Property("WritingPracticeMode") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("WritingScore") + .HasColumnType("integer"); + + b.Property("WritingScoreUpdatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("WritingTotalStrokeCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("LearnerNoteEntryId"); + + b.HasIndex("LessonId"); + + b.HasIndex("SrsCardTemplateId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("UserId", "NextReviewDate"); + + b.HasIndex("UserId", "GrammarPatternId", "Mode") + .IsUnique() + .HasFilter("\"GrammarPointId\" IS NOT NULL"); + + b.HasIndex("UserId", "KanjiId", "Mode") + .IsUnique() + .HasFilter("\"KanjiEntryId\" IS NOT NULL"); + + b.HasIndex("UserId", "NormalizedContentKey", "Mode") + .IsUnique() + .HasFilter("\"NormalizedContentKey\" <> '' AND \"IsDeleted\" = false"); + + b.HasIndex("UserId", "VocabularyId", "Mode") + .IsUnique() + .HasFilter("\"VocabularyId\" IS NOT NULL"); + + b.HasIndex("UserId", "Status", "LearningState", "NextReviewDate"); + + b.ToTable("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IdempotencyKey") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NewEaseFactor") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(2.5); + + b.Property("NewIntervalDays") + .HasColumnType("integer"); + + b.Property("NewState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Learning"); + + b.Property("PreviousEaseFactor") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(2.5); + + b.Property("PreviousIntervalDays") + .HasColumnType("integer"); + + b.Property("PreviousState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("New"); + + b.Property("Quality") + .HasColumnType("integer"); + + b.Property("Rating") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("ResponseTimeMs") + .HasColumnType("integer"); + + b.Property("ReviewCardId") + .HasColumnType("integer") + .HasColumnName("ReviewItemId"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SessionReference") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("StudyMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("flip"); + + b.Property("UserAnswer") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("SessionReference"); + + b.HasIndex("ReviewCardId", "IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.HasIndex("ReviewCardId", "ReviewedAt"); + + b.ToTable("ReviewHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsCardTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcceptedReadingsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("AudioUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("BackText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CardType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FrontText") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("KanjiId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("Meaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NormalizedContentKey") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Reading") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ReviewNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedByUserId") + .HasColumnType("integer"); + + b.Property("SynonymsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UsageNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("LessonId"); + + b.HasIndex("NormalizedContentKey"); + + b.HasIndex("ReviewedByAdminId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("SubmittedByUserId", "Status"); + + b.HasIndex("Status", "JlptLevel", "CardType"); + + b.ToTable("SrsCardTemplates"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsReviewSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CompletedCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DeadlineAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("FilterCardType") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("FilterJlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("FilterLearningState") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("FilterSourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ForgotCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastActivityAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ProcessedStepKeysJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)") + .HasDefaultValue("[]"); + + b.Property("QueueCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("RememberedCount") + .HasColumnType("integer"); + + b.Property("RequestedCount") + .HasColumnType("integer"); + + b.Property("RetryCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("ReviewedCount") + .HasColumnType("integer"); + + b.Property("SelectionScope") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SessionKey") + .HasColumnType("uuid"); + + b.Property("SessionKind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Scheduled"); + + b.Property("ShuffleEnabled") + .HasColumnType("boolean"); + + b.Property("StartedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StudyMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TotalInitialCards") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SessionKey") + .IsUnique(); + + b.HasIndex("UserId", "Status", "LastActivityAtUtc"); + + b.HasIndex("UserId", "SessionKind", "Status", "LastActivityAtUtc"); + + b.ToTable("SrsReviewSessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CancellationReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Capacity") + .HasColumnType("integer"); + + b.Property("CapacitySnapshot") + .HasColumnType("integer"); + + b.Property("CourseDurationWeeks") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("EndsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("EnrollmentClosedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentClosesAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentOpensAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SourceProposalId") + .HasColumnType("integer"); + + b.Property("StartsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TotalTuitionSnapshot") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionSnapshot") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("TuitionSnapshotAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PlanId"); + + b.HasIndex("SourceProposalId") + .IsUnique() + .HasFilter("\"SourceProposalId\" IS NOT NULL"); + + b.ToTable("StudyCohorts", null, t => + { + t.HasCheckConstraint("CK_StudyCohort_Capacity", "\"Capacity\" > 0"); + + t.HasCheckConstraint("CK_StudyCohort_DurationWeeks", "\"CourseDurationWeeks\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortMentorAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AffectedSessionCount") + .HasColumnType("integer"); + + b.Property("AssignedById") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromSessionNumber") + .HasColumnType("integer"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("ImpactSnapshot") + .IsRequired() + .HasColumnType("text"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("PreviousMentorId") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.HasKey("Id"); + + b.HasIndex("AssignedById"); + + b.HasIndex("IdempotencyKey") + .IsUnique(); + + b.HasIndex("MentorId"); + + b.HasIndex("PolicyId"); + + b.HasIndex("PreviousMentorId"); + + b.HasIndex("CohortId", "Id"); + + b.ToTable("StudyCohortMentorAssignments", null, t => + { + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_DifferentMentor", "\"MentorId\" <> \"PreviousMentorId\""); + + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_Reason", "length(btrim(\"Reason\")) > 0"); + + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_Sessions", "\"EffectiveFromSessionNumber\" > 0 AND \"AffectedSessionCount\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActualEndedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ActualStartedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AvailabilityId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("Number") + .HasColumnType("integer"); + + b.Property("Status") + .IsConcurrencyToken() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("AvailabilityId") + .IsUnique(); + + b.HasIndex("CohortId", "Number") + .IsUnique(); + + b.ToTable("StudyCohortSessions", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("CancellationReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CapacitySnapshot") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CheckoutUrl") + .HasColumnType("text"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(3) + .HasColumnType("character varying(3)"); + + b.Property("DurationMonths") + .HasColumnType("integer"); + + b.Property("EndsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MaximumAbsencePercent") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MinimumHomeworkPercent") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("OrderSnapshot") + .HasColumnType("text"); + + b.Property("PaymentConfirmedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentReference") + .HasColumnType("text"); + + b.Property("PaymentReviewReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PaymentStatus") + .IsRequired() + .HasColumnType("text"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("PlanRevision") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("ProviderPaymentReference") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("PurchaseKey") + .HasColumnType("uuid"); + + b.Property("RefundedAmount") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("RefundedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RetakeClaimDays") + .HasColumnType("integer"); + + b.Property("RetakeOfId") + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("SessionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("Individual"); + + b.Property("SessionsPerWeek") + .HasColumnType("integer"); + + b.Property("StartsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.Property("TransferredAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("TransferredFromCourseId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CohortId"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PlanId"); + + b.HasIndex("ProviderPaymentReference") + .IsUnique() + .HasDatabaseName("IX_StudyCourses_ProviderPaymentReference") + .HasFilter("\"ProviderPaymentReference\" IS NOT NULL"); + + b.HasIndex("RetakeOfId") + .IsUnique(); + + b.HasIndex("TransferredFromCourseId") + .IsUnique() + .HasFilter("\"TransferredFromCourseId\" IS NOT NULL"); + + b.HasIndex("CohortId", "LearnerId") + .IsUnique() + .HasDatabaseName("IX_StudyCourses_Cohort_ActiveLearner") + .HasFilter("\"CohortId\" IS NOT NULL AND \"Status\" = 'Active'"); + + b.HasIndex("LearnerId", "PurchaseKey") + .IsUnique(); + + b.ToTable("StudyCourses", null, t => + { + t.HasCheckConstraint("CK_StudyCourses_RefundedAmount", "\"RefundedAmount\" >= 0 AND \"RefundedAmount\" <= \"Amount\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseHomework", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("DueAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Feedback") + .HasColumnType("text"); + + b.Property("Instructions") + .IsRequired() + .HasColumnType("text"); + + b.Property("Passed") + .HasColumnType("boolean"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Submission") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.ToTable("StudyCourseHomework", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCoursePlan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Capacity") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("DurationMonths") + .HasColumnType("integer"); + + b.Property("IsPublished") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Price") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("RetakeClaimDays") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("SessionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("Individual"); + + b.Property("SessionsPerWeek") + .HasColumnType("integer"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.ToTable("StudyCoursePlans", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Attempt") + .HasColumnType("integer"); + + b.Property("AvailabilityId") + .HasColumnType("integer"); + + b.Property("ConfirmedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ConfirmedById") + .HasColumnType("integer"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("MeetingUrl") + .HasColumnType("text"); + + b.Property("Note") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Number") + .HasColumnType("integer"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("AvailabilityId"); + + b.HasIndex("CourseId", "Number", "Attempt") + .IsUnique(); + + b.ToTable("StudyCourseSessions", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiGradingQuota") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DurationDays") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsPopular") + .HasColumnType("boolean"); + + b.Property("IsTrial") + .HasColumnType("boolean"); + + b.Property("MeetingSessionCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PlanCategory") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("self_study"); + + b.Property("Price") + .HasColumnType("decimal(18,0)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.ToTable("SubscriptionPlans", t => + { + t.HasCheckConstraint("CK_SubscriptionPlans_AiGradingQuota", "\"AiGradingQuota\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_DurationDays", "\"DurationDays\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_Price", "\"Price\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_SortOrder", "\"SortOrder\" >= 0"); + }); + + b.HasData( + new + { + Id = 1, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 1 tuần.", + DurationDays = 7, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 1 tuần", + PlanCategory = "self_study", + Price = 1000m, + Revision = 1, + SortOrder = 6 + }, + new + { + Id = 2, + AiGradingQuota = 2, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 2 tuần.", + DurationDays = 14, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 2 tuần", + PlanCategory = "self_study", + Price = 1000m, + Revision = 1, + SortOrder = 5 + }, + new + { + Id = 3, + AiGradingQuota = 3, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 3 tuần.", + DurationDays = 21, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 3 tuần", + PlanCategory = "self_study", + Price = 2000m, + Revision = 1, + SortOrder = 4 + }, + new + { + Id = 4, + AiGradingQuota = 5, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 1 tháng.", + DurationDays = 30, + IsActive = true, + IsDeleted = false, + IsPopular = true, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 1 tháng", + PlanCategory = "self_study", + Price = 2000m, + Revision = 1, + SortOrder = 3 + }, + new + { + Id = 5, + AiGradingQuota = 10, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 2 tháng.", + DurationDays = 60, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 2 tháng", + PlanCategory = "self_study", + Price = 3000m, + Revision = 1, + SortOrder = 2 + }, + new + { + Id = 6, + AiGradingQuota = 15, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 3 tháng.", + DurationDays = 90, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 3 tháng", + PlanCategory = "self_study", + Price = 3000m, + Revision = 1, + SortOrder = 1 + }, + new + { + Id = 7, + AiGradingQuota = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Gói demo gồm 12 buổi ôn luyện 1-1 với Mentor, thời hạn 90 ngày. Dữ liệu thanh toán demo được seed để kiểm thử đặt lịch trên frontend.", + DurationDays = 90, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 12, + Name = "Meeting 1-1 với Mentor - 12 buổi", + PlanCategory = "mentor_legacy", + Price = 1000m, + Revision = 1, + SortOrder = 7 + }, + new + { + Id = 8101, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt luyện nói và chấm phát âm tiếng Nhật bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Luyện nói AI - 1 lượt", + PlanCategory = "speaking", + Price = 1000m, + Revision = 1, + SortOrder = 10 + }, + new + { + Id = 8102, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt chấm bài viết tiếng Nhật bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Luyện viết AI - 1 lượt", + PlanCategory = "writing", + Price = 1000m, + Revision = 1, + SortOrder = 11 + }, + new + { + Id = 8103, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt giải thích chi tiết đáp án đề thi thử bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Giải thích đáp án AI - 1 lượt", + PlanCategory = "ai_grading", + Price = 1000m, + Revision = 1, + SortOrder = 12 + }, + new + { + Id = 8104, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt tạo lộ trình học cá nhân hóa bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Lộ trình học AI - 1 lượt", + PlanCategory = "learning_path", + Price = 1000m, + Revision = 1, + SortOrder = 13 + }, + new + { + Id = 8105, + AiGradingQuota = 0, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một buổi ôn luyện với mentor.", + DurationDays = 30, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 1, + Name = "Mentor - 1 buổi", + PlanCategory = "mentor_legacy", + Price = 1000m, + Revision = 1, + SortOrder = 14 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearningObjectives") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StageCode") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId", "SortOrder"); + + b.ToTable("Topics"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssessedCertificateLevelId") + .HasColumnType("integer"); + + b.Property("AvatarUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CurrentStreak") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutes") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutesMax") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutesMin") + .HasColumnType("integer"); + + b.Property("DeclaredJlptCertificateCode") + .HasColumnType("text"); + + b.Property("Email") + .HasColumnType("text"); + + b.Property("EmailNotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("FirebaseUid") + .HasColumnType("text"); + + b.Property("FirstName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("GoogleSubject") + .IsConcurrencyToken() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsEmailVerified") + .HasColumnType("boolean"); + + b.Property("IsPhoneVerified") + .HasColumnType("boolean"); + + b.Property("LastName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LastStudyDate") + .HasColumnType("timestamp without time zone"); + + b.Property("LearningGoalVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("LearningMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LongestStreak") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NotificationPreferencesJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("PendingEmail") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PendingEmailRequestedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("PhoneNumber") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PlacementDecision") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SelfDeclaredCertificateLevelId") + .HasColumnType("integer"); + + b.Property("StartingCertificateLevelId") + .HasColumnType("integer"); + + b.Property("StudyTimePreference") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("SystemNotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("TargetCertificateLevelId") + .HasColumnType("integer") + .HasColumnName("TargetCertificationLevelId"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TokenVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("AssessedCertificateLevelId"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("GoogleSubject") + .IsUnique(); + + b.HasIndex("SelfDeclaredCertificateLevelId"); + + b.HasIndex("StartingCertificateLevelId"); + + b.HasIndex("TargetCertificateLevelId"); + + b.ToTable("Users"); + + b.HasData( + new + { + Id = 900001, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "admin@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Admin", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "System", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 91, 215, 217, 54, 239, 206, 181, 216, 143, 33, 82, 211, 9, 70, 197, 173, 197, 0, 72, 71, 59, 150, 46, 114, 96, 137, 52, 174, 137, 29, 196, 61, 50, 254, 249, 101, 114, 92, 149, 32, 55, 127, 205, 126, 216, 147, 197, 192, 248, 173, 158, 92, 104, 42, 195, 107, 150, 15, 3, 74, 103, 104, 3, 229 }, + PasswordSalt = new byte[] { 61, 240, 150, 172, 239, 48, 224, 17, 192, 54, 50, 58, 91, 100, 55, 168, 18, 69, 137, 112, 110, 59, 180, 37, 201, 241, 143, 238, 139, 33, 128, 70, 87, 158, 235, 219, 229, 184, 94, 72, 41, 160, 160, 197, 158, 217, 128, 188, 156, 255, 147, 13, 151, 37, 133, 164, 9, 252, 175, 124, 21, 15, 152, 196 }, + PlacementDecision = "NotTaken", + Role = "Admin", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900002, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "mentor1@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Mentor", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "One", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 17, 253, 106, 25, 89, 176, 204, 31, 142, 252, 245, 31, 64, 101, 213, 135, 164, 116, 40, 46, 173, 175, 8, 0, 69, 101, 65, 4, 90, 25, 176, 223, 153, 237, 220, 94, 55, 133, 227, 181, 70, 97, 155, 122, 50, 139, 216, 136, 88, 52, 76, 98, 250, 64, 52, 71, 146, 221, 225, 137, 106, 6, 178, 239 }, + PasswordSalt = new byte[] { 233, 77, 244, 252, 171, 97, 38, 140, 50, 138, 10, 54, 122, 165, 186, 85, 129, 82, 49, 10, 98, 44, 165, 57, 50, 7, 238, 166, 142, 224, 94, 49, 134, 226, 247, 110, 154, 139, 99, 204, 95, 39, 171, 235, 212, 26, 217, 87, 139, 118, 253, 125, 241, 255, 57, 22, 140, 171, 11, 168, 174, 202, 32, 17 }, + PlacementDecision = "NotTaken", + Role = "Mentor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900003, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "mentor2@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Mentor", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Two", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 93, 130, 109, 171, 238, 187, 245, 15, 202, 89, 247, 220, 95, 192, 246, 138, 5, 75, 250, 28, 208, 28, 51, 79, 127, 28, 214, 237, 93, 221, 108, 26, 152, 66, 73, 65, 11, 147, 154, 102, 113, 49, 51, 24, 51, 197, 248, 254, 22, 98, 87, 249, 250, 104, 131, 74, 16, 18, 179, 200, 3, 3, 79, 47 }, + PasswordSalt = new byte[] { 240, 155, 254, 183, 129, 162, 74, 247, 41, 9, 67, 242, 128, 8, 226, 85, 5, 104, 104, 72, 101, 75, 130, 95, 47, 101, 116, 89, 207, 23, 119, 178, 38, 180, 185, 145, 58, 115, 14, 30, 85, 216, 169, 133, 94, 115, 11, 117, 96, 87, 227, 240, 204, 48, 51, 144, 170, 248, 167, 56, 175, 194, 253, 135 }, + PlacementDecision = "NotTaken", + Role = "Mentor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900004, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "author1@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Content", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Author One", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 168, 249, 82, 144, 178, 145, 94, 164, 34, 152, 2, 74, 204, 105, 84, 145, 96, 199, 153, 136, 110, 82, 114, 113, 22, 139, 117, 143, 50, 239, 197, 4, 51, 189, 137, 48, 175, 14, 104, 164, 218, 249, 148, 217, 33, 44, 202, 128, 237, 183, 110, 228, 185, 36, 209, 254, 183, 182, 55, 1, 78, 16, 234, 50 }, + PasswordSalt = new byte[] { 19, 216, 84, 143, 3, 184, 50, 39, 209, 137, 149, 82, 224, 206, 6, 240, 237, 242, 172, 27, 55, 92, 242, 101, 149, 76, 104, 38, 176, 43, 40, 8, 102, 202, 146, 224, 62, 43, 147, 132, 2, 158, 81, 170, 29, 103, 76, 248, 101, 105, 213, 205, 32, 51, 59, 39, 221, 11, 135, 250, 193, 8, 78, 219 }, + PlacementDecision = "NotTaken", + Role = "ContentAuthor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900005, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "author2@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Content", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Author Two", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 189, 121, 9, 1, 230, 137, 43, 239, 79, 56, 195, 196, 66, 116, 42, 1, 137, 55, 54, 249, 55, 231, 79, 224, 182, 182, 199, 133, 100, 39, 138, 5, 223, 215, 48, 46, 60, 214, 49, 88, 42, 186, 232, 116, 237, 89, 55, 144, 4, 78, 215, 231, 237, 220, 96, 225, 202, 97, 61, 165, 246, 28, 126, 198 }, + PasswordSalt = new byte[] { 66, 178, 77, 56, 234, 206, 29, 78, 136, 190, 160, 142, 226, 249, 14, 17, 26, 101, 167, 36, 193, 55, 150, 94, 239, 81, 69, 54, 81, 171, 80, 22, 208, 38, 242, 2, 55, 171, 64, 38, 48, 224, 36, 216, 133, 132, 147, 100, 174, 32, 65, 134, 128, 35, 50, 138, 204, 59, 167, 96, 11, 128, 101, 102 }, + PlacementDecision = "NotTaken", + Role = "ContentAuthor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900006, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Meeting", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Test Learner", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 9, 206, 219, 58, 155, 234, 107, 145, 121, 174, 134, 51, 96, 253, 64, 216, 157, 114, 92, 36, 123, 206, 67, 217, 207, 166, 54, 71, 254, 251, 156, 200, 185, 110, 198, 135, 221, 146, 243, 40, 237, 229, 16, 133, 163, 161, 156, 79, 138, 103, 85, 25, 114, 81, 99, 182, 25, 73, 212, 198, 212, 192, 54, 129 }, + PasswordSalt = new byte[] { 231, 202, 97, 95, 11, 9, 242, 47, 62, 77, 67, 36, 170, 78, 120, 81, 56, 69, 47, 36, 209, 212, 107, 244, 15, 34, 189, 110, 57, 66, 205, 213, 224, 19, 245, 192, 104, 146, 130, 44, 54, 107, 2, 15, 109, 136, 118, 220, 228, 44, 110, 219, 31, 100, 161, 164, 63, 231, 196, 79, 120, 106, 181, 71 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900007, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner2.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Linh", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Nguyen", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 217, 79, 50, 159, 85, 88, 67, 15, 23, 182, 103, 80, 220, 85, 86, 173, 204, 186, 57, 67, 183, 165, 253, 243, 150, 250, 150, 190, 122, 252, 55, 169, 85, 236, 69, 106, 19, 219, 244, 42, 239, 30, 189, 176, 52, 47, 30, 28, 125, 31, 162, 255, 61, 3, 238, 201, 168, 88, 161, 42, 216, 86, 172, 219 }, + PasswordSalt = new byte[] { 85, 97, 108, 158, 219, 70, 81, 106, 73, 23, 205, 163, 105, 159, 117, 19, 175, 147, 178, 99, 112, 116, 163, 243, 109, 178, 129, 229, 245, 175, 91, 174, 66, 198, 122, 88, 80, 68, 160, 64, 85, 118, 105, 41, 135, 89, 49, 160, 120, 13, 116, 148, 255, 27, 157, 207, 106, 203, 127, 74, 19, 61, 148, 120 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900008, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner3.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Minh", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Tran", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 84, 97, 164, 196, 63, 151, 182, 39, 139, 242, 152, 22, 179, 33, 174, 113, 0, 236, 253, 114, 234, 242, 209, 76, 196, 162, 143, 195, 180, 3, 178, 193, 205, 230, 18, 114, 49, 151, 198, 217, 254, 21, 94, 176, 146, 214, 235, 122, 28, 241, 164, 161, 4, 161, 209, 38, 102, 179, 31, 107, 157, 25, 35, 63 }, + PasswordSalt = new byte[] { 26, 188, 78, 205, 57, 115, 100, 129, 148, 135, 165, 205, 148, 203, 245, 36, 244, 177, 9, 104, 120, 140, 21, 164, 36, 75, 122, 51, 115, 69, 174, 180, 120, 155, 62, 37, 97, 227, 212, 134, 200, 7, 66, 255, 219, 10, 140, 149, 67, 86, 164, 170, 142, 165, 181, 103, 47, 100, 238, 24, 178, 29, 171, 226 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900009, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner4.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Hoang", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Pham", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 42, 30, 236, 129, 234, 192, 63, 84, 148, 163, 154, 246, 107, 147, 189, 95, 33, 141, 196, 67, 181, 51, 157, 136, 93, 228, 237, 165, 164, 49, 4, 146, 87, 84, 9, 47, 28, 59, 33, 130, 37, 63, 43, 229, 8, 178, 123, 74, 61, 159, 235, 68, 217, 51, 225, 29, 201, 104, 44, 152, 53, 255, 199, 28 }, + PasswordSalt = new byte[] { 83, 214, 138, 3, 142, 91, 229, 97, 238, 61, 48, 237, 80, 82, 112, 249, 166, 81, 53, 95, 170, 120, 13, 87, 113, 159, 60, 37, 75, 229, 226, 107, 229, 89, 60, 57, 109, 196, 235, 81, 145, 154, 110, 120, 141, 13, 142, 77, 41, 132, 58, 80, 154, 57, 226, 168, 176, 251, 113, 167, 242, 139, 7, 177 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserDeviceToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceIdentifier") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FcmToken") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastSeenAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("FcmToken") + .HasDatabaseName("IX_UserDeviceTokens_FcmToken"); + + b.HasIndex("UserId", "DeviceIdentifier") + .HasDatabaseName("IX_UserDeviceTokens_UserId_DeviceIdentifier"); + + b.HasIndex("UserId", "IsActive") + .HasDatabaseName("IX_UserDeviceTokens_UserId_IsActive"); + + b.ToTable("UserDeviceTokens", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSrsPreference", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AutoEnrollAfterLesson") + .HasColumnType("boolean"); + + b.Property("AutoPlayAudio") + .HasColumnType("boolean"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DailyNewLimit") + .HasColumnType("integer"); + + b.Property("DailyReminderEnabled") + .HasColumnType("boolean"); + + b.Property("DailyReviewLimit") + .HasColumnType("integer"); + + b.Property("EmailReminderEnabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastReminderSentAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastReminderSentLocalDate") + .HasColumnType("date"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PreferredLocale") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("PreferredReviewMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReminderDaysJson") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ReminderFrequency") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("ReminderHour") + .HasColumnType("integer"); + + b.Property("ReminderMinute") + .HasColumnType("integer"); + + b.Property("ShowFuriganaHint") + .HasColumnType("boolean"); + + b.Property("TimezoneId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.HasIndex("DailyReminderEnabled", "LastReminderSentLocalDate"); + + b.ToTable("UserSrsPreferences"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiGradingQuota") + .HasColumnType("integer"); + + b.Property("AiGradingUsedCount") + .HasColumnType("integer"); + + b.Property("AmountPaid") + .HasColumnType("decimal(18,2)"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DurationDaysSnapshot") + .HasColumnType("integer"); + + b.Property("EndDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MeetingSessionsIncluded") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("MeetingSessionsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorPracticeOutcomeJson") + .HasColumnType("text"); + + b.Property("MentorReviewCompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorReviewPlan") + .HasMaxLength(6000) + .HasColumnType("character varying(6000)"); + + b.Property("MentorReviewSessionAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PaymentTransactionId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PendingMentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("PendingMentorQuestion") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PlanCategorySnapshot") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PlanNameSnapshot") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PlanRevisionSnapshot") + .HasColumnType("integer"); + + b.Property("PurchasedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StartDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SubscriptionPlanId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PendingMentorAvailabilityId"); + + b.HasIndex("SubscriptionPlanId"); + + b.HasIndex("UserId", "PaymentStatus", "EndDate"); + + b.ToTable("UserSubscriptions"); + + b.HasData( + new + { + Id = 990001, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 90, + EndDate = new DateTime(2099, 12, 31, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS", + PlanCategorySnapshot = "mentor_legacy", + PlanNameSnapshot = "Meeting 1-1 với Mentor - 12 buổi", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900006, + Version = 0u + }, + new + { + Id = 990002, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-2", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900007, + Version = 0u + }, + new + { + Id = 990003, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-3", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900008, + Version = 0u + }, + new + { + Id = 990004, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-4", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900009, + Version = 0u + }, + new + { + Id = 990005, + AiGradingQuota = 15, + AiGradingUsedCount = 0, + AmountPaid = 3000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 90, + EndDate = new DateTime(2099, 12, 31, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 0, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-FULL-ACCESS-SELF-STUDY", + PlanCategorySnapshot = "self_study", + PlanNameSnapshot = "Tự học tiếng Nhật - 3 tháng", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 6, + UserId = 900006, + Version = 0u + }, + new + { + Id = 990006, + AiGradingQuota = 1, + AiGradingUsedCount = 0, + AmountPaid = 1000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 0, + IsDeleted = false, + MeetingSessionsIncluded = 0, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-FULL-ACCESS-LEARNING-PATH", + PlanCategorySnapshot = "learning_path", + PlanNameSnapshot = "Mua 1 lượt AI đề xuất lộ trình", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 8104, + UserId = 900006, + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleSentence") + .HasColumnType("text"); + + b.Property("ExampleSentenceMeaning") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Meaning") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Reading") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Word") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("Word", "Reading"); + + b.ToTable("Vocabularies"); + }); + + modelBuilder.Entity("FeatureSubscriptionPlan", b => + { + b.HasOne("RikiPath.Domain.Entities.Feature", null) + .WithMany() + .HasForeignKey("FeaturesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.SubscriptionPlan", null) + .WithMany() + .HasForeignKey("SubscriptionPlansId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AiCreditTopUp", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("AiCreditTopUps") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateType", "CertificateType") + .WithMany("Levels") + .HasForeignKey("CertificateTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateType"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "Attempt") + .WithMany() + .HasForeignKey("AttemptId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Enrollment") + .WithMany() + .HasForeignKey("EnrollmentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.ClassQuiz", "Quiz") + .WithMany("Assignments") + .HasForeignKey("QuizId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Attempt"); + + b.Navigation("Enrollment"); + + b.Navigation("Learner"); + + b.Navigation("Quiz"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("DecidedById") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("Course"); + + b.Navigation("CourseSession"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaintEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortComplaint", "Complaint") + .WithMany("History") + .HasForeignKey("ComplaintId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Complaint"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortEnrollmentEntitlement", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "StudyCohort") + .WithMany() + .HasForeignKey("StudyCohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Learner"); + + b.Navigation("Plan"); + + b.Navigation("StudyCohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortLearningFeedback", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("RespondedById") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Course"); + + b.Navigation("CourseSession"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortMentorReview", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cohort"); + + b.Navigation("Course"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "RequestedBy") + .WithMany() + .HasForeignKey("RequestedById") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("ReviewedById") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("RequestedBy"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequestEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortScheduleRequest", "Request") + .WithMany("History") + .HasForeignKey("RequestId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Request"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "DestinationCourse") + .WithMany() + .HasForeignKey("DestinationCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", null) + .WithMany() + .HasForeignKey("PolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "RequestedTargetCohort") + .WithMany() + .HasForeignKey("RequestedTargetCohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("ReviewedById") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "SourceCohort") + .WithMany() + .HasForeignKey("SourceCohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "SourceCourse") + .WithMany() + .HasForeignKey("SourceCourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "TargetCohort") + .WithMany() + .HasForeignKey("TargetCohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("DestinationCourse"); + + b.Navigation("Learner"); + + b.Navigation("RequestedTargetCohort"); + + b.Navigation("SourceCohort"); + + b.Navigation("SourceCourse"); + + b.Navigation("TargetCohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequestEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortTransferRequest", "Request") + .WithMany("History") + .HasForeignKey("RequestId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Request"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentApprovalRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "SubmittedBy") + .WithMany() + .HasForeignKey("SubmittedByUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("SubmittedBy"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAudioTranscription", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CreatedByUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentBankItem", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Owner") + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentLevelMapping", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("ContentLevelMappings") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("ContentLevelMappings") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("ContentLevelMappings") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("ContentLevelMappings") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("CertificateLevel"); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("Passages") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockTestSection"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseAuditEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Audit") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseRetakeRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("RetakeRequests") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseScheduleRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.EmailVerification", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "User") + .WithMany("EmailVerifications") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GradingResult", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkSubmission") + .WithOne("GradingResult") + .HasForeignKey("RikiPath.Domain.Entities.GradingResult", "HomeworkSubmissionId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.PracticeSubmission", "PracticeSubmission") + .WithOne("GradingResult") + .HasForeignKey("RikiPath.Domain.Entities.GradingResult", "PracticeSubmissionId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("HomeworkSubmission"); + + b.Navigation("PracticeSubmission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredGrammarPatterns") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "StudyCourse") + .WithMany() + .HasForeignKey("StudyCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + + b.Navigation("StudyCourse"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentAttachment", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("Attachments") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentExercise", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("Exercises") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany() + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("PracticeExercise"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentLesson", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("HomeworkAssignmentLessons") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("HomeworkAssignmentLessons") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithOne("Submission") + .HasForeignKey("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("Learner"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmissionFile", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkSubmission") + .WithMany("Files") + .HasForeignKey("HomeworkSubmissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkSubmission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptLevelPayCoefficient", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("ConfiguredByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.HasOne("RikiPath.Domain.Entities.KanaCharacter", "KanaCharacter") + .WithMany("PracticeCards") + .HasForeignKey("KanaCharacterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("KanaCharacter"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.KanaWritingPracticeCard", "Card") + .WithMany("Histories") + .HasForeignKey("KanaWritingPracticeCardId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Card"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredKanjis") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerEssay", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LearnerEssays") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerFeedback", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Learner"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerHighlight", b => + { + b.HasOne("RikiPath.Domain.Entities.LearnerNoteEntry", "LinkedNoteEntry") + .WithMany() + .HasForeignKey("LinkedNoteEntryId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.ReviewCard", "LinkedReviewCard") + .WithMany() + .HasForeignKey("LinkedReviewCardId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LinkedNoteEntry"); + + b.Navigation("LinkedReviewCard"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.HasOne("RikiPath.Domain.Entities.NotebookFolder", "Folder") + .WithMany("Files") + .HasForeignKey("FolderId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LearnerNotes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Folder"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany() + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("LearnerNoteEntries") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.LearnerNote", "LearnerNote") + .WithMany("LearnerNoteEntries") + .HasForeignKey("LearnerNoteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.NotebookPage", "NotebookPage") + .WithMany("SavedItems") + .HasForeignKey("NotebookPageId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("LearnerNoteEntries") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("LearnerNote"); + + b.Navigation("NotebookPage"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerPracticeAnswer", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeExerciseAttempt", "PracticeExerciseAttempt") + .WithMany("Answers") + .HasForeignKey("PracticeExerciseAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeQuestion", "PracticeQuestion") + .WithMany("Answers") + .HasForeignKey("PracticeQuestionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeQuestionOption", "SelectedOption") + .WithMany() + .HasForeignKey("SelectedOptionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("PracticeExerciseAttempt"); + + b.Navigation("PracticeQuestion"); + + b.Navigation("SelectedOption"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("Lessons") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany("Lessons") + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "PrerequisiteLesson") + .WithMany() + .HasForeignKey("PrerequisiteLessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Topic", "Topic") + .WithMany("Lessons") + .HasForeignKey("TopicId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredLessons") + .HasForeignKey("UserAccountId"); + + b.Navigation("CertificateLevel"); + + b.Navigation("LanguageSkill"); + + b.Navigation("PrerequisiteLesson"); + + b.Navigation("Topic"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonGrammar", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("LessonGrammars") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonGrammars") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("GrammarPattern"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonKanji", b => + { + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("LessonKanjis") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonKanjis") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Kanji"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonProgress", b => + { + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonProgresses") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LessonProgresses") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lesson"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonVocabulary", b => + { + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonVocabularies") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("LessonVocabularies") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lesson"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAbuseReport", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Reporter") + .WithMany() + .HasForeignKey("ReporterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "TargetUser") + .WithMany() + .HasForeignKey("TargetUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("Reporter"); + + b.Navigation("TargetUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceApproval", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("MentorBooking"); + + b.Navigation("ReviewedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceRecord", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CourseSession"); + + b.Navigation("MentorBooking"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany("MentorAvailabilities") + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorScheduleRule", "ScheduleRule") + .WithMany() + .HasForeignKey("MentorScheduleRuleId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorWeeklyAvailability", "WeeklyAvailability") + .WithMany("Slots") + .HasForeignKey("MentorWeeklyAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "TeachingProposal") + .WithMany("GeneratedAvailabilities") + .HasForeignKey("TeachingProposalId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("ScheduleRule"); + + b.Navigation("TeachingProposal"); + + b.Navigation("WeeklyAvailability"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBankAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "VerifiedByAdmin") + .WithMany() + .HasForeignKey("VerifiedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("MentorUser"); + + b.Navigation("VerifiedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CompensationLevel") + .WithMany() + .HasForeignKey("CompensationLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorCreditGrant", "CreditGrant") + .WithMany() + .HasForeignKey("CreditGrantId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany("MentorBookings") + .HasForeignKey("MentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserSubscription", "UserSubscription") + .WithMany("MentorBookings") + .HasForeignKey("UserSubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CompensationLevel"); + + b.Navigation("CreditGrant"); + + b.Navigation("MentorAvailability"); + + b.Navigation("UserSubscription"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingDayGuard", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingIntent", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Learner"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingReservation", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany() + .HasForeignKey("MentorAvailabilityId", "MentorId") + .HasPrincipalKey("Id", "MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + + b.Navigation("MentorAvailability"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingTerms", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany() + .HasForeignKey("MentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithOne() + .HasForeignKey("RikiPath.Domain.Entities.MentorBookingTerms", "MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorAvailability"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCalendarConnection", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorChatMessage", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Sender") + .WithMany() + .HasForeignKey("SenderUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("Sender"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorCreditGrant", "CreditGrant") + .WithMany("Entries") + .HasForeignKey("CreditGrantId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreditGrant"); + + b.Navigation("Learner"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserSubscription", "UserSubscription") + .WithMany() + .HasForeignKey("UserSubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Learner"); + + b.Navigation("UserSubscription"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ResolvedByAdmin") + .WithMany() + .HasForeignKey("ResolvedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + + b.Navigation("ResolvedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDisputeHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorDispute", "Dispute") + .WithMany("Histories") + .HasForeignKey("DisputeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Dispute"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorEarningEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAttendanceApproval", "AttendanceApproval") + .WithMany() + .HasForeignKey("AttendanceApprovalId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany() + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("AttendanceApproval"); + + b.Navigation("CertificateLevel"); + + b.Navigation("CreatedByAdmin"); + + b.Navigation("MentorBooking"); + + b.Navigation("MentorUser"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorGroupPolicy", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "DeletedByAdmin") + .WithMany() + .HasForeignKey("DeletedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "LastAppliedByAdmin") + .WithMany() + .HasForeignKey("LastAppliedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UpdatedByAdmin") + .WithMany() + .HasForeignKey("UpdatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreatedByAdmin"); + + b.Navigation("DeletedByAdmin"); + + b.Navigation("LastAppliedByAdmin"); + + b.Navigation("UpdatedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorHourlyRate", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfiguredByAdmin"); + + b.Navigation("MentorUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfirmedByAdmin") + .WithMany() + .HasForeignKey("ConfirmedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "InitiatedByAdmin") + .WithMany() + .HasForeignKey("InitiatedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBankAccount", "LockedBankAccount") + .WithMany() + .HasForeignKey("LockedBankAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorPayoutObligation", "PayoutObligation") + .WithMany("Attempts") + .HasForeignKey("PayoutObligationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfirmedByAdmin"); + + b.Navigation("InitiatedByAdmin"); + + b.Navigation("LockedBankAccount"); + + b.Navigation("PayoutObligation"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBankAccount", "LockedBankAccount") + .WithMany() + .HasForeignKey("LockedBankAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.OrganizationPayoutAccount", "OrganizationPayoutAccount") + .WithMany() + .HasForeignKey("OrganizationPayoutAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany() + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("LockedBankAccount"); + + b.Navigation("MentorUser"); + + b.Navigation("OrganizationPayoutAccount"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollAdjustment", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany("Adjustments") + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollLine", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorEarningEntry", "EarningEntry") + .WithMany() + .HasForeignKey("EarningEntryId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany("Lines") + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("EarningEntry"); + + b.Navigation("MentorBooking"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "PreparedByAdmin") + .WithMany() + .HasForeignKey("PreparedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("MentorUser"); + + b.Navigation("PreparedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorProfile", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithOne("MentorProfile") + .HasForeignKey("RikiPath.Domain.Entities.MentorProfile", "MentorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorReview", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorScheduleRule", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorSchedule", "Schedule") + .WithMany("Rules") + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Schedule"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "CoursePlan") + .WithMany() + .HasForeignKey("CoursePlanId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + + b.Navigation("CoursePlan"); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("ReviewedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposalEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "Proposal") + .WithMany("Events") + .HasForeignKey("ProposalId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Proposal"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingQualification", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "VerifiedByAdmin") + .WithMany() + .HasForeignKey("VerifiedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("MentorUser"); + + b.Navigation("VerifiedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", null) + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", null) + .WithMany() + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("Questions") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.ContentPassage", "Passage") + .WithMany("Questions") + .HasForeignKey("PassageId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.MockQuestion", null) + .WithMany() + .HasForeignKey("SourceQuestionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockTestSection"); + + b.Navigation("Passage"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestionOption", b => + { + b.HasOne("RikiPath.Domain.Entities.MockQuestion", "MockQuestion") + .WithMany("Options") + .HasForeignKey("MockQuestionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MockQuestion"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("MockTests") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredMockTests") + .HasForeignKey("UserAccountId"); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAnswer", b => + { + b.HasOne("RikiPath.Domain.Entities.MockQuestion", "MockQuestion") + .WithMany("Answers") + .HasForeignKey("MockQuestionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "MockTestAttempt") + .WithMany("Answers") + .HasForeignKey("MockTestAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockQuestionOption", "SelectedOption") + .WithMany() + .HasForeignKey("SelectedOptionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockQuestion"); + + b.Navigation("MockTestAttempt"); + + b.Navigation("SelectedOption"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("MockTestAttempts") + .HasForeignKey("UserAccountId"); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateSection", "CertificateSection") + .WithMany("MockTestSections") + .HasForeignKey("CertificateSectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany("MockTestSections") + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTest", "MockTest") + .WithMany("Sections") + .HasForeignKey("MockTestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CertificateSection"); + + b.Navigation("LanguageSkill"); + + b.Navigation("MockTest"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSectionResult", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "MockTestAttempt") + .WithMany("SectionResults") + .HasForeignKey("MockTestAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("SectionResults") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MockTestAttempt"); + + b.Navigation("MockTestSection"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Note", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithOne("Note") + .HasForeignKey("RikiPath.Domain.Entities.Note", "MentorBookingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("Notes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.HasOne("RikiPath.Domain.Entities.LearnerNote", "LearnerNote") + .WithMany("Pages") + .HasForeignKey("LearnerNoteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("LearnerNote"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Notification", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("Notifications") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.OrganizationPayoutAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfiguredByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany() + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Topic", "Topic") + .WithMany() + .HasForeignKey("TopicId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CertificateLevel"); + + b.Navigation("LanguageSkill"); + + b.Navigation("Lesson"); + + b.Navigation("Topic"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany() + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany("Attempts") + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("PracticeExercise"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany("Questions") + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PracticeExercise"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestionOption", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeQuestion", "PracticeQuestion") + .WithMany("Options") + .HasForeignKey("PracticeQuestionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PracticeQuestion"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("PracticeSubmissions") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("PracticeSubmissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.RecommendedLearningPath", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("RecommendedLearningPaths") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("ReviewCards") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("ReviewCards") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.LearnerNoteEntry", "LearnerNoteEntry") + .WithMany("ReviewCards") + .HasForeignKey("LearnerNoteEntryId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.SrsCardTemplate", "SrsCardTemplate") + .WithMany() + .HasForeignKey("SrsCardTemplateId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("ReviewCards") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany() + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("LearnerNoteEntry"); + + b.Navigation("Lesson"); + + b.Navigation("SrsCardTemplate"); + + b.Navigation("UserAccount"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.ReviewCard", "ReviewCard") + .WithMany("ReviewHistories") + .HasForeignKey("ReviewCardId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ReviewCard"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsCardTemplate", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany() + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany() + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "SubmittedByUser") + .WithMany() + .HasForeignKey("SubmittedByUserId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany() + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CertificateLevel"); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("Lesson"); + + b.Navigation("ReviewedByAdmin"); + + b.Navigation("SubmittedByUser"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsReviewSession", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "SourceProposal") + .WithMany() + .HasForeignKey("SourceProposalId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("Plan"); + + b.Navigation("SourceProposal"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortMentorAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("AssignedById") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", null) + .WithMany() + .HasForeignKey("PolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("PreviousMentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortSession", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "Availability") + .WithMany() + .HasForeignKey("AvailabilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany("Sessions") + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Availability"); + + b.Navigation("Cohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany("Enrollments") + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "RetakeOf") + .WithMany() + .HasForeignKey("RetakeOfId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", null) + .WithMany() + .HasForeignKey("TransferredFromCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("GroupPolicy"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("Plan"); + + b.Navigation("RetakeOf"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseHomework", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Homework") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCoursePlan", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseSession", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "Availability") + .WithMany() + .HasForeignKey("AvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Sessions") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Availability"); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "AssessedCertificateLevel") + .WithMany() + .HasForeignKey("AssessedCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "SelfDeclaredCertificateLevel") + .WithMany() + .HasForeignKey("SelfDeclaredCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "StartingCertificateLevel") + .WithMany() + .HasForeignKey("StartingCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "TargetCertificateLevel") + .WithMany("LearnersTargeting") + .HasForeignKey("TargetCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("AssessedCertificateLevel"); + + b.Navigation("SelfDeclaredCertificateLevel"); + + b.Navigation("StartingCertificateLevel"); + + b.Navigation("TargetCertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserDeviceToken", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSrsPreference", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "PendingMentorAvailability") + .WithMany() + .HasForeignKey("PendingMentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.SubscriptionPlan", "SubscriptionPlan") + .WithMany("UserSubscriptions") + .HasForeignKey("SubscriptionPlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("UserSubscriptions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Mentor"); + + b.Navigation("PendingMentorAvailability"); + + b.Navigation("SubscriptionPlan"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredVocabularies") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnersTargeting"); + + b.Navigation("Lessons"); + + b.Navigation("MockTests"); + + b.Navigation("PracticeSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.Navigation("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateType", b => + { + b.Navigation("Levels"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Navigation("Assignments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.Navigation("Questions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LessonGrammars"); + + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.Navigation("Attachments"); + + b.Navigation("Exercises"); + + b.Navigation("HomeworkAssignmentLessons"); + + b.Navigation("Submission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.Navigation("Files"); + + b.Navigation("GradingResult"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaCharacter", b => + { + b.Navigation("PracticeCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.Navigation("Histories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnerNoteEntries"); + + b.Navigation("LessonKanjis"); + + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LanguageSkill", b => + { + b.Navigation("Lessons"); + + b.Navigation("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.Navigation("LearnerNoteEntries"); + + b.Navigation("Pages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.Navigation("HomeworkAssignmentLessons"); + + b.Navigation("LessonGrammars"); + + b.Navigation("LessonKanjis"); + + b.Navigation("LessonProgresses"); + + b.Navigation("LessonVocabularies"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.Navigation("MentorBookings"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.Navigation("Note"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.Navigation("Histories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.Navigation("Attempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.Navigation("Adjustments"); + + b.Navigation("Lines"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.Navigation("Rules"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.Navigation("Events"); + + b.Navigation("GeneratedAvailabilities"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.Navigation("Slots"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.Navigation("Answers"); + + b.Navigation("Options"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.Navigation("Sections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.Navigation("Answers"); + + b.Navigation("SectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.Navigation("Passages"); + + b.Navigation("Questions"); + + b.Navigation("SectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.Navigation("Files"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.Navigation("SavedItems"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.Navigation("Attempts"); + + b.Navigation("Questions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.Navigation("Answers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.Navigation("Answers"); + + b.Navigation("Options"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.Navigation("GradingResult"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.Navigation("ReviewHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.Navigation("Enrollments"); + + b.Navigation("Sessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.Navigation("Audit"); + + b.Navigation("Homework"); + + b.Navigation("RetakeRequests"); + + b.Navigation("Sessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.Navigation("UserSubscriptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.Navigation("Lessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.Navigation("AiCreditTopUps"); + + b.Navigation("AuthoredGrammarPatterns"); + + b.Navigation("AuthoredKanjis"); + + b.Navigation("AuthoredLessons"); + + b.Navigation("AuthoredMockTests"); + + b.Navigation("AuthoredVocabularies"); + + b.Navigation("EmailVerifications"); + + b.Navigation("LearnerEssays"); + + b.Navigation("LearnerNotes"); + + b.Navigation("LessonProgresses"); + + b.Navigation("MentorAvailabilities"); + + b.Navigation("MentorProfile"); + + b.Navigation("MockTestAttempts"); + + b.Navigation("Notes"); + + b.Navigation("Notifications"); + + b.Navigation("PracticeSubmissions"); + + b.Navigation("RecommendedLearningPaths"); + + b.Navigation("ReviewCards"); + + b.Navigation("UserSubscriptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.Navigation("MentorBookings"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnerNoteEntries"); + + b.Navigation("LessonVocabularies"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.cs b/RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.cs new file mode 100644 index 0000000..bc52dfc --- /dev/null +++ b/RikiPath.Infrastructure/Migrations/20261201045335_AddClassQuizzes.cs @@ -0,0 +1,154 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace RikiPath.Infrastructure.Migrations +{ + /// + public partial class AddClassQuizzes : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ClassQuizzes", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + CohortId = table.Column(type: "integer", nullable: false), + MentorId = table.Column(type: "integer", nullable: false), + CertificateLevelId = table.Column(type: "integer", nullable: false), + Title = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + TimeLimitMinutes = table.Column(type: "integer", nullable: false), + DueAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + SkillCodes = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + QuestionCount = table.Column(type: "integer", nullable: false), + QuestionSnapshotJson = table.Column(type: "text", nullable: false), + StructureKey = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + PublishedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + CreatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false), + Revision = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ClassQuizzes", x => x.Id); + table.CheckConstraint("CK_ClassQuiz_QuestionCount", "\"QuestionCount\" BETWEEN 1 AND 200"); + table.CheckConstraint("CK_ClassQuiz_Status", "\"Status\" IN ('Published','Cancelled')"); + table.CheckConstraint("CK_ClassQuiz_TimeLimit", "\"TimeLimitMinutes\" BETWEEN 1 AND 240"); + table.ForeignKey( + name: "FK_ClassQuizzes_CertificateLevels_CertificateLevelId", + column: x => x.CertificateLevelId, + principalTable: "CertificateLevels", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_ClassQuizzes_StudyCohorts_CohortId", + column: x => x.CohortId, + principalTable: "StudyCohorts", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_ClassQuizzes_Users_MentorId", + column: x => x.MentorId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "ClassQuizAssignments", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + QuizId = table.Column(type: "integer", nullable: false), + LearnerId = table.Column(type: "integer", nullable: false), + EnrollmentId = table.Column(type: "integer", nullable: false), + AttemptId = table.Column(type: "integer", nullable: true), + AssignedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + CompletedAtUtc = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ClassQuizAssignments", x => x.Id); + table.ForeignKey( + name: "FK_ClassQuizAssignments_ClassQuizzes_QuizId", + column: x => x.QuizId, + principalTable: "ClassQuizzes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ClassQuizAssignments_MockTestAttempts_AttemptId", + column: x => x.AttemptId, + principalTable: "MockTestAttempts", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_ClassQuizAssignments_StudyCourses_EnrollmentId", + column: x => x.EnrollmentId, + principalTable: "StudyCourses", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_ClassQuizAssignments_Users_LearnerId", + column: x => x.LearnerId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizAssignments_AttemptId", + table: "ClassQuizAssignments", + column: "AttemptId", + unique: true, + filter: "\"AttemptId\" IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizAssignments_EnrollmentId", + table: "ClassQuizAssignments", + column: "EnrollmentId"); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizAssignments_LearnerId_EnrollmentId", + table: "ClassQuizAssignments", + columns: new[] { "LearnerId", "EnrollmentId" }); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizAssignments_QuizId_LearnerId", + table: "ClassQuizAssignments", + columns: new[] { "QuizId", "LearnerId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizzes_CertificateLevelId", + table: "ClassQuizzes", + column: "CertificateLevelId"); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizzes_CohortId_IsDeleted_DueAtUtc", + table: "ClassQuizzes", + columns: new[] { "CohortId", "IsDeleted", "DueAtUtc" }); + + migrationBuilder.CreateIndex( + name: "IX_ClassQuizzes_MentorId", + table: "ClassQuizzes", + column: "MentorId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ClassQuizAssignments"); + + migrationBuilder.DropTable( + name: "ClassQuizzes"); + } + } +} diff --git a/RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.Designer.cs b/RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.Designer.cs new file mode 100644 index 0000000..9ea1684 --- /dev/null +++ b/RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.Designer.cs @@ -0,0 +1,14444 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using RikiPath.Infrastructure; + +#nullable disable + +namespace RikiPath.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261201082900_AddRetakeSupportPolicyThresholds")] + partial class AddRetakeSupportPolicyThresholds + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("FeatureSubscriptionPlan", b => + { + b.Property("FeaturesId") + .HasColumnType("integer"); + + b.Property("SubscriptionPlansId") + .HasColumnType("integer"); + + b.HasKey("FeaturesId", "SubscriptionPlansId"); + + b.HasIndex("SubscriptionPlansId"); + + b.ToTable("FeatureSubscriptionPlan"); + + b.HasData( + new + { + FeaturesId = 1, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 7, + SubscriptionPlansId = 7 + }, + new + { + FeaturesId = 8, + SubscriptionPlansId = 7 + }, + new + { + FeaturesId = 13, + SubscriptionPlansId = 8101 + }, + new + { + FeaturesId = 14, + SubscriptionPlansId = 8102 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 8103 + }, + new + { + FeaturesId = 12, + SubscriptionPlansId = 8104 + }, + new + { + FeaturesId = 7, + SubscriptionPlansId = 8105 + }, + new + { + FeaturesId = 8, + SubscriptionPlansId = 8105 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AdminAuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ActorUserId") + .HasColumnType("integer"); + + b.Property("AfterJson") + .HasColumnType("text"); + + b.Property("BeforeJson") + .HasColumnType("text"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("EntityId") + .HasColumnType("integer"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("EntityType", "EntityId"); + + b.ToTable("AdminAuditLogs", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AiCreditTopUp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActivatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PaymentTransactionId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Quantity") + .HasColumnType("integer"); + + b.Property("TotalAmount") + .HasColumnType("decimal(18,2)"); + + b.Property("UnitPrice") + .HasColumnType("decimal(18,2)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "PaymentStatus"); + + b.ToTable("AiCreditTopUps"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateTypeId") + .HasColumnType("integer") + .HasColumnName("CertificationId"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateTypeId", "Code") + .IsUnique(); + + b.ToTable("CertificateLevels", null, t => + { + t.HasCheckConstraint("CK_CertificateLevels_SortOrder", "\"SortOrder\" >= 1"); + }); + + b.HasData( + new + { + Id = 1, + CertificateTypeId = 1, + Code = "N5", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N5", + IsDeleted = false, + Revision = 1, + SortOrder = 1 + }, + new + { + Id = 2, + CertificateTypeId = 1, + Code = "N4", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N4", + IsDeleted = false, + Revision = 1, + SortOrder = 2 + }, + new + { + Id = 3, + CertificateTypeId = 1, + Code = "N3", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N3", + IsDeleted = false, + Revision = 1, + SortOrder = 3 + }, + new + { + Id = 4, + CertificateTypeId = 1, + Code = "N2", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N2", + IsDeleted = false, + Revision = 1, + SortOrder = 4 + }, + new + { + Id = 5, + CertificateTypeId = 1, + Code = "N1", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N1", + IsDeleted = false, + Revision = 1, + SortOrder = 5 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DurationMinutes") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MaxScore") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PassingScore") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId", "Code") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.ToTable("CertificateSections"); + + b.HasData( + new + { + Id = 1, + CertificateLevelId = 1, + Code = "N5_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5285), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 1 + }, + new + { + Id = 2, + CertificateLevelId = 1, + Code = "N5_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5292), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 2 + }, + new + { + Id = 3, + CertificateLevelId = 1, + Code = "N5_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5294), + Description = "Phần thi nghe hiểu tình huống giao tiếp hàng ngày cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 4 + }, + new + { + Id = 16, + CertificateLevelId = 1, + Code = "N5_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5308), + Description = "Phần thi đọc hiểu văn bản, thông báo và đoạn hội thoại ngắn cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 3 + }, + new + { + Id = 4, + CertificateLevelId = 2, + Code = "N4_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5295), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 5, + CertificateLevelId = 2, + Code = "N4_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5296), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 6, + CertificateLevelId = 2, + Code = "N4_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5297), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 7, + CertificateLevelId = 2, + Code = "N4_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5298), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 8, + CertificateLevelId = 3, + Code = "N3_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5300), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 9, + CertificateLevelId = 3, + Code = "N3_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5301), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 10, + CertificateLevelId = 3, + Code = "N3_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5302), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 11, + CertificateLevelId = 3, + Code = "N3_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5303), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 12, + CertificateLevelId = 4, + Code = "N2_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5304), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 13, + CertificateLevelId = 4, + Code = "N2_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5305), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 14, + CertificateLevelId = 4, + Code = "N2_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5306), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 15, + CertificateLevelId = 4, + Code = "N2_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5307), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("CertificateTypes", null, t => + { + t.HasCheckConstraint("CK_CertificateTypes_SortOrder", "\"SortOrder\" >= 1"); + }); + + b.HasData( + new + { + Id = 1, + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese-Language Proficiency Test", + IsActive = true, + IsDeleted = false, + Name = "JLPT", + Revision = 1, + SortOrder = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DueAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PublishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("QuestionCount") + .HasColumnType("integer"); + + b.Property("QuestionSnapshotJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SkillCodes") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StructureKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("CohortId", "IsDeleted", "DueAtUtc"); + + b.ToTable("ClassQuizzes", null, t => + { + t.HasCheckConstraint("CK_ClassQuiz_QuestionCount", "\"QuestionCount\" BETWEEN 1 AND 200"); + + t.HasCheckConstraint("CK_ClassQuiz_Status", "\"Status\" IN ('Published','Cancelled')"); + + t.HasCheckConstraint("CK_ClassQuiz_TimeLimit", "\"TimeLimitMinutes\" BETWEEN 1 AND 240"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssignedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AttemptId") + .HasColumnType("integer"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("QuizId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AttemptId") + .IsUnique() + .HasFilter("\"AttemptId\" IS NOT NULL"); + + b.HasIndex("EnrollmentId"); + + b.HasIndex("LearnerId", "EnrollmentId"); + + b.HasIndex("QuizId", "LearnerId") + .IsUnique(); + + b.ToTable("ClassQuizAssignments", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Category") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecidedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecidedById") + .HasColumnType("integer"); + + b.Property("Decision") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorAccessGrantedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorDisclosure") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorEvidenceAllowed") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRespondedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorResponse") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RefundReviewRequested") + .HasColumnType("boolean"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Title") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CohortId"); + + b.HasIndex("CourseId"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("DecidedById"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.HasIndex("MentorId", "Status", "CreatedAtUtc"); + + b.ToTable("CohortComplaints", null, t => + { + t.HasCheckConstraint("CK_CohortComplaint_Category", "\"Category\" IN ('TeachingQuality', 'MentorConduct', 'Schedule', 'PaymentEnrollment', 'Other')"); + + t.HasCheckConstraint("CK_CohortComplaint_Decision", "(\"Status\" NOT IN ('Resolved', 'Rejected') OR (\"Decision\" IS NOT NULL AND length(btrim(\"Decision\")) > 0 AND \"DecidedById\" IS NOT NULL AND \"DecidedAtUtc\" IS NOT NULL))"); + + t.HasCheckConstraint("CK_CohortComplaint_Message", "length(btrim(\"Message\")) BETWEEN 10 AND 2000"); + + t.HasCheckConstraint("CK_CohortComplaint_RefundReview", "NOT \"RefundReviewRequested\" OR \"Category\" = 'PaymentEnrollment'"); + + t.HasCheckConstraint("CK_CohortComplaint_Status", "\"Status\" IN ('Open', 'UnderReview', 'NeedsInformation', 'Resolved', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaintEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ComplaintId") + .HasColumnType("integer"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("ComplaintId", "Id"); + + b.ToTable("CohortComplaintEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortEnrollmentEntitlement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ConsumedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ConsumedByCourseId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EntitlementReference") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("GrantedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("GrantedById") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("RevocationReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RevokedById") + .HasColumnType("integer"); + + b.Property("SourceType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("StudyCohortId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EntitlementReference") + .IsUnique(); + + b.HasIndex("LearnerId"); + + b.HasIndex("PlanId"); + + b.HasIndex("StudyCohortId", "LearnerId") + .IsUnique() + .HasFilter("\"Status\" = 'Active' AND \"IsDeleted\" = false"); + + b.ToTable("CohortEnrollmentEntitlements", null, t => + { + t.HasCheckConstraint("CK_CohortEnrollmentEntitlement_NoCredit", "\"SourceType\" NOT IN ('ConsultationCredit', 'Credit1on1', 'OneOnOneCredit')"); + + t.HasCheckConstraint("CK_CohortEnrollmentEntitlement_Status", "\"Status\" IN ('Active', 'Consumed', 'Revoked', 'Expired')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortLearningFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RespondedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RespondedById") + .HasColumnType("integer"); + + b.Property("Response") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("Topic") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("MentorId"); + + b.HasIndex("RespondedById"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.ToTable("CohortLearningFeedback", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortMentorReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("Comment") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHidden") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CohortId"); + + b.HasIndex("LearnerId"); + + b.HasIndex("CourseId", "MentorId") + .IsUnique(); + + b.HasIndex("MentorId", "IsHidden", "CreatedAtUtc"); + + b.ToTable("CohortMentorReviews", null, t => + { + t.HasCheckConstraint("CK_CohortMentorReview_Rating", "\"Rating\" BETWEEN 1 AND 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CohortRevisionSnapshot") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("ImpactSnapshot") + .IsRequired() + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RequestedById") + .HasColumnType("integer"); + + b.Property("RequestedByRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("ShiftWeeks") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("CohortId") + .IsUnique() + .HasDatabaseName("IX_CohortScheduleRequests_PendingCohort") + .HasFilter("\"Status\" = 'Pending'"); + + b.HasIndex("ReviewedById"); + + b.HasIndex("CohortId", "Id"); + + b.HasIndex("RequestedById", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.ToTable("CohortScheduleRequests", null, t => + { + t.HasCheckConstraint("CK_CohortScheduleRequest_Decision", "(\"Status\" NOT IN ('Approved', 'Rejected') OR (\"ReviewedById\" IS NOT NULL AND \"ReviewedAtUtc\" IS NOT NULL)) AND (\"Status\" <> 'Rejected' OR (\"DecisionNote\" IS NOT NULL AND length(btrim(\"DecisionNote\")) > 0))"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Kind", "\"Kind\" IN ('ShiftWeeks', 'CancelEmptyCohort')"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Reason", "length(btrim(\"Reason\")) BETWEEN 10 AND 1000"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_ShiftWeeks", "(\"Kind\" = 'ShiftWeeks' AND \"ShiftWeeks\" BETWEEN 1 AND 8) OR (\"Kind\" = 'CancelEmptyCohort' AND \"ShiftWeeks\" IS NULL)"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Status", "\"Status\" IN ('Pending', 'Approved', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequestEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("RequestId", "Id"); + + b.ToTable("CohortScheduleRequestEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DestinationCourseId") + .HasColumnType("integer"); + + b.Property("EligibilitySnapshot") + .HasColumnType("text"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("PolicyId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RequestedTargetCohortId") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SourceCohortId") + .HasColumnType("integer"); + + b.Property("SourceCourseId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TargetCohortId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DestinationCourseId") + .IsUnique() + .HasFilter("\"DestinationCourseId\" IS NOT NULL"); + + b.HasIndex("PolicyId"); + + b.HasIndex("RequestedTargetCohortId"); + + b.HasIndex("ReviewedById"); + + b.HasIndex("SourceCohortId"); + + b.HasIndex("SourceCourseId") + .IsUnique() + .HasDatabaseName("IX_CohortTransferRequests_PendingSource") + .HasFilter("\"Status\" = 'Pending'"); + + b.HasIndex("TargetCohortId"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.ToTable("CohortTransferRequests", null, t => + { + t.HasCheckConstraint("CK_CohortTransferRequest_Decision", "(\"Status\" <> 'Approved' OR (\"TargetCohortId\" IS NOT NULL AND \"DestinationCourseId\" IS NOT NULL AND \"ReviewedById\" IS NOT NULL)) AND (\"Status\" <> 'Rejected' OR (\"DecisionNote\" IS NOT NULL AND length(btrim(\"DecisionNote\")) > 0 AND \"ReviewedById\" IS NOT NULL))"); + + t.HasCheckConstraint("CK_CohortTransferRequest_Status", "\"Status\" IN ('Pending', 'Approved', 'Rejected', 'Withdrawn')"); + + t.HasCheckConstraint("CK_CohortTransferRequest_Target", "\"TargetCohortId\" IS NULL OR \"TargetCohortId\" <> \"SourceCohortId\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequestEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("RequestId", "Id"); + + b.ToTable("CohortTransferRequestEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAiReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentId") + .HasColumnType("integer"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ErrorCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IssuesJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("RequestedByUserId") + .HasColumnType("integer"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Summary") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Verdict") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("WarningCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContentType", "ContentId", "ReviewedAt"); + + b.ToTable("ContentAiReviews"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentApprovalRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("BatchId") + .HasColumnType("uuid"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DiffSummaryJson") + .HasColumnType("text"); + + b.Property("EntityType") + .HasColumnType("integer"); + + b.Property("IdempotencyKey") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReviewHistoryJson") + .HasColumnType("jsonb"); + + b.Property("ReviewNote") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByName") + .HasColumnType("text"); + + b.Property("RightsConfirmed") + .HasColumnType("boolean"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RowKey") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SourceFileName") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("character varying(260)"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceRowNumber") + .HasColumnType("integer"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("ImportExcel"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedByUserId") + .HasColumnType("integer"); + + b.Property("TargetEntityId") + .HasColumnType("integer"); + + b.Property("ValidationSummaryJson") + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("BatchId"); + + b.HasIndex("SubmittedByUserId"); + + b.HasIndex("EntityType", "Status"); + + b.HasIndex("SubmittedByUserId", "IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.ToTable("ContentApprovalRequests"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAudioTranscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AttemptCount") + .HasColumnType("integer"); + + b.Property("AudioUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("AudioUrlHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Confidence") + .HasColumnType("double precision"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("integer"); + + b.Property("ErrorCode") + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("ErrorMessage") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("LanguageCode") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("LeaseExpiresAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LeaseId") + .HasColumnType("uuid"); + + b.Property("NextAttemptAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RawTranscriptJson") + .HasColumnType("jsonb"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Transcript") + .HasColumnType("text"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("AudioUrlHash") + .IsUnique(); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("Status", "NextAttemptAtUtc", "LeaseExpiresAtUtc"); + + b.ToTable("ContentAudioTranscriptions", null, t => + { + t.HasCheckConstraint("CK_ContentAudioTranscription_Attempts", "\"AttemptCount\" >= 0"); + + t.HasCheckConstraint("CK_ContentAudioTranscription_Language", "\"LanguageCode\" = 'ja-JP'"); + + t.HasCheckConstraint("CK_ContentAudioTranscription_Status", "\"Status\" IN ('Pending', 'Processing', 'Completed', 'Failed')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentBankItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EntityType") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LatestBatchId") + .HasColumnType("uuid"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NaturalKey") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OwnerUserId") + .HasColumnType("integer"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TargetEntityId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EntityType", "TargetEntityId"); + + b.HasIndex("OwnerUserId", "EntityType", "NaturalKey") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.ToTable("ContentBankItems"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentLevelMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanjiId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("CertificateLevelId", "GrammarPatternId") + .IsUnique() + .HasFilter("\"GrammarPatternId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.HasIndex("CertificateLevelId", "KanjiId") + .IsUnique() + .HasFilter("\"KanjiId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.HasIndex("CertificateLevelId", "VocabularyId") + .IsUnique() + .HasFilter("\"VocabularyId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.ToTable("ContentLevelMappings", t => + { + t.HasCheckConstraint("CK_ContentLevelMappings_ExactlyOneContent", "(CASE WHEN \"KanjiId\" IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN \"VocabularyId\" IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN \"GrammarPatternId\" IS NOT NULL THEN 1 ELSE 0 END) = 1"); + }); + + b.HasData( + new + { + Id = 920001, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910001 + }, + new + { + Id = 920002, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910002 + }, + new + { + Id = 920003, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910003 + }, + new + { + Id = 920004, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910004 + }, + new + { + Id = 920005, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910005 + }, + new + { + Id = 920006, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910006 + }, + new + { + Id = 920007, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910007 + }, + new + { + Id = 920008, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910008 + }, + new + { + Id = 920009, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910009 + }, + new + { + Id = 920010, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910010 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("AudioTranscript") + .HasColumnType("text"); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("ContentFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("Instructions") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ListeningSection") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("MockTestSectionId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ParentPassageId") + .HasColumnType("integer"); + + b.Property("PassageCode") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("PassageIdentity") + .HasColumnType("uuid"); + + b.Property("PassageText") + .HasColumnType("text"); + + b.Property("PlaybackPolicyJson") + .HasColumnType("jsonb"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContentFingerprint"); + + b.HasIndex("MockTestSectionId"); + + b.HasIndex("PassageIdentity"); + + b.ToTable("ContentPassages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseAuditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("At") + .HasColumnType("timestamp without time zone"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.ToTable("CourseAuditEntries", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseRetakeRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("EligibilitySnapshot") + .HasColumnType("text"); + + b.Property("EvidenceUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorSupportPlan") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorSupportPlanAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorSupportPlanById") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("ResultPublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CourseId") + .IsUnique() + .HasFilter("\"Status\" = 'Pending'"); + + b.ToTable("CourseRetakeRequests", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseScheduleRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Reason") + .IsRequired() + .HasColumnType("text"); + + b.Property("RequestedById") + .HasColumnType("integer"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("SessionId") + .HasColumnType("integer"); + + b.Property("Status") + .IsConcurrencyToken() + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CourseId", "SessionId") + .IsUnique() + .HasFilter("\"Status\" = 'Pending'"); + + b.ToTable("CourseScheduleRequests", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.EmailVerification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsUsed") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("VerificationCode") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("EmailVerifications"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Feature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccessMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("FREE"); + + b.Property("Category") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("general"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditFeatureKey") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsCoreFree") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("RoutePrefixesJson") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("Features"); + + b.HasData( + new + { + Id = 1, + AccessMode = "PLAN_REQUIRED", + Category = "self_study", + Code = "LESSONS_CONTENT", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập kho bài học JLPT đầy đủ theo cấp độ kèm nghe hiểu, đọc hiểu và lưu tiến độ.", + IsCoreFree = false, + IsDeleted = false, + Name = "Thư viện bài học JLPT", + RoutePrefixesJson = "[\"/lessons\",\"/lesson-player\",\"/riki/listening\",\"/riki/reading\"]", + SortOrder = 10 + }, + new + { + Id = 2, + AccessMode = "FREE", + Category = "core_tools", + Code = "JAPANESE_LIBRARY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Tra cứu ngữ pháp, luyện viết Hiragana, Katakana và Kanji theo thứ tự nét miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Thư viện Kana, Kanji & Ngữ pháp", + RoutePrefixesJson = "[\"/grammar\",\"/kanji-writing\",\"/vocabulary-detail\"]", + SortOrder = 3 + }, + new + { + Id = 3, + AccessMode = "FREE", + Category = "practice_exam", + Code = "PRACTICE_EXERCISES", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Làm bài luyện tập củng cố kỹ năng và bộ đề theo cấp độ JLPT.", + IsCoreFree = false, + IsDeleted = false, + Name = "Bài luyện tập theo kỹ năng", + RoutePrefixesJson = "[\"/lesson-practice\",\"/practice-sets\"]", + SortOrder = 20 + }, + new + { + Id = 4, + AccessMode = "FREE", + Category = "practice_exam", + Code = "MOCK_TESTS", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Luyện đề thi thử JLPT mô phỏng đầy đủ 4 kỹ năng và theo dõi kết quả.", + IsCoreFree = false, + IsDeleted = false, + Name = "Đề thi thử JLPT", + RoutePrefixesJson = "[\"/mock-test\",\"/mock-tests\",\"/exam-result\"]", + SortOrder = 21 + }, + new + { + Id = 5, + AccessMode = "FREE", + Category = "self_study", + Code = "STANDARD_ROADMAP", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Xem lộ trình học JLPT tiêu chuẩn theo mục tiêu, kết quả đánh giá năng lực và tiến độ học.", + IsCoreFree = false, + IsDeleted = false, + Name = "Lộ trình tiêu chuẩn & Tiến độ học", + RoutePrefixesJson = "[\"/roadmap\"]", + SortOrder = 11 + }, + new + { + Id = 6, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_MOCK_EXPLANATION", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "mock_test_explanation", + Description = "Nhận phân tích chi tiết đáp án đề thi thử từ trợ lý AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Giải thích câu hỏi bằng AI", + SortOrder = 33 + }, + new + { + Id = 7, + AccessMode = "DISABLED", + Category = "mentor_legacy", + Code = "MENTOR_1ON1_LEGACY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Gói cũ bao gồm 12 buổi ôn luyện trực tiếp 1-1 với Mentor (đã thay bằng lớp học nhóm).", + IsCoreFree = false, + IsDeleted = false, + Name = "12 buổi meeting 1-1 với Mentor", + SortOrder = 90 + }, + new + { + Id = 8, + AccessMode = "DISABLED", + Category = "mentor_legacy", + Code = "MENTOR_ROOM_LEGACY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Cấu hình lịch 1-1 cũ (lớp học nhóm dùng cơ chế ghi danh khóa học riêng).", + IsCoreFree = false, + IsDeleted = false, + Name = "Đặt lịch và phòng học trực tuyến", + SortOrder = 91 + }, + new + { + Id = 9, + AccessMode = "FREE", + Category = "core_tools", + Code = "PERSONAL_NOTEBOOK", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Tạo thư mục, tệp ghi chú, trang bài học, highlight và mục đã lưu cá nhân miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Sổ tay cá nhân & Mini Notebook", + RoutePrefixesJson = "[\"/kanji-notebook\"]", + SortOrder = 1 + }, + new + { + Id = 10, + AccessMode = "FREE", + Category = "core_tools", + Code = "SRS_STUDY", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Ôn thẻ đến hạn, 4 chế độ ôn tự do, quản lý thẻ cá nhân và thư viện thẻ mẫu miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Ôn tập SRS & Thư viện thẻ mẫu", + RoutePrefixesJson = "[\"/daily-srs\"]", + SortOrder = 2 + }, + new + { + Id = 11, + AccessMode = "FREE", + Category = "practice_exam", + Code = "PLACEMENT_TEST", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Làm bài đánh giá trình độ JLPT đầu vào để xác định cấp độ học phù hợp.", + IsCoreFree = false, + IsDeleted = false, + Name = "Đánh giá năng lực đầu vào", + RoutePrefixesJson = "[\"/placement\"]", + SortOrder = 19 + }, + new + { + Id = 12, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_LEARNING_PATH", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "learning_path", + Description = "Tạo kế hoạch học tập chi tiết theo ngày bằng AI dựa trên điểm đánh giá và ngày thi.", + IsCoreFree = false, + IsDeleted = false, + Name = "Lộ trình học cá nhân hóa bằng AI", + SortOrder = 30 + }, + new + { + Id = 13, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_SPEAKING", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "speaking", + Description = "Thu âm tiếng Nhật và nhận điểm phát âm, ngữ điệu cùng nhận xét chi tiết từ AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Luyện nói & Chấm phát âm AI", + RoutePrefixesJson = "[\"/riki/speaking\",\"/speech\"]", + SortOrder = 31 + }, + new + { + Id = 14, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_WRITING", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "writing", + Description = "Viết câu và bài luận tiếng Nhật, nhận sửa lỗi ngữ pháp và chấm điểm từ AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Luyện viết & Chấm bài luận AI", + RoutePrefixesJson = "[\"/riki/essay\",\"/sentence-studio\"]", + SortOrder = 32 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GradingResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FeedbackJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("GradedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("HomeworkSubmissionId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OverallScore") + .HasColumnType("double precision"); + + b.Property("PracticeSubmissionId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HomeworkSubmissionId") + .IsUnique(); + + b.HasIndex("PracticeSubmissionId") + .IsUnique(); + + b.ToTable("GradingResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentenceMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("Structure") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UsageNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("Title"); + + b.HasIndex("UserAccountId"); + + b.ToTable("GrammarPatterns"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiDraftFeedback") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("AiDraftGeneratedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("AiDraftScore") + .HasColumnType("double precision"); + + b.Property("AiDraftUnavailableReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AssignmentScope") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("Booking1on1"); + + b.Property("AuthoredDefinitionJson") + .HasColumnType("text"); + + b.Property("CohortAssignmentGroupKey") + .HasColumnType("uuid"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DueAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Instructions") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorFeedback") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorScore") + .HasColumnType("double precision"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Passed") + .HasColumnType("boolean"); + + b.Property("PublishedByMentorId") + .HasColumnType("integer"); + + b.Property("PublishedFeedbackAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("StudyCourseId") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("MentorId"); + + b.HasIndex("StudyCourseId"); + + b.HasIndex("CohortId", "LearnerId"); + + b.HasIndex("LearnerId", "DueAt"); + + b.ToTable("HomeworkAssignments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentAttachment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileKey") + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StorageReference") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("FileKey"); + + b.HasIndex("HomeworkAssignmentId"); + + b.ToTable("HomeworkAssignmentAttachments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentExercise", b => + { + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.HasKey("HomeworkAssignmentId", "PracticeExerciseId"); + + b.HasIndex("PracticeExerciseId"); + + b.ToTable("HomeworkAssignmentExercises", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentLesson", b => + { + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.HasKey("HomeworkAssignmentId", "LessonId"); + + b.HasIndex("LessonId"); + + b.ToTable("HomeworkAssignmentLessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileUrl") + .HasColumnType("text"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastRevisedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PrivateAudioReference") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PrivateScanReference") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RevisionCount") + .HasColumnType("integer"); + + b.Property("ScanStorageUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SelectedOptionsJson") + .HasColumnType("text"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TextContent") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("HomeworkAssignmentId") + .IsUnique(); + + b.HasIndex("LearnerId"); + + b.HasIndex("LessonId"); + + b.ToTable("HomeworkSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmissionFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileKey") + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("HomeworkSubmissionId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StorageReference") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("FileKey"); + + b.HasIndex("HomeworkSubmissionId"); + + b.ToTable("HomeworkSubmissionFiles"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptExamSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExamDate") + .HasColumnType("date"); + + b.Property("ImportedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Location") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ReviewNote") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SourceUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("Status") + .IsConcurrencyToken() + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("SourceKey") + .IsUnique(); + + b.ToTable("JlptExamSchedules", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptLevelPayCoefficient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("Coefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ConfiguredByAdminId"); + + b.HasIndex("CertificateLevelId", "EffectiveFromUtc") + .IsUnique(); + + b.ToTable("JlptLevelPayCoefficients", t => + { + t.HasCheckConstraint("CK_JlptLevelPayCoefficient_Positive", "\"Coefficient\" > 0"); + + t.HasCheckConstraint("CK_JlptLevelPayCoefficient_Range", "\"EffectiveUntilUtc\" IS NULL OR \"EffectiveUntilUtc\" > \"EffectiveFromUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("Character") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Romaji") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StrokeCount") + .HasColumnType("integer"); + + b.Property("StrokeOrderImageUrl") + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("Character", "Type") + .IsUnique(); + + b.ToTable("KanaCharacters"); + + b.HasData( + new + { + Id = 1, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/22/Ja-a.ogg", + Character = "あ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1757), + IsDeleted = false, + Romaji = "a", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 2, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-i.ogg", + Character = "い", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1766), + IsDeleted = false, + Romaji = "i", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 3, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Ja-u.ogg", + Character = "う", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1768), + IsDeleted = false, + Romaji = "u", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 4, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/21/Ja-e.ogg", + Character = "え", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1770), + IsDeleted = false, + Romaji = "e", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 5, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/df/Ja-o.ogg", + Character = "お", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1771), + IsDeleted = false, + Romaji = "o", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 6, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Ja-ka.ogg", + Character = "か", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1774), + IsDeleted = false, + Romaji = "ka", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 7, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/87/Ja-ki.ogg", + Character = "き", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1775), + IsDeleted = false, + Romaji = "ki", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 8, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Ja-ku.ogg", + Character = "く", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1776), + IsDeleted = false, + Romaji = "ku", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 9, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b3/Ja-ke.ogg", + Character = "け", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1830), + IsDeleted = false, + Romaji = "ke", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 10, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/18/Ja-ko.ogg", + Character = "こ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1832), + IsDeleted = false, + Romaji = "ko", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 11, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Ja-sa.ogg", + Character = "さ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1833), + IsDeleted = false, + Romaji = "sa", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 12, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/80/Ja-shi.ogg", + Character = "し", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1834), + IsDeleted = false, + Romaji = "shi", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 13, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Ja-su.ogg", + Character = "す", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1835), + IsDeleted = false, + Romaji = "su", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 14, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a8/Ja-se.ogg", + Character = "せ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1836), + IsDeleted = false, + Romaji = "se", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 15, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/00/Ja-so.ogg", + Character = "そ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1837), + IsDeleted = false, + Romaji = "so", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 16, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/d2/Ja-ta.ogg", + Character = "た", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1838), + IsDeleted = false, + Romaji = "ta", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 17, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/38/Ja-chi.ogg", + Character = "ち", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1838), + IsDeleted = false, + Romaji = "chi", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 18, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/32/Ja-tsu.ogg", + Character = "つ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1840), + IsDeleted = false, + Romaji = "tsu", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 19, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/10/Ja-te.ogg", + Character = "て", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1841), + IsDeleted = false, + Romaji = "te", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 20, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a5/Ja-to.ogg", + Character = "と", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1842), + IsDeleted = false, + Romaji = "to", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 21, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/92/Ja-na.ogg", + Character = "な", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1843), + IsDeleted = false, + Romaji = "na", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 22, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b7/Ja-ni.ogg", + Character = "に", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1844), + IsDeleted = false, + Romaji = "ni", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 23, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b1/Ja-nu.ogg", + Character = "ぬ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1845), + IsDeleted = false, + Romaji = "nu", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 24, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/86/Ja-ne.ogg", + Character = "ね", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1845), + IsDeleted = false, + Romaji = "ne", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 25, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/54/Ja-no.ogg", + Character = "の", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1846), + IsDeleted = false, + Romaji = "no", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 26, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/Ja-ha.ogg", + Character = "は", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1847), + IsDeleted = false, + Romaji = "ha", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 27, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/99/Ja-hi.ogg", + Character = "ひ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1848), + IsDeleted = false, + Romaji = "hi", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 28, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/70/Ja-fu.ogg", + Character = "ふ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1849), + IsDeleted = false, + Romaji = "fu", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 29, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2a/Ja-he.ogg", + Character = "へ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1849), + IsDeleted = false, + Romaji = "he", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 30, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Ja-ho.ogg", + Character = "ほ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1850), + IsDeleted = false, + Romaji = "ho", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 31, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Ja-ma.ogg", + Character = "ま", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1851), + IsDeleted = false, + Romaji = "ma", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 32, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/16/Ja-mi.ogg", + Character = "み", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1852), + IsDeleted = false, + Romaji = "mi", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 33, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ja-mu.ogg", + Character = "む", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1852), + IsDeleted = false, + Romaji = "mu", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 34, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/8b/Ja-me.ogg", + Character = "め", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1913), + IsDeleted = false, + Romaji = "me", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 35, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Ja-mo.ogg", + Character = "も", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1915), + IsDeleted = false, + Romaji = "mo", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 36, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/e8/Ja-ya.ogg", + Character = "や", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1915), + IsDeleted = false, + Romaji = "ya", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 37, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/7b/Ja-yu.ogg", + Character = "ゆ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1916), + IsDeleted = false, + Romaji = "yu", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 38, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c9/Ja-yo.ogg", + Character = "よ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1917), + IsDeleted = false, + Romaji = "yo", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 39, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/04/Ja-ra.ogg", + Character = "ら", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1918), + IsDeleted = false, + Romaji = "ra", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 40, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/76/Ja-ri.ogg", + Character = "り", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1919), + IsDeleted = false, + Romaji = "ri", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 41, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/56/Ja-ru.ogg", + Character = "る", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1920), + IsDeleted = false, + Romaji = "ru", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 42, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/57/Ja-re.ogg", + Character = "れ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1920), + IsDeleted = false, + Romaji = "re", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 43, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Ja-ro.ogg", + Character = "ろ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1922), + IsDeleted = false, + Romaji = "ro", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 44, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Ja-wa.ogg", + Character = "わ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1922), + IsDeleted = false, + Romaji = "wa", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 45, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/77/Ja-wo.ogg", + Character = "を", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1923), + IsDeleted = false, + Romaji = "wo", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 46, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0c/Ja-n.ogg", + Character = "ん", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1924), + IsDeleted = false, + Romaji = "n", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 47, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/22/Ja-a.ogg", + Character = "ア", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1955), + IsDeleted = false, + Romaji = "a", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 48, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-i.ogg", + Character = "イ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1958), + IsDeleted = false, + Romaji = "i", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 49, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Ja-u.ogg", + Character = "ウ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1959), + IsDeleted = false, + Romaji = "u", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 50, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/21/Ja-e.ogg", + Character = "エ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1960), + IsDeleted = false, + Romaji = "e", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 51, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/df/Ja-o.ogg", + Character = "オ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1961), + IsDeleted = false, + Romaji = "o", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 52, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Ja-ka.ogg", + Character = "カ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1961), + IsDeleted = false, + Romaji = "ka", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 53, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/87/Ja-ki.ogg", + Character = "キ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1962), + IsDeleted = false, + Romaji = "ki", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 54, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Ja-ku.ogg", + Character = "ク", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1963), + IsDeleted = false, + Romaji = "ku", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 55, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b3/Ja-ke.ogg", + Character = "ケ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1964), + IsDeleted = false, + Romaji = "ke", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 56, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/18/Ja-ko.ogg", + Character = "コ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2006), + IsDeleted = false, + Romaji = "ko", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 57, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Ja-sa.ogg", + Character = "サ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2009), + IsDeleted = false, + Romaji = "sa", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 58, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/80/Ja-shi.ogg", + Character = "シ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2010), + IsDeleted = false, + Romaji = "shi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 59, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Ja-su.ogg", + Character = "ス", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2011), + IsDeleted = false, + Romaji = "su", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 60, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a8/Ja-se.ogg", + Character = "セ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2012), + IsDeleted = false, + Romaji = "se", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 61, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/00/Ja-so.ogg", + Character = "ソ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2014), + IsDeleted = false, + Romaji = "so", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 62, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/d2/Ja-ta.ogg", + Character = "タ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2015), + IsDeleted = false, + Romaji = "ta", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 63, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/38/Ja-chi.ogg", + Character = "チ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2016), + IsDeleted = false, + Romaji = "chi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 64, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/32/Ja-tsu.ogg", + Character = "ツ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2017), + IsDeleted = false, + Romaji = "tsu", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 65, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/10/Ja-te.ogg", + Character = "テ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2019), + IsDeleted = false, + Romaji = "te", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 66, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a5/Ja-to.ogg", + Character = "ト", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2022), + IsDeleted = false, + Romaji = "to", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 67, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/92/Ja-na.ogg", + Character = "ナ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2023), + IsDeleted = false, + Romaji = "na", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 68, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b7/Ja-ni.ogg", + Character = "ニ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2024), + IsDeleted = false, + Romaji = "ni", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 69, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b1/Ja-nu.ogg", + Character = "ヌ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2026), + IsDeleted = false, + Romaji = "nu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 70, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/86/Ja-ne.ogg", + Character = "ネ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2027), + IsDeleted = false, + Romaji = "ne", + StrokeCount = 4, + Type = "Katakana" + }, + new + { + Id = 71, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/54/Ja-no.ogg", + Character = "ノ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2028), + IsDeleted = false, + Romaji = "no", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 72, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/Ja-ha.ogg", + Character = "ハ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2029), + IsDeleted = false, + Romaji = "ha", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 73, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/99/Ja-hi.ogg", + Character = "ヒ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2030), + IsDeleted = false, + Romaji = "hi", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 74, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/70/Ja-fu.ogg", + Character = "フ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2032), + IsDeleted = false, + Romaji = "fu", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 75, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2a/Ja-he.ogg", + Character = "ヘ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2033), + IsDeleted = false, + Romaji = "he", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 76, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Ja-ho.ogg", + Character = "ホ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2034), + IsDeleted = false, + Romaji = "ho", + StrokeCount = 4, + Type = "Katakana" + }, + new + { + Id = 77, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Ja-ma.ogg", + Character = "マ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2036), + IsDeleted = false, + Romaji = "ma", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 78, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/16/Ja-mi.ogg", + Character = "ミ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2037), + IsDeleted = false, + Romaji = "mi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 79, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ja-mu.ogg", + Character = "ム", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2038), + IsDeleted = false, + Romaji = "mu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 80, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/8b/Ja-me.ogg", + Character = "メ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2039), + IsDeleted = false, + Romaji = "me", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 81, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Ja-mo.ogg", + Character = "モ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2086), + IsDeleted = false, + Romaji = "mo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 82, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/e8/Ja-ya.ogg", + Character = "ヤ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2087), + IsDeleted = false, + Romaji = "ya", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 83, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/7b/Ja-yu.ogg", + Character = "ユ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2088), + IsDeleted = false, + Romaji = "yu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 84, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c9/Ja-yo.ogg", + Character = "ヨ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2089), + IsDeleted = false, + Romaji = "yo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 85, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/04/Ja-ra.ogg", + Character = "ラ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2090), + IsDeleted = false, + Romaji = "ra", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 86, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/76/Ja-ri.ogg", + Character = "リ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2092), + IsDeleted = false, + Romaji = "ri", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 87, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/56/Ja-ru.ogg", + Character = "ル", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2093), + IsDeleted = false, + Romaji = "ru", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 88, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/57/Ja-re.ogg", + Character = "レ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2094), + IsDeleted = false, + Romaji = "re", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 89, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Ja-ro.ogg", + Character = "ロ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2096), + IsDeleted = false, + Romaji = "ro", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 90, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Ja-wa.ogg", + Character = "ワ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2097), + IsDeleted = false, + Romaji = "wa", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 91, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/77/Ja-wo.ogg", + Character = "ヲ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2098), + IsDeleted = false, + Romaji = "wo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 92, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0c/Ja-n.ogg", + Character = "ン", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2099), + IsDeleted = false, + Romaji = "n", + StrokeCount = 2, + Type = "Katakana" + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EaseFactor") + .HasColumnType("double precision"); + + b.Property("IntervalDays") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanaCharacterId") + .HasColumnType("integer"); + + b.Property("LastReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NextReviewDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Repetitions") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("KanaCharacterId"); + + b.HasIndex("UserId", "KanaCharacterId") + .IsUnique(); + + b.HasIndex("UserId", "NextReviewDate"); + + b.ToTable("KanaWritingPracticeCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanaWritingPracticeCardId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Quality") + .HasColumnType("integer"); + + b.Property("Rating") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalMistakes") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("KanaWritingPracticeCardId"); + + b.ToTable("KanaWritingPracticeHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("Character") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KunYomi") + .HasColumnType("text"); + + b.Property("Meaning") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OnYomi") + .HasColumnType("text"); + + b.Property("SinoVietnamese") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("StrokeCount") + .HasColumnType("integer"); + + b.Property("StrokeOrderImageUrl") + .HasColumnType("text"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("Character"); + + b.HasIndex("Status"); + + b.HasIndex("UserAccountId"); + + b.ToTable("Kanjis"); + + b.HasData( + new + { + Id = 910001, + Character = "日", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひ、か", + Meaning = "Mặt trời; ngày", + OnYomi = "ニチ、ジツ", + SinoVietnamese = "Nhật", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910002, + Character = "月", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "つき", + Meaning = "Mặt trăng; tháng", + OnYomi = "ゲツ、ガツ", + SinoVietnamese = "Nguyệt", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910003, + Character = "火", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひ、ほ", + Meaning = "Lửa", + OnYomi = "カ", + SinoVietnamese = "Hỏa", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910004, + Character = "水", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "みず", + Meaning = "Nước", + OnYomi = "スイ", + SinoVietnamese = "Thủy", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910005, + Character = "木", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "き、こ", + Meaning = "Cây; gỗ", + OnYomi = "モク、ボク", + SinoVietnamese = "Mộc", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910006, + Character = "金", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "かね、かな", + Meaning = "Vàng; tiền", + OnYomi = "キン、コン", + SinoVietnamese = "Kim", + Status = "Published", + StrokeCount = 8, + Version = 1 + }, + new + { + Id = 910007, + Character = "土", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "つち", + Meaning = "Đất", + OnYomi = "ド、ト", + SinoVietnamese = "Thổ", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910008, + Character = "山", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "やま", + Meaning = "Núi", + OnYomi = "サン", + SinoVietnamese = "Sơn", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910009, + Character = "川", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "かわ", + Meaning = "Sông", + OnYomi = "セン", + SinoVietnamese = "Xuyên", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910010, + Character = "人", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひと", + Meaning = "Người", + OnYomi = "ジン、ニン", + SinoVietnamese = "Nhân", + Status = "Published", + StrokeCount = 2, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LanguageSkill", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Code") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique() + .HasFilter("\"Code\" IS NOT NULL"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LanguageSkills"); + + b.HasData( + new + { + Id = 1, + Code = "VOCABULARY", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese vocabulary learning skill.", + IsDeleted = false, + Name = "Vocabulary" + }, + new + { + Id = 2, + Code = "KANJI", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese kanji learning skill.", + IsDeleted = false, + Name = "Kanji" + }, + new + { + Id = 3, + Code = "GRAMMAR", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese grammar learning skill.", + IsDeleted = false, + Name = "Grammar" + }, + new + { + Id = 4, + Code = "LISTENING", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese listening comprehension skill.", + IsDeleted = false, + Name = "Listening" + }, + new + { + Id = 5, + Code = "READING", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese reading comprehension skill.", + IsDeleted = false, + Name = "Reading" + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerEssay", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentText") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageStoragePath") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageUrl") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OcrLanguage") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("OriginalOcrText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedDate"); + + b.ToTable("LearnerEssays"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("TargetId") + .HasColumnType("integer"); + + b.Property("TargetTitle") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("UpdatedAtUtc", "Id"); + + b.HasIndex("LearnerId", "TargetType", "TargetId") + .IsUnique(); + + b.ToTable("LearnerFeedback", null, t => + { + t.HasCheckConstraint("CK_LearnerFeedback_Rating", "\"Rating\" BETWEEN 1 AND 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerHighlight", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AnchorPrefix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AnchorSuffix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Color") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ContentVersionHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EndOffset") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LinkedNoteEntryId") + .HasColumnType("integer"); + + b.Property("LinkedReviewCardId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SelectedText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("StartOffset") + .HasColumnType("integer"); + + b.Property("TargetId") + .HasColumnType("integer"); + + b.Property("TargetKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TargetType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TranslationSnapshot") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LinkedNoteEntryId"); + + b.HasIndex("LinkedReviewCardId"); + + b.HasIndex("UserId", "CreatedDate"); + + b.HasIndex("UserId", "TargetKey"); + + b.HasIndex("UserId", "TargetType", "TargetId"); + + b.ToTable("LearnerHighlights"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FolderId") + .HasColumnType("integer"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("FolderId"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_LearnerNotes_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("UserId", "Name"); + + b.HasIndex("UserId", "FolderId", "IsDeleted", "SortOrder"); + + b.ToTable("LearnerNotes"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContextSnippet") + .HasMaxLength(600) + .HasColumnType("character varying(600)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleMeaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExampleSentence") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("HighlightColor") + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("ItemKind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("manual"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.Property("LearnerNoteId") + .HasColumnType("integer") + .HasColumnName("VocabularyListId"); + + b.Property("ManualMeaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ManualReading") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ManualWord") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("NotebookPageId") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TagsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'[]'::jsonb"); + + b.Property("VocabularyId") + .HasColumnType("integer") + .HasColumnName("VocabularyEntryId"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("LearnerNoteId", "IsDeleted"); + + b.HasIndex("NotebookPageId", "IsDeleted", "SortOrder"); + + b.ToTable("LearnerNoteEntries"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerPracticeAnswer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseAttemptId") + .HasColumnType("integer"); + + b.Property("PracticeQuestionId") + .HasColumnType("integer"); + + b.Property("SelectedOptionId") + .HasColumnType("integer"); + + b.Property("TextAnswer") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("PracticeQuestionId"); + + b.HasIndex("SelectedOptionId"); + + b.HasIndex("PracticeExerciseAttemptId", "PracticeQuestionId") + .IsUnique(); + + b.ToTable("LearnerPracticeAnswers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("EstimatedMinutes") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(15); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer") + .HasColumnName("SkillId"); + + b.Property("LearningObjectives") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PrerequisiteLessonId") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceProvenance") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("TopicId") + .HasColumnType("integer"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("PrerequisiteLessonId"); + + b.HasIndex("Status"); + + b.HasIndex("TopicId"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("CertificateLevelId", "LanguageSkillId"); + + b.ToTable("Lessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonGrammar", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("GrammarPatternId") + .HasColumnType("integer") + .HasColumnName("GrammarPointId"); + + b.HasKey("LessonId", "GrammarPatternId"); + + b.HasIndex("GrammarPatternId"); + + b.ToTable("LessonGrammars"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonKanji", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.HasKey("LessonId", "KanjiId"); + + b.HasIndex("KanjiId"); + + b.ToTable("LessonKanjis"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonProgress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FirstViewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("InteractionCount") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastInteractedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LastPositionSeconds") + .HasColumnType("integer"); + + b.Property("LastWatchedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ProgressPercent") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LessonId"); + + b.HasIndex("UserId", "LessonId") + .IsUnique(); + + b.ToTable("LessonProgresses"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonVocabulary", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("VocabularyId") + .HasColumnType("integer") + .HasColumnName("VocabularyEntryId"); + + b.HasKey("LessonId", "VocabularyId"); + + b.HasIndex("VocabularyId"); + + b.ToTable("LessonVocabularies"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAbuseReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ReporterId") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetUserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("ReporterId") + .HasDatabaseName("IX_MentorAbuseReports_ReporterId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorAbuseReports_Status"); + + b.HasIndex("TargetUserId") + .HasDatabaseName("IX_MentorAbuseReports_TargetUserId"); + + b.ToTable("MentorAbuseReports", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceApproval", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionReason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceSummary") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("RawLearnerDurationSeconds") + .HasColumnType("integer"); + + b.Property("RawMentorDurationSeconds") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("ReviewedByAdminId"); + + b.ToTable("MentorAttendanceApprovals", t => + { + t.HasCheckConstraint("CK_MentorAttendanceApproval_Minutes", "\"ApprovedEligibleMinutes\" IS NULL OR (\"ApprovedEligibleMinutes\" > 0 AND \"ApprovedEligibleMinutes\" <= 90)"); + + t.HasCheckConstraint("CK_MentorAttendanceApproval_RawDuration", "\"RawMentorDurationSeconds\" >= 0 AND \"RawLearnerDurationSeconds\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("FirstJoinedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastJoinedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastSeenAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LeftAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ReconnectionCount") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("RoomId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TotalDurationSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("RoomId") + .HasDatabaseName("IX_MentorAttendanceRecords_RoomId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorAttendanceRecords_Status"); + + b.HasIndex("UserId") + .HasDatabaseName("IX_MentorAttendanceRecords_UserId"); + + b.HasIndex("MentorBookingId", "UserId") + .IsUnique() + .HasDatabaseName("IX_MentorAttendanceRecords_Booking_User"); + + b.HasIndex("RoomId", "UserId") + .IsUnique() + .HasFilter("\"MentorBookingId\" IS NULL"); + + b.ToTable("MentorAttendanceRecords", null, t => + { + t.HasCheckConstraint("CK_MentorAttendanceRecord_Duration", "\"TotalDurationSeconds\" >= 0"); + + t.HasCheckConstraint("CK_MentorAttendanceRecord_Reconnection", "\"ReconnectionCount\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminName") + .HasColumnType("text"); + + b.Property("AttendanceTrackingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("BookedCount") + .HasColumnType("integer"); + + b.Property("CancelReason") + .HasColumnType("text"); + + b.Property("CancelRejectedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CancelRejectionReason") + .HasColumnType("text"); + + b.Property("CancelRequestedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ChangeRequestReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ChangeRequestedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ChangeResolution") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EndTime") + .HasColumnType("timestamp without time zone"); + + b.Property("GenerationKey") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("IsApproved") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("MaxLearners") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorScheduleRuleId") + .HasColumnType("bigint"); + + b.Property("MentorWeeklyAvailabilityId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectionReason") + .HasColumnType("text"); + + b.Property("RestMinutesSnapshot") + .HasColumnType("integer"); + + b.Property("RoomId") + .HasColumnType("uuid"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SessionMinutesSnapshot") + .HasColumnType("integer"); + + b.Property("StartTime") + .HasColumnType("timestamp without time zone"); + + b.Property("TeachingProposalId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("GenerationKey") + .IsUnique() + .HasFilter("\"GenerationKey\" IS NOT NULL"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorScheduleRuleId"); + + b.HasIndex("MentorWeeklyAvailabilityId"); + + b.HasIndex("RoomId") + .IsUnique(); + + b.HasIndex("TeachingProposalId") + .HasFilter("\"TeachingProposalId\" IS NOT NULL"); + + b.HasIndex("MentorId", "StartTime", "EndTime"); + + b.ToTable("MentorAvailabilities", t => + { + t.HasCheckConstraint("CK_MentorAvailability_BookedCount", "\"BookedCount\" >= 0 AND \"BookedCount\" <= \"MaxLearners\""); + + t.HasCheckConstraint("CK_MentorAvailability_GeneratedSlot", "(\"GenerationKey\" IS NULL AND \"PolicyVersion\" IS NULL AND \"MentorScheduleRuleId\" IS NULL AND \"LocalBusinessDate\" IS NULL AND \"GroupPolicyId\" IS NULL AND \"SessionMinutesSnapshot\" IS NULL AND \"RestMinutesSnapshot\" IS NULL) OR (\"GenerationKey\" IS NOT NULL AND \"PolicyVersion\" IS NOT NULL AND \"PolicyVersion\" > 0 AND (\"MentorScheduleRuleId\" IS NOT NULL OR \"TeachingProposalId\" IS NOT NULL) AND \"LocalBusinessDate\" IS NOT NULL AND ((\"GroupPolicyId\" IS NULL AND \"SessionMinutesSnapshot\" IS NULL AND \"RestMinutesSnapshot\" IS NULL AND \"MaxLearners\" = 1 AND \"EndTime\" = \"StartTime\" + INTERVAL '90 minutes') OR (\"GroupPolicyId\" IS NOT NULL AND \"SessionMinutesSnapshot\" > 0 AND \"RestMinutesSnapshot\" >= 0 AND \"MaxLearners\" BETWEEN 1 AND 50 AND \"EndTime\" = \"StartTime\" + \"SessionMinutesSnapshot\" * INTERVAL '1 minute')))"); + }); + + b.HasData( + new + { + Id = 990001, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 1, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 2, 10, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900002, + RoomId = new Guid("a1000000-0000-0000-0000-000000990001"), + StartTime = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990002, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 3, 14, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900002, + RoomId = new Guid("a1000000-0000-0000-0000-000000990002"), + StartTime = new DateTime(2026, 10, 3, 13, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990003, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 4, 10, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900003, + RoomId = new Guid("a1000000-0000-0000-0000-000000990003"), + StartTime = new DateTime(2026, 10, 4, 9, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990004, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 5, 14, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900003, + RoomId = new Guid("a1000000-0000-0000-0000-000000990004"), + StartTime = new DateTime(2026, 10, 5, 13, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBankAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountHolderName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AccountNumberHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AccountVersion") + .HasColumnType("integer"); + + b.Property("BankCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("BankName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedAccountNumber") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsCurrent") + .HasColumnType("boolean"); + + b.Property("MaskedAccountNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("VerificationNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VerificationStatus") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedByAdminId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorUserId") + .IsUnique() + .HasDatabaseName("IX_MentorBankAccounts_MentorUserId_Current") + .HasFilter("\"IsCurrent\" = TRUE"); + + b.HasIndex("VerifiedByAdminId"); + + b.HasIndex("MentorUserId", "AccountVersion") + .IsUnique(); + + b.ToTable("MentorBankAccounts", t => + { + t.HasCheckConstraint("CK_MentorBankAccount_Version", "\"AccountVersion\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttendedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CancellationReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CancelledByRole") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CancelledByUserId") + .HasColumnType("integer"); + + b.Property("CompensationCurrency") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CompensationFormulaVersion") + .HasColumnType("integer"); + + b.Property("CompensationLevelId") + .HasColumnType("integer"); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditGrantId") + .HasColumnType("bigint"); + + b.Property("ExceptionApproved") + .HasColumnType("boolean"); + + b.Property("ExceptionReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExceptionRequested") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MeetingLink") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeFeedback") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PracticeFeedbackAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeScore") + .HasColumnType("integer"); + + b.Property("Question") + .HasColumnType("text"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ScheduledCompensationAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserSubscriptionId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CompensationLevelId"); + + b.HasIndex("CreditGrantId"); + + b.HasIndex("MentorAvailabilityId", "LearnerId") + .IsUnique() + .HasFilter("\"MentorAvailabilityId\" IS NOT NULL AND \"LearnerId\" IS NOT NULL AND NOT \"IsDeleted\" AND \"Status\" <> 'Cancelled'"); + + b.HasIndex("MentorAvailabilityId", "UserSubscriptionId") + .IsUnique() + .HasFilter("NOT \"IsDeleted\" AND \"Status\" <> 'Cancelled'"); + + b.HasIndex("UserSubscriptionId", "Status"); + + b.ToTable("MentorBookings"); + + b.HasData( + new + { + Id = 990001, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Meeting demo để kiểm thử phòng họp trên frontend.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990001, + Version = 0u + }, + new + { + Id = 990002, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Em muốn nhờ Mentor giải đáp phần ngữ pháp N3 bài 5.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990002, + Version = 0u + }, + new + { + Id = 990003, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Hỏi về cách phân biệt giữa ~てくる và ~ていく.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990003, + Version = 0u + }, + new + { + Id = 990004, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Tư vấn phương pháp luyện nghe JLPT N3 hiệu quả.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990004, + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingDayGuard", b => + { + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("ActiveBookingCount") + .HasColumnType("integer"); + + b.HasKey("MentorId", "LocalBusinessDate"); + + b.ToTable("MentorBookingDayGuards", null, t => + { + t.HasCheckConstraint("CK_MentorBookingDayGuard_Count", "\"ActiveBookingCount\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingIntent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IntentKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("RequestHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("LearnerId", "IntentKey") + .IsUnique(); + + b.ToTable("MentorBookingIntents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingReservation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EndUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("ReleasedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RestProtectedUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("StartUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MentorAvailabilityId") + .HasFilter("\"ReleasedAtUtc\" IS NULL"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("MentorAvailabilityId", "MentorId"); + + b.HasIndex("MentorId", "LocalBusinessDate", "ReleasedAtUtc"); + + b.ToTable("MentorBookingReservations", null, t => + { + t.HasCheckConstraint("CK_MentorBookingReservation_Interval", "\"EndUtc\" > \"StartUtc\""); + + t.HasCheckConstraint("CK_MentorBookingReservation_PolicyVersion", "\"PolicyVersion\" > 0"); + + t.HasCheckConstraint("CK_MentorBookingReservation_Rest", "\"RestProtectedUntilUtc\" >= \"EndUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingTerms", b => + { + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ConfirmedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("ScheduledEndUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduledStartUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MentorBookingId"); + + b.HasIndex("MentorAvailabilityId"); + + b.ToTable("MentorBookingTerms", null, t => + { + t.HasCheckConstraint("CK_MentorBookingTerms_Interval", "\"ScheduledEndUtc\" > \"ScheduledStartUtc\""); + + t.HasCheckConstraint("CK_MentorBookingTerms_PolicyVersion", "\"PolicyVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCalendarConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("LastSyncedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("ProtectedRefreshToken") + .HasColumnType("text"); + + b.Property("StateExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StateHash") + .HasColumnType("text"); + + b.Property("SyncedEventsJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("MentorId") + .IsUnique(); + + b.HasIndex("StateHash") + .IsUnique(); + + b.ToTable("MentorCalendarConnections", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorChatMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ReadAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderUserId") + .HasColumnType("integer"); + + b.Property("SentAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("SenderUserId"); + + b.HasIndex("MentorBookingId", "Id"); + + b.HasIndex("MentorBookingId", "ReadAt", "SenderUserId"); + + b.ToTable("MentorChatMessages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreditGrantId") + .HasColumnType("bigint"); + + b.Property("EntryType") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId"); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("CreditGrantId", "EntryType"); + + b.HasIndex("MentorBookingId", "EntryType"); + + b.ToTable("MentorCreditEntries", null, t => + { + t.HasCheckConstraint("CK_MentorCreditEntry_Amount", "\"Amount\" <> 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AvailableQuantity") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("InitialQuantity") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("UserSubscriptionId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserSubscriptionId") + .IsUnique(); + + b.HasIndex("LearnerId", "ExpiresAtUtc"); + + b.HasIndex("LearnerId", "CertificateLevelId", "ExpiresAtUtc"); + + b.ToTable("MentorCreditGrants", null, t => + { + t.HasCheckConstraint("CK_MentorCreditGrant_PolicyVersion", "\"PolicyVersion\" > 0"); + + t.HasCheckConstraint("CK_MentorCreditGrant_Quantity", "\"InitialQuantity\" > 0 AND \"AvailableQuantity\" >= 0 AND \"AvailableQuantity\" <= \"InitialQuantity\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminDecision") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("AdminNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Category") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditRefunded") + .HasColumnType("boolean"); + + b.Property("EvidenceUrls") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("IsRefundApproved") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRespondedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorResponse") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RefundOperationKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ResolvedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ResolvedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId") + .HasDatabaseName("IX_MentorDisputes_LearnerId"); + + b.HasIndex("MentorBookingId") + .HasDatabaseName("IX_MentorDisputes_MentorBookingId"); + + b.HasIndex("MentorId") + .HasDatabaseName("IX_MentorDisputes_MentorId"); + + b.HasIndex("ResolvedByAdminId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorDisputes_Status"); + + b.ToTable("MentorDisputes", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDisputeHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("DisputeId") + .HasColumnType("integer"); + + b.Property("NewStatus") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("PreviousStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DisputeId") + .HasDatabaseName("IX_MentorDisputeHistories_DisputeId"); + + b.ToTable("MentorDisputeHistories", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorEarningEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("AttendanceApprovalId") + .HasColumnType("bigint"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("FormulaVersion") + .HasColumnType("integer"); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("GrossAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("JlptLevelCode") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("AttendanceApprovalId") + .IsUnique(); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.HasIndex("MentorUserId", "Status"); + + b.ToTable("MentorEarningEntries", t => + { + t.HasCheckConstraint("CK_MentorEarningEntry_Positive", "\"FrozenHourlyRate\" > 0 AND \"FrozenLevelCoefficient\" > 0 AND \"ApprovedEligibleMinutes\" > 0 AND \"ApprovedEligibleMinutes\" <= 90 AND \"GrossAmount\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorGroupPolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CancellationLeadHours") + .HasColumnType("integer"); + + b.Property("CheckoutHoldMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("DeletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedByAdminId") + .HasColumnType("integer"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("HomeworkDeadlineDays") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsArchivedRevision") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KpiReportingPeriodDays") + .HasColumnType("integer"); + + b.Property("LastAppliedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedByAdminId") + .HasColumnType("integer"); + + b.Property("LearnerTransferEnabled") + .HasColumnType("boolean"); + + b.Property("MaxLearners") + .HasColumnType("integer"); + + b.Property("MentorReplacementEnabled") + .HasColumnType("boolean"); + + b.Property("MentorReplacementLeadHours") + .HasColumnType("integer"); + + b.Property("MinimumPreparationDays") + .HasColumnType("integer"); + + b.Property("MinimumPublishedEnrollmentDays") + .HasColumnType("integer"); + + b.Property("PlacementAttemptLimit") + .HasColumnType("integer"); + + b.Property("RemediationAttendanceThresholdPercent") + .ValueGeneratedOnAdd() + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasDefaultValue(90m); + + b.Property("RemediationCompletionThresholdPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("RemediationThresholdComparison") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("RequireAdminRemediationReview") + .HasColumnType("boolean"); + + b.Property("RequireOfficialExamEvidence") + .HasColumnType("boolean"); + + b.Property("ReschedulingLeadHours") + .HasColumnType("integer"); + + b.Property("RestMinutes") + .HasColumnType("integer"); + + b.Property("RetakeSupportEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("TransferAllowedAfterSourceStart") + .HasColumnType("boolean"); + + b.Property("TuitionPerSessionN2") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN3") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN4") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN5") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedByAdminId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("DeletedByAdminId"); + + b.HasIndex("EffectiveFromUtc"); + + b.HasIndex("IsActive") + .IsUnique() + .HasDatabaseName("IX_MentorGroupPolicies_SingleActive") + .HasFilter("\"IsActive\" = TRUE"); + + b.HasIndex("LastAppliedByAdminId"); + + b.HasIndex("UpdatedByAdminId"); + + b.HasIndex("Version") + .IsUnique() + .HasDatabaseName("IX_MentorGroupPolicies_LiveVersion") + .HasFilter("\"IsArchivedRevision\" = FALSE"); + + b.ToTable("MentorGroupPolicies", null, t => + { + t.HasCheckConstraint("CK_MentorGroupPolicy_Capacity", "\"MaxLearners\" BETWEEN 1 AND 50"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_CheckoutHold", "\"CheckoutHoldMinutes\" BETWEEN 1 AND 60"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Comparison", "\"RemediationThresholdComparison\" IN ('>', '>=')"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_EnrollmentDays", "\"MinimumPublishedEnrollmentDays\" BETWEEN 1 AND 180"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Evidence", "\"RequireOfficialExamEvidence\" AND \"RequireAdminRemediationReview\""); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Positive", "\"Version\" > 0 AND \"SessionMinutes\" > 0 AND \"RestMinutes\" >= 0 AND \"MinimumPreparationDays\" >= 1 AND \"CancellationLeadHours\" >= 0 AND \"ReschedulingLeadHours\" >= 0 AND \"HomeworkDeadlineDays\" > 0 AND \"PlacementAttemptLimit\" > 0 AND \"KpiReportingPeriodDays\" > 0"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Remediation", "\"RemediationCompletionThresholdPercent\" > 0 AND \"RemediationCompletionThresholdPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_RemediationAttendance", "\"RemediationAttendanceThresholdPercent\" > 0 AND \"RemediationAttendanceThresholdPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_ReplacementLead", "\"MentorReplacementLeadHours\" BETWEEN 0 AND 720"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_State", "\"Revision\" > 0 AND NOT (\"IsActive\" AND (\"IsArchivedRevision\" OR \"IsDeleted\"))"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_TransferAfterStart", "\"LearnerTransferEnabled\" OR NOT \"TransferAllowedAfterSourceStart\""); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Tuition", "\"TuitionPerSessionN5\" >= 0 AND \"TuitionPerSessionN4\" >= 0 AND \"TuitionPerSessionN3\" >= 0 AND \"TuitionPerSessionN2\" >= 0"); + }); + + b.HasData( + new + { + Id = 1, + CancellationLeadHours = 24, + CheckoutHoldMinutes = 10, + CreatedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + EffectiveFromUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + HomeworkDeadlineDays = 7, + IsActive = true, + IsArchivedRevision = false, + IsDeleted = false, + KpiReportingPeriodDays = 30, + LastAppliedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + LearnerTransferEnabled = true, + MaxLearners = 4, + MentorReplacementEnabled = true, + MentorReplacementLeadHours = 24, + MinimumPreparationDays = 1, + MinimumPublishedEnrollmentDays = 7, + PlacementAttemptLimit = 2, + RemediationAttendanceThresholdPercent = 90m, + RemediationCompletionThresholdPercent = 90m, + RemediationThresholdComparison = ">", + RequireAdminRemediationReview = true, + RequireOfficialExamEvidence = true, + ReschedulingLeadHours = 24, + RestMinutes = 15, + RetakeSupportEnabled = true, + Revision = 1, + SessionMinutes = 90, + TransferAllowedAfterSourceStart = false, + TuitionPerSessionN2 = 110000m, + TuitionPerSessionN3 = 90000m, + TuitionPerSessionN4 = 75000m, + TuitionPerSessionN5 = 60000m, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorHourlyRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountPerHour") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ConfiguredByAdminId"); + + b.HasIndex("MentorUserId", "EffectiveFromUtc") + .IsUnique(); + + b.ToTable("MentorHourlyRates", t => + { + t.HasCheckConstraint("CK_MentorHourlyRate_Positive", "\"AmountPerHour\" > 0"); + + t.HasCheckConstraint("CK_MentorHourlyRate_Range", "\"EffectiveUntilUtc\" IS NULL OR \"EffectiveUntilUtc\" > \"EffectiveFromUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorOutboxEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AggregateId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("AggregateType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("AvailableAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeliveredAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EventKey") + .IsRequired() + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("EventVersion") + .HasColumnType("integer"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("EventKey") + .IsUnique(); + + b.HasIndex("DeliveredAtUtc", "AvailableAtUtc", "CreatedAtUtc"); + + b.ToTable("MentorOutboxEvents", null, t => + { + t.HasCheckConstraint("CK_MentorOutbox_Attempts", "\"Attempts\" >= 0"); + + t.HasCheckConstraint("CK_MentorOutbox_EventVersion", "\"EventVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("AttemptNumber") + .HasColumnType("integer"); + + b.Property("BatchId") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ConfirmedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("ErrorCode") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ErrorMessage") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceStorageKey") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExecutionMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("IdempotencyKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("InitiatedByAdminId") + .HasColumnType("integer"); + + b.Property("InternalStatus") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("LockedBankAccountId") + .HasColumnType("bigint"); + + b.Property("PayoutObligationId") + .HasColumnType("bigint"); + + b.Property("ProviderPayoutId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProviderStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("TransferReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ConfirmedByAdminId"); + + b.HasIndex("IdempotencyKey") + .IsUnique(); + + b.HasIndex("InitiatedByAdminId"); + + b.HasIndex("LockedBankAccountId"); + + b.HasIndex("PayoutObligationId") + .IsUnique() + .HasDatabaseName("IX_MentorPayoutAttempts_OneSucceededPerObligation") + .HasFilter("\"InternalStatus\" = 'Succeeded'"); + + b.HasIndex("TransferReference") + .IsUnique() + .HasDatabaseName("IX_MentorPayoutAttempts_SucceededTransferReference") + .HasFilter("\"TransferReference\" IS NOT NULL AND \"InternalStatus\" = 'Succeeded'"); + + b.HasIndex("PayoutObligationId", "AttemptNumber") + .IsUnique(); + + b.ToTable("MentorPayoutAttempts", t => + { + t.HasCheckConstraint("CK_MentorPayoutAttempt_ManualEvidence", "(\"ExecutionMethod\" <> 'ManualBankTransfer' OR \"InternalStatus\" <> 'Succeeded') OR (\"TransferReference\" IS NOT NULL AND \"EvidenceStorageKey\" IS NOT NULL)"); + + t.HasCheckConstraint("CK_MentorPayoutAttempt_Positive", "\"Amount\" > 0 AND \"AttemptNumber\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActiveAttemptId") + .HasColumnType("bigint"); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("LockedBankAccountId") + .HasColumnType("bigint"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("OrganizationPayoutAccountId") + .HasColumnType("bigint"); + + b.Property("PayableAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("SelectedMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SettledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SettledAttemptId") + .HasColumnType("bigint"); + + b.Property("SettledReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("LockedBankAccountId"); + + b.HasIndex("MentorUserId"); + + b.HasIndex("OrganizationPayoutAccountId"); + + b.HasIndex("PayrollPeriodId") + .IsUnique(); + + b.ToTable("MentorPayoutObligations", t => + { + t.HasCheckConstraint("CK_MentorPayoutObligation_Positive", "\"PayableAmount\" > 0"); + + t.HasCheckConstraint("CK_MentorPayoutObligation_Settlement", "(\"Status\" <> 'Paid') OR (\"SettledAttemptId\" IS NOT NULL AND \"SettledReference\" IS NOT NULL AND \"SettledAtUtc\" IS NOT NULL)"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollAdjustment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RelatedBookingId") + .HasColumnType("integer"); + + b.Property("RelatedEarningEntryId") + .HasColumnType("bigint"); + + b.Property("SignedAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.ToTable("MentorPayrollAdjustments", t => + { + t.HasCheckConstraint("CK_MentorPayrollAdjustment_NonZero", "\"SignedAmount\" <> 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollLine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EarningEntryId") + .HasColumnType("bigint"); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("LineAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("EarningEntryId") + .IsUnique(); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.ToTable("MentorPayrollLines", t => + { + t.HasCheckConstraint("CK_MentorPayrollLine_Positive", "\"LineAmount\" > 0 AND \"ApprovedEligibleMinutes\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovalNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ApprovedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("ClosedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("GrossPayableAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("Month") + .HasColumnType("integer"); + + b.Property("PreparedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PreparedByAdminId") + .HasColumnType("integer"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SupplementalReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("TotalAdjustmentsAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("TotalEarningsAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.Property("Year") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("PreparedByAdminId"); + + b.HasIndex("MentorUserId", "Year", "Month", "SequenceNumber", "Currency") + .IsUnique(); + + b.ToTable("MentorPayrollPeriods", t => + { + t.HasCheckConstraint("CK_MentorPayrollPeriod_Payable", "\"TotalEarningsAmount\" >= 0 AND \"GrossPayableAmount\" >= 0"); + + t.HasCheckConstraint("CK_MentorPayrollPeriod_Period", "\"Year\" >= 2020 AND \"Year\" <= 2100 AND \"Month\" >= 1 AND \"Month\" <= 12 AND \"SequenceNumber\" >= 1"); + + t.HasCheckConstraint("CK_MentorPayrollPeriod_Supplemental", "\"SequenceNumber\" = 1 OR (\"SupplementalReason\" IS NOT NULL AND length(trim(\"SupplementalReason\")) > 0)"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorProfile", b => + { + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Bio") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Expertise") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IntroductionVideoUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectionReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("VerificationDocumentUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VerificationStatus") + .IsConcurrencyToken() + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Workplace") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("YearsOfExperience") + .HasColumnType("integer"); + + b.HasKey("MentorId"); + + b.ToTable("MentorProfiles", (string)null); + + b.HasData( + new + { + MentorId = 900002, + Bio = "Chuyên gia tiếng Nhật với 8 năm kinh nghiệm giảng dạy JLPT N1, N2 và tiếng Nhật doanh nghiệp.", + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + Expertise = "Luyện thi JLPT N1-N2, Tiếng Nhật thương mại, Phỏng vấn xin việc", + IsDeleted = false, + JlptLevel = "N1", + ReviewedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + ReviewedByAdminName = "Admin System", + SubmittedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + VerificationStatus = "Approved", + Workplace = "Riki Nihongo Academy", + YearsOfExperience = 8 + }, + new + { + MentorId = 900003, + Bio = "Giảng viên tiếng Nhật bản xứ, chuyên sâu về phát âm và giao tiếp Kaiwa thực tế.", + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + Expertise = "Giao tiếp Kaiwa tự nhiên, Luyện phát âm chuẩn Tokyo, JLPT N3-N2", + IsDeleted = false, + JlptLevel = "N1", + ReviewedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + ReviewedByAdminName = "Admin System", + SubmittedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + VerificationStatus = "Approved", + Workplace = "Riki Nihongo Academy", + YearsOfExperience = 5 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("IsPublic") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRepliedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorReply") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModerationStatus") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId") + .HasDatabaseName("IX_MentorReviews_LearnerId"); + + b.HasIndex("MentorBookingId") + .IsUnique() + .HasDatabaseName("IX_MentorReviews_MentorBookingId"); + + b.HasIndex("MentorId", "IsPublic", "ModerationStatus") + .HasDatabaseName("IX_MentorReviews_Mentor_Public_Status"); + + b.ToTable("MentorReviews", null, t => + { + t.HasCheckConstraint("CK_MentorReview_Rating_Range", "\"Rating\" >= 1 AND \"Rating\" <= 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AutoPublish") + .HasColumnType("boolean"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("GeneratedThrough") + .HasColumnType("date"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("TimeZoneId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("MentorId", "PolicyVersion") + .IsUnique(); + + b.ToTable("MentorSchedules", null, t => + { + t.HasCheckConstraint("CK_MentorSchedule_PolicyVersion", "\"PolicyVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorScheduleRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DaypartCode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("LocalEnd") + .HasColumnType("time without time zone"); + + b.Property("LocalStart") + .HasColumnType("time without time zone"); + + b.Property("ScheduleId") + .HasColumnType("bigint"); + + b.Property("Weekday") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId", "Weekday", "DaypartCode", "EffectiveFrom") + .IsUnique(); + + b.ToTable("MentorScheduleRules", null, t => + { + t.HasCheckConstraint("CK_MentorScheduleRule_Daypart", "\"DaypartCode\" IN ('Morning', 'Noon', 'Afternoon', 'Evening')"); + + t.HasCheckConstraint("CK_MentorScheduleRule_Time", "\"LocalEnd\" > \"LocalStart\""); + + t.HasCheckConstraint("CK_MentorScheduleRule_Weekday", "\"Weekday\" BETWEEN 0 AND 6"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CourseDurationWeeks") + .HasColumnType("integer"); + + b.Property("CourseObjective") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("CoursePlanId") + .HasColumnType("integer"); + + b.Property("CourseTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpectedStartDate") + .HasColumnType("date"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("HiddenFromMentorAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHiddenFromMentorHistory") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastSavedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("OpenEnrollmentIdempotencyKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OpenedClassAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OptionalAttachmentsJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("OptionalNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("ProgramType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ReviewReason") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionDurationMinutes") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("SubmissionIdempotencyKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("WeeklySessionsJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CoursePlanId"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("ReviewedByAdminId"); + + b.HasIndex("MentorId", "OpenEnrollmentIdempotencyKey") + .IsUnique() + .HasDatabaseName("IX_MentorTeachingProposals_MentorId_OpenEnrollmentIdempotencyKey") + .HasFilter("\"OpenEnrollmentIdempotencyKey\" IS NOT NULL"); + + b.HasIndex("MentorId", "SubmissionIdempotencyKey") + .IsUnique() + .HasDatabaseName("IX_MentorTeachingProposals_MentorId_SubmissionIdempotencyKey") + .HasFilter("\"SubmissionIdempotencyKey\" IS NOT NULL"); + + b.HasIndex("Status", "SubmittedAtUtc"); + + b.HasIndex("MentorId", "Status", "UpdatedAtUtc"); + + b.ToTable("MentorTeachingProposals", null, t => + { + t.HasCheckConstraint("CK_MentorTeachingProposal_Duration", "\"CourseDurationWeeks\" BETWEEN 1 AND 104 AND \"SessionDurationMinutes\" BETWEEN 30 AND 240"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_ProgramType", "\"ProgramType\" IN ('StandardJlpt', 'IntensiveJlpt', 'ExamPrepJlpt', 'CustomJlpt')"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_Revision", "\"Revision\" > 0"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_Status", "\"Status\" IN ('Draft', 'PendingReview', 'ChangesRequested', 'Approved', 'OpenedClass', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposalEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(48) + .HasColumnType("character varying(48)"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ActorUserId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("FromStatus") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ProposalId") + .HasColumnType("integer"); + + b.Property("Reason") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("RevisionAfter") + .HasColumnType("integer"); + + b.Property("SnapshotJson") + .HasColumnType("jsonb"); + + b.Property("ToStatus") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("ProposalId", "CreatedAtUtc"); + + b.ToTable("MentorTeachingProposalEvents", null, t => + { + t.HasCheckConstraint("CK_MentorTeachingProposalEvent_RevisionAfter", "\"RevisionAfter\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingQualification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedByAdminId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("VerifiedByAdminId"); + + b.HasIndex("MentorUserId", "CertificateLevelId") + .IsUnique() + .HasFilter("\"IsActive\" = TRUE"); + + b.ToTable("MentorTeachingQualifications", t => + { + t.HasCheckConstraint("CK_MentorTeachingQualification_Revoked", "\"RevokedAtUtc\" IS NULL OR \"RevokedAtUtc\" >= \"VerifiedAtUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Date") + .HasColumnType("date"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Period") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorId", "Date", "Period") + .IsUnique() + .HasFilter("NOT \"IsDeleted\""); + + b.ToTable("MentorWeeklyAvailabilities", t => + { + t.HasCheckConstraint("CK_MentorWeeklyAvailability_Period", "\"Period\" IN ('Morning', 'Afternoon', 'Evening')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("AnswerKeyJson") + .HasColumnType("jsonb"); + + b.Property("AudioTranscript") + .HasColumnType("text"); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("ContentFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Difficulty") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("GroupSortOrder") + .HasColumnType("integer"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("InteractionDataJson") + .HasColumnType("jsonb"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("MockTestSectionId") + .HasColumnType("integer") + .HasColumnName("PracticeTestSectionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionsJson") + .HasColumnType("jsonb"); + + b.Property("ParentQuestionId") + .HasColumnType("integer"); + + b.Property("PassageId") + .HasColumnType("integer"); + + b.Property("PlaybackPolicyJson") + .HasColumnType("jsonb"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("QuestionGroupTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("QuestionIdentity") + .HasColumnType("uuid"); + + b.Property("QuestionText") + .IsRequired() + .HasColumnType("text"); + + b.Property("QuestionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("SingleChoice"); + + b.Property("QuestionVersion") + .HasColumnType("integer"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SkillMetadataJson") + .HasColumnType("jsonb"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceQuestionId") + .HasColumnType("integer"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("Manual"); + + b.Property("TagsJson") + .HasColumnType("jsonb"); + + b.Property("TemplateKind") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Topic") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.HasKey("Id"); + + b.HasIndex("ContentFingerprint"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("PassageId"); + + b.HasIndex("QuestionIdentity"); + + b.HasIndex("SourceQuestionId"); + + b.HasIndex("MockTestSectionId", "IsArchivedVersion"); + + b.HasIndex("CertificateLevelId", "LanguageSkillId", "PublishStatus", "IsArchivedVersion"); + + b.ToTable("MockQuestions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestionOption", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockQuestionId") + .HasColumnType("integer") + .HasColumnName("PracticeQuestionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionText") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockQuestionId"); + + b.ToTable("MockQuestionOptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("BlueprintPolicyJson") + .HasColumnType("jsonb"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ExamKind") + .HasColumnType("integer"); + + b.Property("FocusSkillId") + .HasColumnType("integer"); + + b.Property("IncludedSkillsJson") + .HasColumnType("jsonb"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsManagedWorkflow") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ParentExamId") + .HasColumnType("integer"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TagsJson") + .HasColumnType("jsonb"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserAccountId"); + + b.ToTable("MockTests"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAnswer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiExplanationGeneratedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AiExplanationInputJson") + .HasColumnType("jsonb"); + + b.Property("AiExplanationJson") + .HasColumnType("jsonb"); + + b.Property("AiExplanationVersion") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockQuestionId") + .HasColumnType("integer") + .HasColumnName("PracticeQuestionId"); + + b.Property("MockTestAttemptId") + .HasColumnType("integer") + .HasColumnName("PracticeTestAttemptId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ResponseJson") + .HasColumnType("jsonb"); + + b.Property("SelectedOptionId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockQuestionId"); + + b.HasIndex("SelectedOptionId"); + + b.HasIndex("MockTestAttemptId", "MockQuestionId") + .IsUnique(); + + b.ToTable("MockTestAnswers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttemptKind") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsPlacementAssessment") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("QuestionSnapshotJson") + .HasColumnType("text"); + + b.Property("StartedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalScore") + .HasColumnType("double precision"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StartedAt"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "AttemptKind") + .IsUnique() + .HasFilter("\"AttemptKind\" = 1 AND \"IsCompleted\" = false AND \"IsDeleted\" = false"); + + b.ToTable("MockTestAttempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateSectionId") + .HasColumnType("integer") + .HasColumnName("CertificationSectionId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DurationMinutes") + .HasColumnType("integer"); + + b.Property("Instructions") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer") + .HasColumnName("SkillId"); + + b.Property("MockTestId") + .HasColumnType("integer") + .HasColumnName("MockTestId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SectionPolicyJson") + .HasColumnType("jsonb"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateSectionId"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("MockTestId", "CertificateSectionId"); + + b.ToTable("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSectionResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CorrectCount") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockTestAttemptId") + .HasColumnType("integer") + .HasColumnName("MockTestAttemptId"); + + b.Property("MockTestSectionId") + .HasColumnType("integer") + .HasColumnName("MockTestSectionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ScorePercent") + .HasColumnType("double precision"); + + b.Property("TotalCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockTestSectionId"); + + b.HasIndex("MockTestAttemptId", "MockTestSectionId") + .IsUnique(); + + b.ToTable("MockTestSectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Note", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AnsweredAt") + .HasColumnType("timestamp without time zone"); + + b.Property("AuthorRole") + .IsRequired() + .HasColumnType("text"); + + b.Property("Content") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("Notes"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("NormalizedName") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_NotebookFolders_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("UserId", "NormalizedName") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("UserId", "IsDeleted", "SortOrder"); + + b.ToTable("NotebookFolders", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChecklistCompletedCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ChecklistTotalCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ContentFormatVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ContentJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'{\"type\":\"doc\",\"version\":1,\"blocks\":[]}'::jsonb"); + + b.Property("ContentPlainText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue(""); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FavoritedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastAutosavedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerNoteId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_NotebookPages_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("LearnerNoteId", "IsDeleted", "SortOrder"); + + b.HasIndex("UserId", "IsDeleted", "IsFavorite"); + + b.ToTable("NotebookPages", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DeliveredTokens") + .HasColumnType("text"); + + b.Property("IdempotencyKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("LinkUrl") + .HasColumnType("text"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.OrganizationPayoutAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountHolderName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("BankCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("BankName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ChannelCode") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("MaskedAccountNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ProviderAccountReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProviderType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelCode") + .IsUnique(); + + b.HasIndex("ConfiguredByAdminId"); + + b.ToTable("OrganizationPayoutAccounts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PassingScorePercent") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(70.0); + + b.Property("Scope") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("LessonQuickCheck"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("TopicId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("TopicId"); + + b.HasIndex("LessonId", "LanguageSkillId"); + + b.HasIndex("Scope", "CertificateLevelId"); + + b.HasIndex("Scope", "TopicId"); + + b.ToTable("PracticeExercises"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.Property("ScorePercent") + .HasColumnType("double precision"); + + b.Property("StartedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeExerciseId"); + + b.HasIndex("HomeworkAssignmentId", "PracticeExerciseId") + .IsUnique(); + + b.HasIndex("UserId", "PracticeExerciseId", "StartedAt"); + + b.ToTable("PracticeExerciseAttempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.Property("QuestionText") + .IsRequired() + .HasColumnType("text"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeExerciseId"); + + b.ToTable("PracticeQuestions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestionOption", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("PracticeQuestionId") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeQuestionId"); + + b.ToTable("PracticeQuestionOptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TextContent") + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserId", "Type", "SubmittedAt"); + + b.ToTable("PracticeSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.RecommendedLearningPath", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BaseActivePathId") + .HasColumnType("integer"); + + b.Property("ConfirmedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("GeneratedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsViewed") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PreviewExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StartingCertificateLevelId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SuggestionJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Summary") + .HasColumnType("text"); + + b.Property("TargetCertificateLevelId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasFilter("\"Status\" = 'Active'"); + + b.HasIndex("UserId", "GeneratedAt"); + + b.HasIndex("UserId", "Version") + .IsUnique(); + + b.ToTable("RecommendedLearningPaths"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcceptedReadingsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ArchivedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("AudioUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("BackText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)") + .HasDefaultValue(""); + + b.Property("CardType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("Vocabulary"); + + b.Property("ContextSnippet") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CorrectCount") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EaseFactor") + .HasColumnType("double precision"); + + b.Property("ExampleMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FrontText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasDefaultValue(""); + + b.Property("GrammarPatternId") + .HasColumnType("integer") + .HasColumnName("GrammarPointId"); + + b.Property("IncorrectCount") + .HasColumnType("integer"); + + b.Property("IntervalDays") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.Property("Lapses") + .HasColumnType("integer"); + + b.Property("LastReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerNoteEntryId") + .HasColumnType("integer") + .HasColumnName("VocabularyNoteEntryId"); + + b.Property("LearningState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("New"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("MasteredAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Meaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Mode") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NextReviewDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NormalizedContentKey") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(300) + .HasColumnType("character varying(300)") + .HasDefaultValue(""); + + b.Property("PersonalNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Reading") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Repetitions") + .HasColumnType("integer"); + + b.Property("Revision") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourceLabel") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceLinksJson") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("Manual"); + + b.Property("SourceVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SrsCardTemplateId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Active"); + + b.Property("SuspendedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SynonymsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.Property("WritingCorrectStrokeCount") + .HasColumnType("integer"); + + b.Property("WritingPracticeMode") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("WritingScore") + .HasColumnType("integer"); + + b.Property("WritingScoreUpdatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("WritingTotalStrokeCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("LearnerNoteEntryId"); + + b.HasIndex("LessonId"); + + b.HasIndex("SrsCardTemplateId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("UserId", "NextReviewDate"); + + b.HasIndex("UserId", "GrammarPatternId", "Mode") + .IsUnique() + .HasFilter("\"GrammarPointId\" IS NOT NULL"); + + b.HasIndex("UserId", "KanjiId", "Mode") + .IsUnique() + .HasFilter("\"KanjiEntryId\" IS NOT NULL"); + + b.HasIndex("UserId", "NormalizedContentKey", "Mode") + .IsUnique() + .HasFilter("\"NormalizedContentKey\" <> '' AND \"IsDeleted\" = false"); + + b.HasIndex("UserId", "VocabularyId", "Mode") + .IsUnique() + .HasFilter("\"VocabularyId\" IS NOT NULL"); + + b.HasIndex("UserId", "Status", "LearningState", "NextReviewDate"); + + b.ToTable("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IdempotencyKey") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NewEaseFactor") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(2.5); + + b.Property("NewIntervalDays") + .HasColumnType("integer"); + + b.Property("NewState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Learning"); + + b.Property("PreviousEaseFactor") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(2.5); + + b.Property("PreviousIntervalDays") + .HasColumnType("integer"); + + b.Property("PreviousState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("New"); + + b.Property("Quality") + .HasColumnType("integer"); + + b.Property("Rating") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("ResponseTimeMs") + .HasColumnType("integer"); + + b.Property("ReviewCardId") + .HasColumnType("integer") + .HasColumnName("ReviewItemId"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SessionReference") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("StudyMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("flip"); + + b.Property("UserAnswer") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("SessionReference"); + + b.HasIndex("ReviewCardId", "IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.HasIndex("ReviewCardId", "ReviewedAt"); + + b.ToTable("ReviewHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsCardTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcceptedReadingsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("AudioUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("BackText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CardType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FrontText") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("KanjiId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("Meaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NormalizedContentKey") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Reading") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ReviewNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedByUserId") + .HasColumnType("integer"); + + b.Property("SynonymsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UsageNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("LessonId"); + + b.HasIndex("NormalizedContentKey"); + + b.HasIndex("ReviewedByAdminId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("SubmittedByUserId", "Status"); + + b.HasIndex("Status", "JlptLevel", "CardType"); + + b.ToTable("SrsCardTemplates"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsReviewSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CompletedCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DeadlineAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("FilterCardType") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("FilterJlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("FilterLearningState") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("FilterSourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ForgotCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastActivityAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ProcessedStepKeysJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)") + .HasDefaultValue("[]"); + + b.Property("QueueCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("RememberedCount") + .HasColumnType("integer"); + + b.Property("RequestedCount") + .HasColumnType("integer"); + + b.Property("RetryCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("ReviewedCount") + .HasColumnType("integer"); + + b.Property("SelectionScope") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SessionKey") + .HasColumnType("uuid"); + + b.Property("SessionKind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Scheduled"); + + b.Property("ShuffleEnabled") + .HasColumnType("boolean"); + + b.Property("StartedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StudyMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TotalInitialCards") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SessionKey") + .IsUnique(); + + b.HasIndex("UserId", "Status", "LastActivityAtUtc"); + + b.HasIndex("UserId", "SessionKind", "Status", "LastActivityAtUtc"); + + b.ToTable("SrsReviewSessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CancellationReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Capacity") + .HasColumnType("integer"); + + b.Property("CapacitySnapshot") + .HasColumnType("integer"); + + b.Property("CourseDurationWeeks") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("EndsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("EnrollmentClosedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentClosesAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentOpensAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SourceProposalId") + .HasColumnType("integer"); + + b.Property("StartsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TotalTuitionSnapshot") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionSnapshot") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("TuitionSnapshotAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PlanId"); + + b.HasIndex("SourceProposalId") + .IsUnique() + .HasFilter("\"SourceProposalId\" IS NOT NULL"); + + b.ToTable("StudyCohorts", null, t => + { + t.HasCheckConstraint("CK_StudyCohort_Capacity", "\"Capacity\" > 0"); + + t.HasCheckConstraint("CK_StudyCohort_DurationWeeks", "\"CourseDurationWeeks\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortMentorAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AffectedSessionCount") + .HasColumnType("integer"); + + b.Property("AssignedById") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromSessionNumber") + .HasColumnType("integer"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("ImpactSnapshot") + .IsRequired() + .HasColumnType("text"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("PreviousMentorId") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.HasKey("Id"); + + b.HasIndex("AssignedById"); + + b.HasIndex("IdempotencyKey") + .IsUnique(); + + b.HasIndex("MentorId"); + + b.HasIndex("PolicyId"); + + b.HasIndex("PreviousMentorId"); + + b.HasIndex("CohortId", "Id"); + + b.ToTable("StudyCohortMentorAssignments", null, t => + { + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_DifferentMentor", "\"MentorId\" <> \"PreviousMentorId\""); + + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_Reason", "length(btrim(\"Reason\")) > 0"); + + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_Sessions", "\"EffectiveFromSessionNumber\" > 0 AND \"AffectedSessionCount\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActualEndedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ActualStartedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AvailabilityId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("Number") + .HasColumnType("integer"); + + b.Property("Status") + .IsConcurrencyToken() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("AvailabilityId") + .IsUnique(); + + b.HasIndex("CohortId", "Number") + .IsUnique(); + + b.ToTable("StudyCohortSessions", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("CancellationReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CapacitySnapshot") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CheckoutUrl") + .HasColumnType("text"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(3) + .HasColumnType("character varying(3)"); + + b.Property("DurationMonths") + .HasColumnType("integer"); + + b.Property("EndsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MaximumAbsencePercent") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MinimumHomeworkPercent") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("OrderSnapshot") + .HasColumnType("text"); + + b.Property("PaymentConfirmedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentReference") + .HasColumnType("text"); + + b.Property("PaymentReviewReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PaymentStatus") + .IsRequired() + .HasColumnType("text"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("PlanRevision") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("ProviderPaymentReference") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("PurchaseKey") + .HasColumnType("uuid"); + + b.Property("RefundedAmount") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("RefundedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RetakeClaimDays") + .HasColumnType("integer"); + + b.Property("RetakeOfId") + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("SessionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("Individual"); + + b.Property("SessionsPerWeek") + .HasColumnType("integer"); + + b.Property("StartsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.Property("TransferredAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("TransferredFromCourseId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CohortId"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PlanId"); + + b.HasIndex("ProviderPaymentReference") + .IsUnique() + .HasDatabaseName("IX_StudyCourses_ProviderPaymentReference") + .HasFilter("\"ProviderPaymentReference\" IS NOT NULL"); + + b.HasIndex("RetakeOfId") + .IsUnique(); + + b.HasIndex("TransferredFromCourseId") + .IsUnique() + .HasFilter("\"TransferredFromCourseId\" IS NOT NULL"); + + b.HasIndex("CohortId", "LearnerId") + .IsUnique() + .HasDatabaseName("IX_StudyCourses_Cohort_ActiveLearner") + .HasFilter("\"CohortId\" IS NOT NULL AND \"Status\" = 'Active'"); + + b.HasIndex("LearnerId", "PurchaseKey") + .IsUnique(); + + b.ToTable("StudyCourses", null, t => + { + t.HasCheckConstraint("CK_StudyCourses_RefundedAmount", "\"RefundedAmount\" >= 0 AND \"RefundedAmount\" <= \"Amount\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseHomework", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("DueAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Feedback") + .HasColumnType("text"); + + b.Property("Instructions") + .IsRequired() + .HasColumnType("text"); + + b.Property("Passed") + .HasColumnType("boolean"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Submission") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.ToTable("StudyCourseHomework", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCoursePlan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Capacity") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("DurationMonths") + .HasColumnType("integer"); + + b.Property("IsPublished") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Price") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("RetakeClaimDays") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("SessionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("Individual"); + + b.Property("SessionsPerWeek") + .HasColumnType("integer"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.ToTable("StudyCoursePlans", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Attempt") + .HasColumnType("integer"); + + b.Property("AvailabilityId") + .HasColumnType("integer"); + + b.Property("ConfirmedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ConfirmedById") + .HasColumnType("integer"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("MeetingUrl") + .HasColumnType("text"); + + b.Property("Note") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Number") + .HasColumnType("integer"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("AvailabilityId"); + + b.HasIndex("CourseId", "Number", "Attempt") + .IsUnique(); + + b.ToTable("StudyCourseSessions", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiGradingQuota") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DurationDays") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsPopular") + .HasColumnType("boolean"); + + b.Property("IsTrial") + .HasColumnType("boolean"); + + b.Property("MeetingSessionCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PlanCategory") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("self_study"); + + b.Property("Price") + .HasColumnType("decimal(18,0)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.ToTable("SubscriptionPlans", t => + { + t.HasCheckConstraint("CK_SubscriptionPlans_AiGradingQuota", "\"AiGradingQuota\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_DurationDays", "\"DurationDays\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_Price", "\"Price\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_SortOrder", "\"SortOrder\" >= 0"); + }); + + b.HasData( + new + { + Id = 1, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 1 tuần.", + DurationDays = 7, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 1 tuần", + PlanCategory = "self_study", + Price = 1000m, + Revision = 1, + SortOrder = 6 + }, + new + { + Id = 2, + AiGradingQuota = 2, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 2 tuần.", + DurationDays = 14, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 2 tuần", + PlanCategory = "self_study", + Price = 1000m, + Revision = 1, + SortOrder = 5 + }, + new + { + Id = 3, + AiGradingQuota = 3, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 3 tuần.", + DurationDays = 21, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 3 tuần", + PlanCategory = "self_study", + Price = 2000m, + Revision = 1, + SortOrder = 4 + }, + new + { + Id = 4, + AiGradingQuota = 5, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 1 tháng.", + DurationDays = 30, + IsActive = true, + IsDeleted = false, + IsPopular = true, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 1 tháng", + PlanCategory = "self_study", + Price = 2000m, + Revision = 1, + SortOrder = 3 + }, + new + { + Id = 5, + AiGradingQuota = 10, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 2 tháng.", + DurationDays = 60, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 2 tháng", + PlanCategory = "self_study", + Price = 3000m, + Revision = 1, + SortOrder = 2 + }, + new + { + Id = 6, + AiGradingQuota = 15, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 3 tháng.", + DurationDays = 90, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 3 tháng", + PlanCategory = "self_study", + Price = 3000m, + Revision = 1, + SortOrder = 1 + }, + new + { + Id = 7, + AiGradingQuota = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Gói demo gồm 12 buổi ôn luyện 1-1 với Mentor, thời hạn 90 ngày. Dữ liệu thanh toán demo được seed để kiểm thử đặt lịch trên frontend.", + DurationDays = 90, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 12, + Name = "Meeting 1-1 với Mentor - 12 buổi", + PlanCategory = "mentor_legacy", + Price = 1000m, + Revision = 1, + SortOrder = 7 + }, + new + { + Id = 8101, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt luyện nói và chấm phát âm tiếng Nhật bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Luyện nói AI - 1 lượt", + PlanCategory = "speaking", + Price = 1000m, + Revision = 1, + SortOrder = 10 + }, + new + { + Id = 8102, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt chấm bài viết tiếng Nhật bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Luyện viết AI - 1 lượt", + PlanCategory = "writing", + Price = 1000m, + Revision = 1, + SortOrder = 11 + }, + new + { + Id = 8103, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt giải thích chi tiết đáp án đề thi thử bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Giải thích đáp án AI - 1 lượt", + PlanCategory = "ai_grading", + Price = 1000m, + Revision = 1, + SortOrder = 12 + }, + new + { + Id = 8104, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt tạo lộ trình học cá nhân hóa bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Lộ trình học AI - 1 lượt", + PlanCategory = "learning_path", + Price = 1000m, + Revision = 1, + SortOrder = 13 + }, + new + { + Id = 8105, + AiGradingQuota = 0, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một buổi ôn luyện với mentor.", + DurationDays = 30, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 1, + Name = "Mentor - 1 buổi", + PlanCategory = "mentor_legacy", + Price = 1000m, + Revision = 1, + SortOrder = 14 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearningObjectives") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StageCode") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId", "SortOrder"); + + b.ToTable("Topics"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssessedCertificateLevelId") + .HasColumnType("integer"); + + b.Property("AvatarUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CurrentStreak") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutes") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutesMax") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutesMin") + .HasColumnType("integer"); + + b.Property("DeclaredJlptCertificateCode") + .HasColumnType("text"); + + b.Property("Email") + .HasColumnType("text"); + + b.Property("EmailNotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("FirebaseUid") + .HasColumnType("text"); + + b.Property("FirstName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("GoogleSubject") + .IsConcurrencyToken() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsEmailVerified") + .HasColumnType("boolean"); + + b.Property("IsPhoneVerified") + .HasColumnType("boolean"); + + b.Property("LastName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LastStudyDate") + .HasColumnType("timestamp without time zone"); + + b.Property("LearningGoalVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("LearningMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LongestStreak") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NotificationPreferencesJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("PendingEmail") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PendingEmailRequestedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("PhoneNumber") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PlacementDecision") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SelfDeclaredCertificateLevelId") + .HasColumnType("integer"); + + b.Property("StartingCertificateLevelId") + .HasColumnType("integer"); + + b.Property("StudyTimePreference") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("SystemNotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("TargetCertificateLevelId") + .HasColumnType("integer") + .HasColumnName("TargetCertificationLevelId"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TokenVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("AssessedCertificateLevelId"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("GoogleSubject") + .IsUnique(); + + b.HasIndex("SelfDeclaredCertificateLevelId"); + + b.HasIndex("StartingCertificateLevelId"); + + b.HasIndex("TargetCertificateLevelId"); + + b.ToTable("Users"); + + b.HasData( + new + { + Id = 900001, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "admin@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Admin", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "System", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 91, 215, 217, 54, 239, 206, 181, 216, 143, 33, 82, 211, 9, 70, 197, 173, 197, 0, 72, 71, 59, 150, 46, 114, 96, 137, 52, 174, 137, 29, 196, 61, 50, 254, 249, 101, 114, 92, 149, 32, 55, 127, 205, 126, 216, 147, 197, 192, 248, 173, 158, 92, 104, 42, 195, 107, 150, 15, 3, 74, 103, 104, 3, 229 }, + PasswordSalt = new byte[] { 61, 240, 150, 172, 239, 48, 224, 17, 192, 54, 50, 58, 91, 100, 55, 168, 18, 69, 137, 112, 110, 59, 180, 37, 201, 241, 143, 238, 139, 33, 128, 70, 87, 158, 235, 219, 229, 184, 94, 72, 41, 160, 160, 197, 158, 217, 128, 188, 156, 255, 147, 13, 151, 37, 133, 164, 9, 252, 175, 124, 21, 15, 152, 196 }, + PlacementDecision = "NotTaken", + Role = "Admin", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900002, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "mentor1@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Mentor", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "One", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 17, 253, 106, 25, 89, 176, 204, 31, 142, 252, 245, 31, 64, 101, 213, 135, 164, 116, 40, 46, 173, 175, 8, 0, 69, 101, 65, 4, 90, 25, 176, 223, 153, 237, 220, 94, 55, 133, 227, 181, 70, 97, 155, 122, 50, 139, 216, 136, 88, 52, 76, 98, 250, 64, 52, 71, 146, 221, 225, 137, 106, 6, 178, 239 }, + PasswordSalt = new byte[] { 233, 77, 244, 252, 171, 97, 38, 140, 50, 138, 10, 54, 122, 165, 186, 85, 129, 82, 49, 10, 98, 44, 165, 57, 50, 7, 238, 166, 142, 224, 94, 49, 134, 226, 247, 110, 154, 139, 99, 204, 95, 39, 171, 235, 212, 26, 217, 87, 139, 118, 253, 125, 241, 255, 57, 22, 140, 171, 11, 168, 174, 202, 32, 17 }, + PlacementDecision = "NotTaken", + Role = "Mentor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900003, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "mentor2@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Mentor", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Two", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 93, 130, 109, 171, 238, 187, 245, 15, 202, 89, 247, 220, 95, 192, 246, 138, 5, 75, 250, 28, 208, 28, 51, 79, 127, 28, 214, 237, 93, 221, 108, 26, 152, 66, 73, 65, 11, 147, 154, 102, 113, 49, 51, 24, 51, 197, 248, 254, 22, 98, 87, 249, 250, 104, 131, 74, 16, 18, 179, 200, 3, 3, 79, 47 }, + PasswordSalt = new byte[] { 240, 155, 254, 183, 129, 162, 74, 247, 41, 9, 67, 242, 128, 8, 226, 85, 5, 104, 104, 72, 101, 75, 130, 95, 47, 101, 116, 89, 207, 23, 119, 178, 38, 180, 185, 145, 58, 115, 14, 30, 85, 216, 169, 133, 94, 115, 11, 117, 96, 87, 227, 240, 204, 48, 51, 144, 170, 248, 167, 56, 175, 194, 253, 135 }, + PlacementDecision = "NotTaken", + Role = "Mentor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900004, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "author1@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Content", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Author One", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 168, 249, 82, 144, 178, 145, 94, 164, 34, 152, 2, 74, 204, 105, 84, 145, 96, 199, 153, 136, 110, 82, 114, 113, 22, 139, 117, 143, 50, 239, 197, 4, 51, 189, 137, 48, 175, 14, 104, 164, 218, 249, 148, 217, 33, 44, 202, 128, 237, 183, 110, 228, 185, 36, 209, 254, 183, 182, 55, 1, 78, 16, 234, 50 }, + PasswordSalt = new byte[] { 19, 216, 84, 143, 3, 184, 50, 39, 209, 137, 149, 82, 224, 206, 6, 240, 237, 242, 172, 27, 55, 92, 242, 101, 149, 76, 104, 38, 176, 43, 40, 8, 102, 202, 146, 224, 62, 43, 147, 132, 2, 158, 81, 170, 29, 103, 76, 248, 101, 105, 213, 205, 32, 51, 59, 39, 221, 11, 135, 250, 193, 8, 78, 219 }, + PlacementDecision = "NotTaken", + Role = "ContentAuthor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900005, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "author2@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Content", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Author Two", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 189, 121, 9, 1, 230, 137, 43, 239, 79, 56, 195, 196, 66, 116, 42, 1, 137, 55, 54, 249, 55, 231, 79, 224, 182, 182, 199, 133, 100, 39, 138, 5, 223, 215, 48, 46, 60, 214, 49, 88, 42, 186, 232, 116, 237, 89, 55, 144, 4, 78, 215, 231, 237, 220, 96, 225, 202, 97, 61, 165, 246, 28, 126, 198 }, + PasswordSalt = new byte[] { 66, 178, 77, 56, 234, 206, 29, 78, 136, 190, 160, 142, 226, 249, 14, 17, 26, 101, 167, 36, 193, 55, 150, 94, 239, 81, 69, 54, 81, 171, 80, 22, 208, 38, 242, 2, 55, 171, 64, 38, 48, 224, 36, 216, 133, 132, 147, 100, 174, 32, 65, 134, 128, 35, 50, 138, 204, 59, 167, 96, 11, 128, 101, 102 }, + PlacementDecision = "NotTaken", + Role = "ContentAuthor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900006, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Meeting", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Test Learner", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 9, 206, 219, 58, 155, 234, 107, 145, 121, 174, 134, 51, 96, 253, 64, 216, 157, 114, 92, 36, 123, 206, 67, 217, 207, 166, 54, 71, 254, 251, 156, 200, 185, 110, 198, 135, 221, 146, 243, 40, 237, 229, 16, 133, 163, 161, 156, 79, 138, 103, 85, 25, 114, 81, 99, 182, 25, 73, 212, 198, 212, 192, 54, 129 }, + PasswordSalt = new byte[] { 231, 202, 97, 95, 11, 9, 242, 47, 62, 77, 67, 36, 170, 78, 120, 81, 56, 69, 47, 36, 209, 212, 107, 244, 15, 34, 189, 110, 57, 66, 205, 213, 224, 19, 245, 192, 104, 146, 130, 44, 54, 107, 2, 15, 109, 136, 118, 220, 228, 44, 110, 219, 31, 100, 161, 164, 63, 231, 196, 79, 120, 106, 181, 71 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900007, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner2.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Linh", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Nguyen", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 217, 79, 50, 159, 85, 88, 67, 15, 23, 182, 103, 80, 220, 85, 86, 173, 204, 186, 57, 67, 183, 165, 253, 243, 150, 250, 150, 190, 122, 252, 55, 169, 85, 236, 69, 106, 19, 219, 244, 42, 239, 30, 189, 176, 52, 47, 30, 28, 125, 31, 162, 255, 61, 3, 238, 201, 168, 88, 161, 42, 216, 86, 172, 219 }, + PasswordSalt = new byte[] { 85, 97, 108, 158, 219, 70, 81, 106, 73, 23, 205, 163, 105, 159, 117, 19, 175, 147, 178, 99, 112, 116, 163, 243, 109, 178, 129, 229, 245, 175, 91, 174, 66, 198, 122, 88, 80, 68, 160, 64, 85, 118, 105, 41, 135, 89, 49, 160, 120, 13, 116, 148, 255, 27, 157, 207, 106, 203, 127, 74, 19, 61, 148, 120 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900008, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner3.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Minh", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Tran", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 84, 97, 164, 196, 63, 151, 182, 39, 139, 242, 152, 22, 179, 33, 174, 113, 0, 236, 253, 114, 234, 242, 209, 76, 196, 162, 143, 195, 180, 3, 178, 193, 205, 230, 18, 114, 49, 151, 198, 217, 254, 21, 94, 176, 146, 214, 235, 122, 28, 241, 164, 161, 4, 161, 209, 38, 102, 179, 31, 107, 157, 25, 35, 63 }, + PasswordSalt = new byte[] { 26, 188, 78, 205, 57, 115, 100, 129, 148, 135, 165, 205, 148, 203, 245, 36, 244, 177, 9, 104, 120, 140, 21, 164, 36, 75, 122, 51, 115, 69, 174, 180, 120, 155, 62, 37, 97, 227, 212, 134, 200, 7, 66, 255, 219, 10, 140, 149, 67, 86, 164, 170, 142, 165, 181, 103, 47, 100, 238, 24, 178, 29, 171, 226 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900009, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner4.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Hoang", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Pham", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 42, 30, 236, 129, 234, 192, 63, 84, 148, 163, 154, 246, 107, 147, 189, 95, 33, 141, 196, 67, 181, 51, 157, 136, 93, 228, 237, 165, 164, 49, 4, 146, 87, 84, 9, 47, 28, 59, 33, 130, 37, 63, 43, 229, 8, 178, 123, 74, 61, 159, 235, 68, 217, 51, 225, 29, 201, 104, 44, 152, 53, 255, 199, 28 }, + PasswordSalt = new byte[] { 83, 214, 138, 3, 142, 91, 229, 97, 238, 61, 48, 237, 80, 82, 112, 249, 166, 81, 53, 95, 170, 120, 13, 87, 113, 159, 60, 37, 75, 229, 226, 107, 229, 89, 60, 57, 109, 196, 235, 81, 145, 154, 110, 120, 141, 13, 142, 77, 41, 132, 58, 80, 154, 57, 226, 168, 176, 251, 113, 167, 242, 139, 7, 177 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserDeviceToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceIdentifier") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FcmToken") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastSeenAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("FcmToken") + .HasDatabaseName("IX_UserDeviceTokens_FcmToken"); + + b.HasIndex("UserId", "DeviceIdentifier") + .HasDatabaseName("IX_UserDeviceTokens_UserId_DeviceIdentifier"); + + b.HasIndex("UserId", "IsActive") + .HasDatabaseName("IX_UserDeviceTokens_UserId_IsActive"); + + b.ToTable("UserDeviceTokens", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSrsPreference", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AutoEnrollAfterLesson") + .HasColumnType("boolean"); + + b.Property("AutoPlayAudio") + .HasColumnType("boolean"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DailyNewLimit") + .HasColumnType("integer"); + + b.Property("DailyReminderEnabled") + .HasColumnType("boolean"); + + b.Property("DailyReviewLimit") + .HasColumnType("integer"); + + b.Property("EmailReminderEnabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastReminderSentAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastReminderSentLocalDate") + .HasColumnType("date"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PreferredLocale") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("PreferredReviewMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReminderDaysJson") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ReminderFrequency") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("ReminderHour") + .HasColumnType("integer"); + + b.Property("ReminderMinute") + .HasColumnType("integer"); + + b.Property("ShowFuriganaHint") + .HasColumnType("boolean"); + + b.Property("TimezoneId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.HasIndex("DailyReminderEnabled", "LastReminderSentLocalDate"); + + b.ToTable("UserSrsPreferences"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiGradingQuota") + .HasColumnType("integer"); + + b.Property("AiGradingUsedCount") + .HasColumnType("integer"); + + b.Property("AmountPaid") + .HasColumnType("decimal(18,2)"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DurationDaysSnapshot") + .HasColumnType("integer"); + + b.Property("EndDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MeetingSessionsIncluded") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("MeetingSessionsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorPracticeOutcomeJson") + .HasColumnType("text"); + + b.Property("MentorReviewCompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorReviewPlan") + .HasMaxLength(6000) + .HasColumnType("character varying(6000)"); + + b.Property("MentorReviewSessionAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PaymentTransactionId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PendingMentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("PendingMentorQuestion") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PlanCategorySnapshot") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PlanNameSnapshot") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PlanRevisionSnapshot") + .HasColumnType("integer"); + + b.Property("PurchasedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StartDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SubscriptionPlanId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PendingMentorAvailabilityId"); + + b.HasIndex("SubscriptionPlanId"); + + b.HasIndex("UserId", "PaymentStatus", "EndDate"); + + b.ToTable("UserSubscriptions"); + + b.HasData( + new + { + Id = 990001, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 90, + EndDate = new DateTime(2099, 12, 31, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS", + PlanCategorySnapshot = "mentor_legacy", + PlanNameSnapshot = "Meeting 1-1 với Mentor - 12 buổi", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900006, + Version = 0u + }, + new + { + Id = 990002, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-2", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900007, + Version = 0u + }, + new + { + Id = 990003, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-3", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900008, + Version = 0u + }, + new + { + Id = 990004, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-4", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900009, + Version = 0u + }, + new + { + Id = 990005, + AiGradingQuota = 15, + AiGradingUsedCount = 0, + AmountPaid = 3000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 90, + EndDate = new DateTime(2099, 12, 31, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 0, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-FULL-ACCESS-SELF-STUDY", + PlanCategorySnapshot = "self_study", + PlanNameSnapshot = "Tự học tiếng Nhật - 3 tháng", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 6, + UserId = 900006, + Version = 0u + }, + new + { + Id = 990006, + AiGradingQuota = 1, + AiGradingUsedCount = 0, + AmountPaid = 1000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 0, + IsDeleted = false, + MeetingSessionsIncluded = 0, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-FULL-ACCESS-LEARNING-PATH", + PlanCategorySnapshot = "learning_path", + PlanNameSnapshot = "Mua 1 lượt AI đề xuất lộ trình", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 8104, + UserId = 900006, + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleSentence") + .HasColumnType("text"); + + b.Property("ExampleSentenceMeaning") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Meaning") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Reading") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Word") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("Word", "Reading"); + + b.ToTable("Vocabularies"); + }); + + modelBuilder.Entity("FeatureSubscriptionPlan", b => + { + b.HasOne("RikiPath.Domain.Entities.Feature", null) + .WithMany() + .HasForeignKey("FeaturesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.SubscriptionPlan", null) + .WithMany() + .HasForeignKey("SubscriptionPlansId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AiCreditTopUp", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("AiCreditTopUps") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateType", "CertificateType") + .WithMany("Levels") + .HasForeignKey("CertificateTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateType"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "Attempt") + .WithMany() + .HasForeignKey("AttemptId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Enrollment") + .WithMany() + .HasForeignKey("EnrollmentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.ClassQuiz", "Quiz") + .WithMany("Assignments") + .HasForeignKey("QuizId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Attempt"); + + b.Navigation("Enrollment"); + + b.Navigation("Learner"); + + b.Navigation("Quiz"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("DecidedById") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("Course"); + + b.Navigation("CourseSession"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaintEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortComplaint", "Complaint") + .WithMany("History") + .HasForeignKey("ComplaintId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Complaint"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortEnrollmentEntitlement", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "StudyCohort") + .WithMany() + .HasForeignKey("StudyCohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Learner"); + + b.Navigation("Plan"); + + b.Navigation("StudyCohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortLearningFeedback", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("RespondedById") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Course"); + + b.Navigation("CourseSession"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortMentorReview", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cohort"); + + b.Navigation("Course"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "RequestedBy") + .WithMany() + .HasForeignKey("RequestedById") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("ReviewedById") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("RequestedBy"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequestEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortScheduleRequest", "Request") + .WithMany("History") + .HasForeignKey("RequestId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Request"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "DestinationCourse") + .WithMany() + .HasForeignKey("DestinationCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", null) + .WithMany() + .HasForeignKey("PolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "RequestedTargetCohort") + .WithMany() + .HasForeignKey("RequestedTargetCohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("ReviewedById") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "SourceCohort") + .WithMany() + .HasForeignKey("SourceCohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "SourceCourse") + .WithMany() + .HasForeignKey("SourceCourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "TargetCohort") + .WithMany() + .HasForeignKey("TargetCohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("DestinationCourse"); + + b.Navigation("Learner"); + + b.Navigation("RequestedTargetCohort"); + + b.Navigation("SourceCohort"); + + b.Navigation("SourceCourse"); + + b.Navigation("TargetCohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequestEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortTransferRequest", "Request") + .WithMany("History") + .HasForeignKey("RequestId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Request"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentApprovalRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "SubmittedBy") + .WithMany() + .HasForeignKey("SubmittedByUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("SubmittedBy"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAudioTranscription", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CreatedByUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentBankItem", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Owner") + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentLevelMapping", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("ContentLevelMappings") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("ContentLevelMappings") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("ContentLevelMappings") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("ContentLevelMappings") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("CertificateLevel"); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("Passages") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockTestSection"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseAuditEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Audit") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseRetakeRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("RetakeRequests") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseScheduleRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.EmailVerification", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "User") + .WithMany("EmailVerifications") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GradingResult", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkSubmission") + .WithOne("GradingResult") + .HasForeignKey("RikiPath.Domain.Entities.GradingResult", "HomeworkSubmissionId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.PracticeSubmission", "PracticeSubmission") + .WithOne("GradingResult") + .HasForeignKey("RikiPath.Domain.Entities.GradingResult", "PracticeSubmissionId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("HomeworkSubmission"); + + b.Navigation("PracticeSubmission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredGrammarPatterns") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "StudyCourse") + .WithMany() + .HasForeignKey("StudyCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + + b.Navigation("StudyCourse"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentAttachment", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("Attachments") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentExercise", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("Exercises") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany() + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("PracticeExercise"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentLesson", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("HomeworkAssignmentLessons") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("HomeworkAssignmentLessons") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithOne("Submission") + .HasForeignKey("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("Learner"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmissionFile", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkSubmission") + .WithMany("Files") + .HasForeignKey("HomeworkSubmissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkSubmission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptLevelPayCoefficient", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("ConfiguredByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.HasOne("RikiPath.Domain.Entities.KanaCharacter", "KanaCharacter") + .WithMany("PracticeCards") + .HasForeignKey("KanaCharacterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("KanaCharacter"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.KanaWritingPracticeCard", "Card") + .WithMany("Histories") + .HasForeignKey("KanaWritingPracticeCardId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Card"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredKanjis") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerEssay", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LearnerEssays") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerFeedback", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Learner"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerHighlight", b => + { + b.HasOne("RikiPath.Domain.Entities.LearnerNoteEntry", "LinkedNoteEntry") + .WithMany() + .HasForeignKey("LinkedNoteEntryId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.ReviewCard", "LinkedReviewCard") + .WithMany() + .HasForeignKey("LinkedReviewCardId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LinkedNoteEntry"); + + b.Navigation("LinkedReviewCard"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.HasOne("RikiPath.Domain.Entities.NotebookFolder", "Folder") + .WithMany("Files") + .HasForeignKey("FolderId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LearnerNotes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Folder"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany() + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("LearnerNoteEntries") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.LearnerNote", "LearnerNote") + .WithMany("LearnerNoteEntries") + .HasForeignKey("LearnerNoteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.NotebookPage", "NotebookPage") + .WithMany("SavedItems") + .HasForeignKey("NotebookPageId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("LearnerNoteEntries") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("LearnerNote"); + + b.Navigation("NotebookPage"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerPracticeAnswer", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeExerciseAttempt", "PracticeExerciseAttempt") + .WithMany("Answers") + .HasForeignKey("PracticeExerciseAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeQuestion", "PracticeQuestion") + .WithMany("Answers") + .HasForeignKey("PracticeQuestionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeQuestionOption", "SelectedOption") + .WithMany() + .HasForeignKey("SelectedOptionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("PracticeExerciseAttempt"); + + b.Navigation("PracticeQuestion"); + + b.Navigation("SelectedOption"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("Lessons") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany("Lessons") + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "PrerequisiteLesson") + .WithMany() + .HasForeignKey("PrerequisiteLessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Topic", "Topic") + .WithMany("Lessons") + .HasForeignKey("TopicId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredLessons") + .HasForeignKey("UserAccountId"); + + b.Navigation("CertificateLevel"); + + b.Navigation("LanguageSkill"); + + b.Navigation("PrerequisiteLesson"); + + b.Navigation("Topic"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonGrammar", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("LessonGrammars") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonGrammars") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("GrammarPattern"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonKanji", b => + { + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("LessonKanjis") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonKanjis") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Kanji"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonProgress", b => + { + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonProgresses") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LessonProgresses") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lesson"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonVocabulary", b => + { + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonVocabularies") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("LessonVocabularies") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lesson"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAbuseReport", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Reporter") + .WithMany() + .HasForeignKey("ReporterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "TargetUser") + .WithMany() + .HasForeignKey("TargetUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("Reporter"); + + b.Navigation("TargetUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceApproval", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("MentorBooking"); + + b.Navigation("ReviewedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceRecord", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CourseSession"); + + b.Navigation("MentorBooking"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany("MentorAvailabilities") + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorScheduleRule", "ScheduleRule") + .WithMany() + .HasForeignKey("MentorScheduleRuleId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorWeeklyAvailability", "WeeklyAvailability") + .WithMany("Slots") + .HasForeignKey("MentorWeeklyAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "TeachingProposal") + .WithMany("GeneratedAvailabilities") + .HasForeignKey("TeachingProposalId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("ScheduleRule"); + + b.Navigation("TeachingProposal"); + + b.Navigation("WeeklyAvailability"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBankAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "VerifiedByAdmin") + .WithMany() + .HasForeignKey("VerifiedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("MentorUser"); + + b.Navigation("VerifiedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CompensationLevel") + .WithMany() + .HasForeignKey("CompensationLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorCreditGrant", "CreditGrant") + .WithMany() + .HasForeignKey("CreditGrantId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany("MentorBookings") + .HasForeignKey("MentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserSubscription", "UserSubscription") + .WithMany("MentorBookings") + .HasForeignKey("UserSubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CompensationLevel"); + + b.Navigation("CreditGrant"); + + b.Navigation("MentorAvailability"); + + b.Navigation("UserSubscription"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingDayGuard", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingIntent", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Learner"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingReservation", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany() + .HasForeignKey("MentorAvailabilityId", "MentorId") + .HasPrincipalKey("Id", "MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + + b.Navigation("MentorAvailability"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingTerms", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany() + .HasForeignKey("MentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithOne() + .HasForeignKey("RikiPath.Domain.Entities.MentorBookingTerms", "MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorAvailability"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCalendarConnection", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorChatMessage", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Sender") + .WithMany() + .HasForeignKey("SenderUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("Sender"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorCreditGrant", "CreditGrant") + .WithMany("Entries") + .HasForeignKey("CreditGrantId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreditGrant"); + + b.Navigation("Learner"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserSubscription", "UserSubscription") + .WithMany() + .HasForeignKey("UserSubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Learner"); + + b.Navigation("UserSubscription"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ResolvedByAdmin") + .WithMany() + .HasForeignKey("ResolvedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + + b.Navigation("ResolvedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDisputeHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorDispute", "Dispute") + .WithMany("Histories") + .HasForeignKey("DisputeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Dispute"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorEarningEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAttendanceApproval", "AttendanceApproval") + .WithMany() + .HasForeignKey("AttendanceApprovalId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany() + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("AttendanceApproval"); + + b.Navigation("CertificateLevel"); + + b.Navigation("CreatedByAdmin"); + + b.Navigation("MentorBooking"); + + b.Navigation("MentorUser"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorGroupPolicy", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "DeletedByAdmin") + .WithMany() + .HasForeignKey("DeletedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "LastAppliedByAdmin") + .WithMany() + .HasForeignKey("LastAppliedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UpdatedByAdmin") + .WithMany() + .HasForeignKey("UpdatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreatedByAdmin"); + + b.Navigation("DeletedByAdmin"); + + b.Navigation("LastAppliedByAdmin"); + + b.Navigation("UpdatedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorHourlyRate", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfiguredByAdmin"); + + b.Navigation("MentorUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfirmedByAdmin") + .WithMany() + .HasForeignKey("ConfirmedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "InitiatedByAdmin") + .WithMany() + .HasForeignKey("InitiatedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBankAccount", "LockedBankAccount") + .WithMany() + .HasForeignKey("LockedBankAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorPayoutObligation", "PayoutObligation") + .WithMany("Attempts") + .HasForeignKey("PayoutObligationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfirmedByAdmin"); + + b.Navigation("InitiatedByAdmin"); + + b.Navigation("LockedBankAccount"); + + b.Navigation("PayoutObligation"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBankAccount", "LockedBankAccount") + .WithMany() + .HasForeignKey("LockedBankAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.OrganizationPayoutAccount", "OrganizationPayoutAccount") + .WithMany() + .HasForeignKey("OrganizationPayoutAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany() + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("LockedBankAccount"); + + b.Navigation("MentorUser"); + + b.Navigation("OrganizationPayoutAccount"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollAdjustment", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany("Adjustments") + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollLine", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorEarningEntry", "EarningEntry") + .WithMany() + .HasForeignKey("EarningEntryId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany("Lines") + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("EarningEntry"); + + b.Navigation("MentorBooking"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "PreparedByAdmin") + .WithMany() + .HasForeignKey("PreparedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("MentorUser"); + + b.Navigation("PreparedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorProfile", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithOne("MentorProfile") + .HasForeignKey("RikiPath.Domain.Entities.MentorProfile", "MentorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorReview", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorScheduleRule", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorSchedule", "Schedule") + .WithMany("Rules") + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Schedule"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "CoursePlan") + .WithMany() + .HasForeignKey("CoursePlanId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + + b.Navigation("CoursePlan"); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("ReviewedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposalEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "Proposal") + .WithMany("Events") + .HasForeignKey("ProposalId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Proposal"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingQualification", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "VerifiedByAdmin") + .WithMany() + .HasForeignKey("VerifiedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("MentorUser"); + + b.Navigation("VerifiedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", null) + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", null) + .WithMany() + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("Questions") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.ContentPassage", "Passage") + .WithMany("Questions") + .HasForeignKey("PassageId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.MockQuestion", null) + .WithMany() + .HasForeignKey("SourceQuestionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockTestSection"); + + b.Navigation("Passage"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestionOption", b => + { + b.HasOne("RikiPath.Domain.Entities.MockQuestion", "MockQuestion") + .WithMany("Options") + .HasForeignKey("MockQuestionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MockQuestion"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("MockTests") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredMockTests") + .HasForeignKey("UserAccountId"); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAnswer", b => + { + b.HasOne("RikiPath.Domain.Entities.MockQuestion", "MockQuestion") + .WithMany("Answers") + .HasForeignKey("MockQuestionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "MockTestAttempt") + .WithMany("Answers") + .HasForeignKey("MockTestAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockQuestionOption", "SelectedOption") + .WithMany() + .HasForeignKey("SelectedOptionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockQuestion"); + + b.Navigation("MockTestAttempt"); + + b.Navigation("SelectedOption"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("MockTestAttempts") + .HasForeignKey("UserAccountId"); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateSection", "CertificateSection") + .WithMany("MockTestSections") + .HasForeignKey("CertificateSectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany("MockTestSections") + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTest", "MockTest") + .WithMany("Sections") + .HasForeignKey("MockTestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CertificateSection"); + + b.Navigation("LanguageSkill"); + + b.Navigation("MockTest"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSectionResult", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "MockTestAttempt") + .WithMany("SectionResults") + .HasForeignKey("MockTestAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("SectionResults") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MockTestAttempt"); + + b.Navigation("MockTestSection"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Note", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithOne("Note") + .HasForeignKey("RikiPath.Domain.Entities.Note", "MentorBookingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("Notes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.HasOne("RikiPath.Domain.Entities.LearnerNote", "LearnerNote") + .WithMany("Pages") + .HasForeignKey("LearnerNoteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("LearnerNote"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Notification", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("Notifications") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.OrganizationPayoutAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfiguredByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany() + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Topic", "Topic") + .WithMany() + .HasForeignKey("TopicId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CertificateLevel"); + + b.Navigation("LanguageSkill"); + + b.Navigation("Lesson"); + + b.Navigation("Topic"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany() + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany("Attempts") + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("PracticeExercise"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany("Questions") + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PracticeExercise"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestionOption", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeQuestion", "PracticeQuestion") + .WithMany("Options") + .HasForeignKey("PracticeQuestionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PracticeQuestion"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("PracticeSubmissions") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("PracticeSubmissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.RecommendedLearningPath", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("RecommendedLearningPaths") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("ReviewCards") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("ReviewCards") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.LearnerNoteEntry", "LearnerNoteEntry") + .WithMany("ReviewCards") + .HasForeignKey("LearnerNoteEntryId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.SrsCardTemplate", "SrsCardTemplate") + .WithMany() + .HasForeignKey("SrsCardTemplateId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("ReviewCards") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany() + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("LearnerNoteEntry"); + + b.Navigation("Lesson"); + + b.Navigation("SrsCardTemplate"); + + b.Navigation("UserAccount"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.ReviewCard", "ReviewCard") + .WithMany("ReviewHistories") + .HasForeignKey("ReviewCardId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ReviewCard"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsCardTemplate", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany() + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany() + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "SubmittedByUser") + .WithMany() + .HasForeignKey("SubmittedByUserId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany() + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CertificateLevel"); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("Lesson"); + + b.Navigation("ReviewedByAdmin"); + + b.Navigation("SubmittedByUser"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsReviewSession", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "SourceProposal") + .WithMany() + .HasForeignKey("SourceProposalId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("Plan"); + + b.Navigation("SourceProposal"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortMentorAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("AssignedById") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", null) + .WithMany() + .HasForeignKey("PolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("PreviousMentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortSession", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "Availability") + .WithMany() + .HasForeignKey("AvailabilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany("Sessions") + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Availability"); + + b.Navigation("Cohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany("Enrollments") + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "RetakeOf") + .WithMany() + .HasForeignKey("RetakeOfId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", null) + .WithMany() + .HasForeignKey("TransferredFromCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("GroupPolicy"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("Plan"); + + b.Navigation("RetakeOf"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseHomework", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Homework") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCoursePlan", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseSession", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "Availability") + .WithMany() + .HasForeignKey("AvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Sessions") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Availability"); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "AssessedCertificateLevel") + .WithMany() + .HasForeignKey("AssessedCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "SelfDeclaredCertificateLevel") + .WithMany() + .HasForeignKey("SelfDeclaredCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "StartingCertificateLevel") + .WithMany() + .HasForeignKey("StartingCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "TargetCertificateLevel") + .WithMany("LearnersTargeting") + .HasForeignKey("TargetCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("AssessedCertificateLevel"); + + b.Navigation("SelfDeclaredCertificateLevel"); + + b.Navigation("StartingCertificateLevel"); + + b.Navigation("TargetCertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserDeviceToken", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSrsPreference", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "PendingMentorAvailability") + .WithMany() + .HasForeignKey("PendingMentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.SubscriptionPlan", "SubscriptionPlan") + .WithMany("UserSubscriptions") + .HasForeignKey("SubscriptionPlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("UserSubscriptions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Mentor"); + + b.Navigation("PendingMentorAvailability"); + + b.Navigation("SubscriptionPlan"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredVocabularies") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnersTargeting"); + + b.Navigation("Lessons"); + + b.Navigation("MockTests"); + + b.Navigation("PracticeSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.Navigation("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateType", b => + { + b.Navigation("Levels"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Navigation("Assignments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.Navigation("Questions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LessonGrammars"); + + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.Navigation("Attachments"); + + b.Navigation("Exercises"); + + b.Navigation("HomeworkAssignmentLessons"); + + b.Navigation("Submission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.Navigation("Files"); + + b.Navigation("GradingResult"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaCharacter", b => + { + b.Navigation("PracticeCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.Navigation("Histories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnerNoteEntries"); + + b.Navigation("LessonKanjis"); + + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LanguageSkill", b => + { + b.Navigation("Lessons"); + + b.Navigation("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.Navigation("LearnerNoteEntries"); + + b.Navigation("Pages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.Navigation("HomeworkAssignmentLessons"); + + b.Navigation("LessonGrammars"); + + b.Navigation("LessonKanjis"); + + b.Navigation("LessonProgresses"); + + b.Navigation("LessonVocabularies"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.Navigation("MentorBookings"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.Navigation("Note"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.Navigation("Histories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.Navigation("Attempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.Navigation("Adjustments"); + + b.Navigation("Lines"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.Navigation("Rules"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.Navigation("Events"); + + b.Navigation("GeneratedAvailabilities"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.Navigation("Slots"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.Navigation("Answers"); + + b.Navigation("Options"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.Navigation("Sections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.Navigation("Answers"); + + b.Navigation("SectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.Navigation("Passages"); + + b.Navigation("Questions"); + + b.Navigation("SectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.Navigation("Files"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.Navigation("SavedItems"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.Navigation("Attempts"); + + b.Navigation("Questions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.Navigation("Answers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.Navigation("Answers"); + + b.Navigation("Options"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.Navigation("GradingResult"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.Navigation("ReviewHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.Navigation("Enrollments"); + + b.Navigation("Sessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.Navigation("Audit"); + + b.Navigation("Homework"); + + b.Navigation("RetakeRequests"); + + b.Navigation("Sessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.Navigation("UserSubscriptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.Navigation("Lessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.Navigation("AiCreditTopUps"); + + b.Navigation("AuthoredGrammarPatterns"); + + b.Navigation("AuthoredKanjis"); + + b.Navigation("AuthoredLessons"); + + b.Navigation("AuthoredMockTests"); + + b.Navigation("AuthoredVocabularies"); + + b.Navigation("EmailVerifications"); + + b.Navigation("LearnerEssays"); + + b.Navigation("LearnerNotes"); + + b.Navigation("LessonProgresses"); + + b.Navigation("MentorAvailabilities"); + + b.Navigation("MentorProfile"); + + b.Navigation("MockTestAttempts"); + + b.Navigation("Notes"); + + b.Navigation("Notifications"); + + b.Navigation("PracticeSubmissions"); + + b.Navigation("RecommendedLearningPaths"); + + b.Navigation("ReviewCards"); + + b.Navigation("UserSubscriptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.Navigation("MentorBookings"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnerNoteEntries"); + + b.Navigation("LessonVocabularies"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.cs b/RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.cs new file mode 100644 index 0000000..baa9378 --- /dev/null +++ b/RikiPath.Infrastructure/Migrations/20261201082900_AddRetakeSupportPolicyThresholds.cs @@ -0,0 +1,58 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace RikiPath.Infrastructure.Migrations +{ + /// + public partial class AddRetakeSupportPolicyThresholds : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RemediationAttendanceThresholdPercent", + table: "MentorGroupPolicies", + type: "numeric(5,2)", + precision: 5, + scale: 2, + nullable: false, + defaultValue: 90m); + + migrationBuilder.AddColumn( + name: "RetakeSupportEnabled", + table: "MentorGroupPolicies", + type: "boolean", + nullable: false, + defaultValue: true); + + migrationBuilder.UpdateData( + table: "MentorGroupPolicies", + keyColumn: "Id", + keyValue: 1, + columns: new[] { "RemediationAttendanceThresholdPercent", "RetakeSupportEnabled" }, + values: new object[] { 90m, true }); + + migrationBuilder.AddCheckConstraint( + name: "CK_MentorGroupPolicy_RemediationAttendance", + table: "MentorGroupPolicies", + sql: "\"RemediationAttendanceThresholdPercent\" > 0 AND \"RemediationAttendanceThresholdPercent\" <= 100"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "CK_MentorGroupPolicy_RemediationAttendance", + table: "MentorGroupPolicies"); + + migrationBuilder.DropColumn( + name: "RemediationAttendanceThresholdPercent", + table: "MentorGroupPolicies"); + + migrationBuilder.DropColumn( + name: "RetakeSupportEnabled", + table: "MentorGroupPolicies"); + } + } +} diff --git a/RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.Designer.cs b/RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.Designer.cs new file mode 100644 index 0000000..83cbfe6 --- /dev/null +++ b/RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.Designer.cs @@ -0,0 +1,14635 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using RikiPath.Infrastructure; + +#nullable disable + +namespace RikiPath.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments")] + partial class AddMentorKpiPolicyAndTimesheetAdjustments + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("FeatureSubscriptionPlan", b => + { + b.Property("FeaturesId") + .HasColumnType("integer"); + + b.Property("SubscriptionPlansId") + .HasColumnType("integer"); + + b.HasKey("FeaturesId", "SubscriptionPlansId"); + + b.HasIndex("SubscriptionPlansId"); + + b.ToTable("FeatureSubscriptionPlan"); + + b.HasData( + new + { + FeaturesId = 1, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 1 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 2 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 3 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 4 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 5 + }, + new + { + FeaturesId = 1, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 2, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 3, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 4, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 5, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 6 + }, + new + { + FeaturesId = 7, + SubscriptionPlansId = 7 + }, + new + { + FeaturesId = 8, + SubscriptionPlansId = 7 + }, + new + { + FeaturesId = 13, + SubscriptionPlansId = 8101 + }, + new + { + FeaturesId = 14, + SubscriptionPlansId = 8102 + }, + new + { + FeaturesId = 6, + SubscriptionPlansId = 8103 + }, + new + { + FeaturesId = 12, + SubscriptionPlansId = 8104 + }, + new + { + FeaturesId = 7, + SubscriptionPlansId = 8105 + }, + new + { + FeaturesId = 8, + SubscriptionPlansId = 8105 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AdminAuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ActorUserId") + .HasColumnType("integer"); + + b.Property("AfterJson") + .HasColumnType("text"); + + b.Property("BeforeJson") + .HasColumnType("text"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("EntityId") + .HasColumnType("integer"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("EntityType", "EntityId"); + + b.ToTable("AdminAuditLogs", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AiCreditTopUp", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActivatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PaymentTransactionId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Quantity") + .HasColumnType("integer"); + + b.Property("TotalAmount") + .HasColumnType("decimal(18,2)"); + + b.Property("UnitPrice") + .HasColumnType("decimal(18,2)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "PaymentStatus"); + + b.ToTable("AiCreditTopUps"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateTypeId") + .HasColumnType("integer") + .HasColumnName("CertificationId"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateTypeId", "Code") + .IsUnique(); + + b.ToTable("CertificateLevels", null, t => + { + t.HasCheckConstraint("CK_CertificateLevels_SortOrder", "\"SortOrder\" >= 1"); + }); + + b.HasData( + new + { + Id = 1, + CertificateTypeId = 1, + Code = "N5", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N5", + IsDeleted = false, + Revision = 1, + SortOrder = 1 + }, + new + { + Id = 2, + CertificateTypeId = 1, + Code = "N4", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N4", + IsDeleted = false, + Revision = 1, + SortOrder = 2 + }, + new + { + Id = 3, + CertificateTypeId = 1, + Code = "N3", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N3", + IsDeleted = false, + Revision = 1, + SortOrder = 3 + }, + new + { + Id = 4, + CertificateTypeId = 1, + Code = "N2", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N2", + IsDeleted = false, + Revision = 1, + SortOrder = 4 + }, + new + { + Id = 5, + CertificateTypeId = 1, + Code = "N1", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "JLPT N1", + IsDeleted = false, + Revision = 1, + SortOrder = 5 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DurationMinutes") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MaxScore") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PassingScore") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId", "Code") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.ToTable("CertificateSections"); + + b.HasData( + new + { + Id = 1, + CertificateLevelId = 1, + Code = "N5_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5285), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 1 + }, + new + { + Id = 2, + CertificateLevelId = 1, + Code = "N5_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5292), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 2 + }, + new + { + Id = 3, + CertificateLevelId = 1, + Code = "N5_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5294), + Description = "Phần thi nghe hiểu tình huống giao tiếp hàng ngày cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 4 + }, + new + { + Id = 16, + CertificateLevelId = 1, + Code = "N5_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5308), + Description = "Phần thi đọc hiểu văn bản, thông báo và đoạn hội thoại ngắn cấp độ N5", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 3 + }, + new + { + Id = 4, + CertificateLevelId = 2, + Code = "N4_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5295), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 5, + CertificateLevelId = 2, + Code = "N4_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5296), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 6, + CertificateLevelId = 2, + Code = "N4_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5297), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 7, + CertificateLevelId = 2, + Code = "N4_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5298), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N4", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 8, + CertificateLevelId = 3, + Code = "N3_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5300), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 9, + CertificateLevelId = 3, + Code = "N3_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5301), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 10, + CertificateLevelId = 3, + Code = "N3_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5302), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 11, + CertificateLevelId = 3, + Code = "N3_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5303), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N3", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 12, + CertificateLevelId = 4, + Code = "N2_VOCAB", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5304), + Description = "Phần thi kiểm tra chữ Hán, cách đọc và từ vựng cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Từ vựng)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 13, + CertificateLevelId = 4, + Code = "N2_GRAMMAR", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5305), + Description = "Phần thi kiểm tra cấu trúc ngữ pháp và sắp xếp câu cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Kiến thức ngôn ngữ (Ngữ pháp)", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 14, + CertificateLevelId = 4, + Code = "N2_READING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5306), + Description = "Phần thi đọc hiểu văn bản, thông báo và biểu mẫu cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Đọc hiểu", + PassingScore = 0, + SortOrder = 0 + }, + new + { + Id = 15, + CertificateLevelId = 4, + Code = "N2_LISTENING", + CreatedDate = new DateTime(2026, 10, 31, 11, 13, 24, 991, DateTimeKind.Utc).AddTicks(5307), + Description = "Phần thi nghe hiểu hội thoại và tình huống thực tế cấp độ N2", + IsDeleted = false, + MaxScore = 0, + Name = "Nghe hiểu", + PassingScore = 0, + SortOrder = 0 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("CertificateTypes", null, t => + { + t.HasCheckConstraint("CK_CertificateTypes_SortOrder", "\"SortOrder\" >= 1"); + }); + + b.HasData( + new + { + Id = 1, + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese-Language Proficiency Test", + IsActive = true, + IsDeleted = false, + Name = "JLPT", + Revision = 1, + SortOrder = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DueAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PublishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("QuestionCount") + .HasColumnType("integer"); + + b.Property("QuestionSnapshotJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SkillCodes") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StructureKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("CohortId", "IsDeleted", "DueAtUtc"); + + b.ToTable("ClassQuizzes", null, t => + { + t.HasCheckConstraint("CK_ClassQuiz_QuestionCount", "\"QuestionCount\" BETWEEN 1 AND 200"); + + t.HasCheckConstraint("CK_ClassQuiz_Status", "\"Status\" IN ('Published','Cancelled')"); + + t.HasCheckConstraint("CK_ClassQuiz_TimeLimit", "\"TimeLimitMinutes\" BETWEEN 1 AND 240"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssignedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AttemptId") + .HasColumnType("integer"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("QuizId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AttemptId") + .IsUnique() + .HasFilter("\"AttemptId\" IS NOT NULL"); + + b.HasIndex("EnrollmentId"); + + b.HasIndex("LearnerId", "EnrollmentId"); + + b.HasIndex("QuizId", "LearnerId") + .IsUnique(); + + b.ToTable("ClassQuizAssignments", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Category") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecidedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecidedById") + .HasColumnType("integer"); + + b.Property("Decision") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorAccessGrantedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorDisclosure") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorEvidenceAllowed") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRespondedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorResponse") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RefundReviewRequested") + .HasColumnType("boolean"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Title") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CohortId"); + + b.HasIndex("CourseId"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("DecidedById"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.HasIndex("MentorId", "Status", "CreatedAtUtc"); + + b.ToTable("CohortComplaints", null, t => + { + t.HasCheckConstraint("CK_CohortComplaint_Category", "\"Category\" IN ('TeachingQuality', 'MentorConduct', 'Schedule', 'PaymentEnrollment', 'Other')"); + + t.HasCheckConstraint("CK_CohortComplaint_Decision", "(\"Status\" NOT IN ('Resolved', 'Rejected') OR (\"Decision\" IS NOT NULL AND length(btrim(\"Decision\")) > 0 AND \"DecidedById\" IS NOT NULL AND \"DecidedAtUtc\" IS NOT NULL))"); + + t.HasCheckConstraint("CK_CohortComplaint_Message", "length(btrim(\"Message\")) BETWEEN 10 AND 2000"); + + t.HasCheckConstraint("CK_CohortComplaint_RefundReview", "NOT \"RefundReviewRequested\" OR \"Category\" = 'PaymentEnrollment'"); + + t.HasCheckConstraint("CK_CohortComplaint_Status", "\"Status\" IN ('Open', 'UnderReview', 'NeedsInformation', 'Resolved', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaintEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ComplaintId") + .HasColumnType("integer"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("ComplaintId", "Id"); + + b.ToTable("CohortComplaintEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortEnrollmentEntitlement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ConsumedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ConsumedByCourseId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EntitlementReference") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("GrantedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("GrantedById") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("RevocationReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RevokedById") + .HasColumnType("integer"); + + b.Property("SourceType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("StudyCohortId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EntitlementReference") + .IsUnique(); + + b.HasIndex("LearnerId"); + + b.HasIndex("PlanId"); + + b.HasIndex("StudyCohortId", "LearnerId") + .IsUnique() + .HasFilter("\"Status\" = 'Active' AND \"IsDeleted\" = false"); + + b.ToTable("CohortEnrollmentEntitlements", null, t => + { + t.HasCheckConstraint("CK_CohortEnrollmentEntitlement_NoCredit", "\"SourceType\" NOT IN ('ConsultationCredit', 'Credit1on1', 'OneOnOneCredit')"); + + t.HasCheckConstraint("CK_CohortEnrollmentEntitlement_Status", "\"Status\" IN ('Active', 'Consumed', 'Revoked', 'Expired')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortLearningFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RespondedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RespondedById") + .HasColumnType("integer"); + + b.Property("Response") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("Topic") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("MentorId"); + + b.HasIndex("RespondedById"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.ToTable("CohortLearningFeedback", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortMentorReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("Comment") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHidden") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CohortId"); + + b.HasIndex("LearnerId"); + + b.HasIndex("CourseId", "MentorId") + .IsUnique(); + + b.HasIndex("MentorId", "IsHidden", "CreatedAtUtc"); + + b.ToTable("CohortMentorReviews", null, t => + { + t.HasCheckConstraint("CK_CohortMentorReview_Rating", "\"Rating\" BETWEEN 1 AND 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CohortRevisionSnapshot") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("ImpactSnapshot") + .IsRequired() + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RequestedById") + .HasColumnType("integer"); + + b.Property("RequestedByRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("ShiftWeeks") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("CohortId") + .IsUnique() + .HasDatabaseName("IX_CohortScheduleRequests_PendingCohort") + .HasFilter("\"Status\" = 'Pending'"); + + b.HasIndex("ReviewedById"); + + b.HasIndex("CohortId", "Id"); + + b.HasIndex("RequestedById", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.ToTable("CohortScheduleRequests", null, t => + { + t.HasCheckConstraint("CK_CohortScheduleRequest_Decision", "(\"Status\" NOT IN ('Approved', 'Rejected') OR (\"ReviewedById\" IS NOT NULL AND \"ReviewedAtUtc\" IS NOT NULL)) AND (\"Status\" <> 'Rejected' OR (\"DecisionNote\" IS NOT NULL AND length(btrim(\"DecisionNote\")) > 0))"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Kind", "\"Kind\" IN ('ShiftWeeks', 'CancelEmptyCohort')"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Reason", "length(btrim(\"Reason\")) BETWEEN 10 AND 1000"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_ShiftWeeks", "(\"Kind\" = 'ShiftWeeks' AND \"ShiftWeeks\" BETWEEN 1 AND 8) OR (\"Kind\" = 'CancelEmptyCohort' AND \"ShiftWeeks\" IS NULL)"); + + t.HasCheckConstraint("CK_CohortScheduleRequest_Status", "\"Status\" IN ('Pending', 'Approved', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequestEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("RequestId", "Id"); + + b.ToTable("CohortScheduleRequestEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DestinationCourseId") + .HasColumnType("integer"); + + b.Property("EligibilitySnapshot") + .HasColumnType("text"); + + b.Property("EvidenceUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("PolicyId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RequestedTargetCohortId") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SourceCohortId") + .HasColumnType("integer"); + + b.Property("SourceCourseId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TargetCohortId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DestinationCourseId") + .IsUnique() + .HasFilter("\"DestinationCourseId\" IS NOT NULL"); + + b.HasIndex("PolicyId"); + + b.HasIndex("RequestedTargetCohortId"); + + b.HasIndex("ReviewedById"); + + b.HasIndex("SourceCohortId"); + + b.HasIndex("SourceCourseId") + .IsUnique() + .HasDatabaseName("IX_CohortTransferRequests_PendingSource") + .HasFilter("\"Status\" = 'Pending'"); + + b.HasIndex("TargetCohortId"); + + b.HasIndex("LearnerId", "IdempotencyKey") + .IsUnique(); + + b.HasIndex("Status", "CreatedAtUtc"); + + b.ToTable("CohortTransferRequests", null, t => + { + t.HasCheckConstraint("CK_CohortTransferRequest_Decision", "(\"Status\" <> 'Approved' OR (\"TargetCohortId\" IS NOT NULL AND \"DestinationCourseId\" IS NOT NULL AND \"ReviewedById\" IS NOT NULL)) AND (\"Status\" <> 'Rejected' OR (\"DecisionNote\" IS NOT NULL AND length(btrim(\"DecisionNote\")) > 0 AND \"ReviewedById\" IS NOT NULL))"); + + t.HasCheckConstraint("CK_CohortTransferRequest_Status", "\"Status\" IN ('Pending', 'Approved', 'Rejected', 'Withdrawn')"); + + t.HasCheckConstraint("CK_CohortTransferRequest_Target", "\"TargetCohortId\" IS NULL OR \"TargetCohortId\" <> \"SourceCohortId\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequestEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("RequestId", "Id"); + + b.ToTable("CohortTransferRequestEvents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAiReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentId") + .HasColumnType("integer"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ErrorCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IssuesJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("RequestedByUserId") + .HasColumnType("integer"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Summary") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Verdict") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("WarningCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContentType", "ContentId", "ReviewedAt"); + + b.ToTable("ContentAiReviews"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentApprovalRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("BatchId") + .HasColumnType("uuid"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DiffSummaryJson") + .HasColumnType("text"); + + b.Property("EntityType") + .HasColumnType("integer"); + + b.Property("IdempotencyKey") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReviewHistoryJson") + .HasColumnType("jsonb"); + + b.Property("ReviewNote") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByName") + .HasColumnType("text"); + + b.Property("RightsConfirmed") + .HasColumnType("boolean"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RowKey") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SourceFileName") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("character varying(260)"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceRowNumber") + .HasColumnType("integer"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("ImportExcel"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedByUserId") + .HasColumnType("integer"); + + b.Property("TargetEntityId") + .HasColumnType("integer"); + + b.Property("ValidationSummaryJson") + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("BatchId"); + + b.HasIndex("SubmittedByUserId"); + + b.HasIndex("EntityType", "Status"); + + b.HasIndex("SubmittedByUserId", "IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.ToTable("ContentApprovalRequests"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAudioTranscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AttemptCount") + .HasColumnType("integer"); + + b.Property("AudioUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("AudioUrlHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Confidence") + .HasColumnType("double precision"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("integer"); + + b.Property("ErrorCode") + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("ErrorMessage") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("LanguageCode") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("LeaseExpiresAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LeaseId") + .HasColumnType("uuid"); + + b.Property("NextAttemptAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RawTranscriptJson") + .HasColumnType("jsonb"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Transcript") + .HasColumnType("text"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("AudioUrlHash") + .IsUnique(); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("Status", "NextAttemptAtUtc", "LeaseExpiresAtUtc"); + + b.ToTable("ContentAudioTranscriptions", null, t => + { + t.HasCheckConstraint("CK_ContentAudioTranscription_Attempts", "\"AttemptCount\" >= 0"); + + t.HasCheckConstraint("CK_ContentAudioTranscription_Language", "\"LanguageCode\" = 'ja-JP'"); + + t.HasCheckConstraint("CK_ContentAudioTranscription_Status", "\"Status\" IN ('Pending', 'Processing', 'Completed', 'Failed')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentBankItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EntityType") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LatestBatchId") + .HasColumnType("uuid"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NaturalKey") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OwnerUserId") + .HasColumnType("integer"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TargetEntityId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EntityType", "TargetEntityId"); + + b.HasIndex("OwnerUserId", "EntityType", "NaturalKey") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.ToTable("ContentBankItems"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentLevelMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanjiId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("CertificateLevelId", "GrammarPatternId") + .IsUnique() + .HasFilter("\"GrammarPatternId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.HasIndex("CertificateLevelId", "KanjiId") + .IsUnique() + .HasFilter("\"KanjiId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.HasIndex("CertificateLevelId", "VocabularyId") + .IsUnique() + .HasFilter("\"VocabularyId\" IS NOT NULL AND \"IsDeleted\" = false"); + + b.ToTable("ContentLevelMappings", t => + { + t.HasCheckConstraint("CK_ContentLevelMappings_ExactlyOneContent", "(CASE WHEN \"KanjiId\" IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN \"VocabularyId\" IS NOT NULL THEN 1 ELSE 0 END) + (CASE WHEN \"GrammarPatternId\" IS NOT NULL THEN 1 ELSE 0 END) = 1"); + }); + + b.HasData( + new + { + Id = 920001, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910001 + }, + new + { + Id = 920002, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910002 + }, + new + { + Id = 920003, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910003 + }, + new + { + Id = 920004, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910004 + }, + new + { + Id = 920005, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910005 + }, + new + { + Id = 920006, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910006 + }, + new + { + Id = 920007, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910007 + }, + new + { + Id = 920008, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910008 + }, + new + { + Id = 920009, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910009 + }, + new + { + Id = 920010, + CertificateLevelId = 1, + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KanjiId = 910010 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("AudioTranscript") + .HasColumnType("text"); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("ContentFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("Instructions") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ListeningSection") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("MockTestSectionId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ParentPassageId") + .HasColumnType("integer"); + + b.Property("PassageCode") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("PassageIdentity") + .HasColumnType("uuid"); + + b.Property("PassageText") + .HasColumnType("text"); + + b.Property("PlaybackPolicyJson") + .HasColumnType("jsonb"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContentFingerprint"); + + b.HasIndex("MockTestSectionId"); + + b.HasIndex("PassageIdentity"); + + b.ToTable("ContentPassages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseAuditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("At") + .HasColumnType("timestamp without time zone"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.ToTable("CourseAuditEntries", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseRetakeRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("EligibilitySnapshot") + .HasColumnType("text"); + + b.Property("EvidenceUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorSupportPlan") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorSupportPlanAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorSupportPlanById") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("ResultPublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("CourseId") + .IsUnique() + .HasFilter("\"Status\" = 'Pending'"); + + b.ToTable("CourseRetakeRequests", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseScheduleRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Reason") + .IsRequired() + .HasColumnType("text"); + + b.Property("RequestedById") + .HasColumnType("integer"); + + b.Property("Response") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("SessionId") + .HasColumnType("integer"); + + b.Property("Status") + .IsConcurrencyToken() + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CourseId", "SessionId") + .IsUnique() + .HasFilter("\"Status\" = 'Pending'"); + + b.ToTable("CourseScheduleRequests", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.EmailVerification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsUsed") + .HasColumnType("boolean"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("VerificationCode") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("EmailVerifications"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Feature", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccessMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("FREE"); + + b.Property("Category") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("general"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditFeatureKey") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsCoreFree") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("RoutePrefixesJson") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("Features"); + + b.HasData( + new + { + Id = 1, + AccessMode = "PLAN_REQUIRED", + Category = "self_study", + Code = "LESSONS_CONTENT", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập kho bài học JLPT đầy đủ theo cấp độ kèm nghe hiểu, đọc hiểu và lưu tiến độ.", + IsCoreFree = false, + IsDeleted = false, + Name = "Thư viện bài học JLPT", + RoutePrefixesJson = "[\"/lessons\",\"/lesson-player\",\"/riki/listening\",\"/riki/reading\"]", + SortOrder = 10 + }, + new + { + Id = 2, + AccessMode = "FREE", + Category = "core_tools", + Code = "JAPANESE_LIBRARY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Tra cứu ngữ pháp, luyện viết Hiragana, Katakana và Kanji theo thứ tự nét miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Thư viện Kana, Kanji & Ngữ pháp", + RoutePrefixesJson = "[\"/grammar\",\"/kanji-writing\",\"/vocabulary-detail\"]", + SortOrder = 3 + }, + new + { + Id = 3, + AccessMode = "FREE", + Category = "practice_exam", + Code = "PRACTICE_EXERCISES", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Làm bài luyện tập củng cố kỹ năng và bộ đề theo cấp độ JLPT.", + IsCoreFree = false, + IsDeleted = false, + Name = "Bài luyện tập theo kỹ năng", + RoutePrefixesJson = "[\"/lesson-practice\",\"/practice-sets\"]", + SortOrder = 20 + }, + new + { + Id = 4, + AccessMode = "FREE", + Category = "practice_exam", + Code = "MOCK_TESTS", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Luyện đề thi thử JLPT mô phỏng đầy đủ 4 kỹ năng và theo dõi kết quả.", + IsCoreFree = false, + IsDeleted = false, + Name = "Đề thi thử JLPT", + RoutePrefixesJson = "[\"/mock-test\",\"/mock-tests\",\"/exam-result\"]", + SortOrder = 21 + }, + new + { + Id = 5, + AccessMode = "FREE", + Category = "self_study", + Code = "STANDARD_ROADMAP", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Xem lộ trình học JLPT tiêu chuẩn theo mục tiêu, kết quả đánh giá năng lực và tiến độ học.", + IsCoreFree = false, + IsDeleted = false, + Name = "Lộ trình tiêu chuẩn & Tiến độ học", + RoutePrefixesJson = "[\"/roadmap\"]", + SortOrder = 11 + }, + new + { + Id = 6, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_MOCK_EXPLANATION", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "mock_test_explanation", + Description = "Nhận phân tích chi tiết đáp án đề thi thử từ trợ lý AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Giải thích câu hỏi bằng AI", + SortOrder = 33 + }, + new + { + Id = 7, + AccessMode = "DISABLED", + Category = "mentor_legacy", + Code = "MENTOR_1ON1_LEGACY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Gói cũ bao gồm 12 buổi ôn luyện trực tiếp 1-1 với Mentor (đã thay bằng lớp học nhóm).", + IsCoreFree = false, + IsDeleted = false, + Name = "12 buổi meeting 1-1 với Mentor", + SortOrder = 90 + }, + new + { + Id = 8, + AccessMode = "DISABLED", + Category = "mentor_legacy", + Code = "MENTOR_ROOM_LEGACY", + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Cấu hình lịch 1-1 cũ (lớp học nhóm dùng cơ chế ghi danh khóa học riêng).", + IsCoreFree = false, + IsDeleted = false, + Name = "Đặt lịch và phòng học trực tuyến", + SortOrder = 91 + }, + new + { + Id = 9, + AccessMode = "FREE", + Category = "core_tools", + Code = "PERSONAL_NOTEBOOK", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Tạo thư mục, tệp ghi chú, trang bài học, highlight và mục đã lưu cá nhân miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Sổ tay cá nhân & Mini Notebook", + RoutePrefixesJson = "[\"/kanji-notebook\"]", + SortOrder = 1 + }, + new + { + Id = 10, + AccessMode = "FREE", + Category = "core_tools", + Code = "SRS_STUDY", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Ôn thẻ đến hạn, 4 chế độ ôn tự do, quản lý thẻ cá nhân và thư viện thẻ mẫu miễn phí.", + IsCoreFree = true, + IsDeleted = false, + Name = "Ôn tập SRS & Thư viện thẻ mẫu", + RoutePrefixesJson = "[\"/daily-srs\"]", + SortOrder = 2 + }, + new + { + Id = 11, + AccessMode = "FREE", + Category = "practice_exam", + Code = "PLACEMENT_TEST", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Làm bài đánh giá trình độ JLPT đầu vào để xác định cấp độ học phù hợp.", + IsCoreFree = false, + IsDeleted = false, + Name = "Đánh giá năng lực đầu vào", + RoutePrefixesJson = "[\"/placement\"]", + SortOrder = 19 + }, + new + { + Id = 12, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_LEARNING_PATH", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "learning_path", + Description = "Tạo kế hoạch học tập chi tiết theo ngày bằng AI dựa trên điểm đánh giá và ngày thi.", + IsCoreFree = false, + IsDeleted = false, + Name = "Lộ trình học cá nhân hóa bằng AI", + SortOrder = 30 + }, + new + { + Id = 13, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_SPEAKING", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "speaking", + Description = "Thu âm tiếng Nhật và nhận điểm phát âm, ngữ điệu cùng nhận xét chi tiết từ AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Luyện nói & Chấm phát âm AI", + RoutePrefixesJson = "[\"/riki/speaking\",\"/speech\"]", + SortOrder = 31 + }, + new + { + Id = 14, + AccessMode = "CREDIT_REQUIRED", + Category = "ai_services", + Code = "AI_WRITING", + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + CreditFeatureKey = "writing", + Description = "Viết câu và bài luận tiếng Nhật, nhận sửa lỗi ngữ pháp và chấm điểm từ AI.", + IsCoreFree = false, + IsDeleted = false, + Name = "Luyện viết & Chấm bài luận AI", + RoutePrefixesJson = "[\"/riki/essay\",\"/sentence-studio\"]", + SortOrder = 32 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GradingResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FeedbackJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("GradedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("HomeworkSubmissionId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OverallScore") + .HasColumnType("double precision"); + + b.Property("PracticeSubmissionId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HomeworkSubmissionId") + .IsUnique(); + + b.HasIndex("PracticeSubmissionId") + .IsUnique(); + + b.ToTable("GradingResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentenceMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("Structure") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UsageNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("Title"); + + b.HasIndex("UserAccountId"); + + b.ToTable("GrammarPatterns"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiDraftFeedback") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("AiDraftGeneratedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("AiDraftScore") + .HasColumnType("double precision"); + + b.Property("AiDraftUnavailableReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AssignmentScope") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("Booking1on1"); + + b.Property("AuthoredDefinitionJson") + .HasColumnType("text"); + + b.Property("CohortAssignmentGroupKey") + .HasColumnType("uuid"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DueAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Instructions") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorFeedback") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorScore") + .HasColumnType("double precision"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Passed") + .HasColumnType("boolean"); + + b.Property("PublishedByMentorId") + .HasColumnType("integer"); + + b.Property("PublishedFeedbackAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("StudyCourseId") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("MentorId"); + + b.HasIndex("StudyCourseId"); + + b.HasIndex("CohortId", "LearnerId"); + + b.HasIndex("LearnerId", "DueAt"); + + b.ToTable("HomeworkAssignments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentAttachment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileKey") + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StorageReference") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("FileKey"); + + b.HasIndex("HomeworkAssignmentId"); + + b.ToTable("HomeworkAssignmentAttachments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentExercise", b => + { + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.HasKey("HomeworkAssignmentId", "PracticeExerciseId"); + + b.HasIndex("PracticeExerciseId"); + + b.ToTable("HomeworkAssignmentExercises", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentLesson", b => + { + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.HasKey("HomeworkAssignmentId", "LessonId"); + + b.HasIndex("LessonId"); + + b.ToTable("HomeworkAssignmentLessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileUrl") + .HasColumnType("text"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastRevisedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PrivateAudioReference") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PrivateScanReference") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("RevisionCount") + .HasColumnType("integer"); + + b.Property("ScanStorageUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SelectedOptionsJson") + .HasColumnType("text"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TextContent") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("HomeworkAssignmentId") + .IsUnique(); + + b.HasIndex("LearnerId"); + + b.HasIndex("LessonId"); + + b.ToTable("HomeworkSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmissionFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FileKey") + .HasColumnType("uuid"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("HomeworkSubmissionId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StorageReference") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("FileKey"); + + b.HasIndex("HomeworkSubmissionId"); + + b.ToTable("HomeworkSubmissionFiles"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptExamSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExamDate") + .HasColumnType("date"); + + b.Property("ImportedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Location") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ReviewNote") + .HasColumnType("text"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedById") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SourceUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("Status") + .IsConcurrencyToken() + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("SourceKey") + .IsUnique(); + + b.ToTable("JlptExamSchedules", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptLevelPayCoefficient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("Coefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ConfiguredByAdminId"); + + b.HasIndex("CertificateLevelId", "EffectiveFromUtc") + .IsUnique(); + + b.ToTable("JlptLevelPayCoefficients", t => + { + t.HasCheckConstraint("CK_JlptLevelPayCoefficient_Positive", "\"Coefficient\" > 0"); + + t.HasCheckConstraint("CK_JlptLevelPayCoefficient_Range", "\"EffectiveUntilUtc\" IS NULL OR \"EffectiveUntilUtc\" > \"EffectiveFromUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("Character") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Romaji") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StrokeCount") + .HasColumnType("integer"); + + b.Property("StrokeOrderImageUrl") + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("Character", "Type") + .IsUnique(); + + b.ToTable("KanaCharacters"); + + b.HasData( + new + { + Id = 1, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/22/Ja-a.ogg", + Character = "あ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1757), + IsDeleted = false, + Romaji = "a", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 2, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-i.ogg", + Character = "い", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1766), + IsDeleted = false, + Romaji = "i", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 3, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Ja-u.ogg", + Character = "う", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1768), + IsDeleted = false, + Romaji = "u", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 4, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/21/Ja-e.ogg", + Character = "え", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1770), + IsDeleted = false, + Romaji = "e", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 5, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/df/Ja-o.ogg", + Character = "お", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1771), + IsDeleted = false, + Romaji = "o", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 6, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Ja-ka.ogg", + Character = "か", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1774), + IsDeleted = false, + Romaji = "ka", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 7, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/87/Ja-ki.ogg", + Character = "き", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1775), + IsDeleted = false, + Romaji = "ki", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 8, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Ja-ku.ogg", + Character = "く", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1776), + IsDeleted = false, + Romaji = "ku", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 9, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b3/Ja-ke.ogg", + Character = "け", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1830), + IsDeleted = false, + Romaji = "ke", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 10, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/18/Ja-ko.ogg", + Character = "こ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1832), + IsDeleted = false, + Romaji = "ko", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 11, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Ja-sa.ogg", + Character = "さ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1833), + IsDeleted = false, + Romaji = "sa", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 12, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/80/Ja-shi.ogg", + Character = "し", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1834), + IsDeleted = false, + Romaji = "shi", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 13, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Ja-su.ogg", + Character = "す", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1835), + IsDeleted = false, + Romaji = "su", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 14, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a8/Ja-se.ogg", + Character = "せ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1836), + IsDeleted = false, + Romaji = "se", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 15, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/00/Ja-so.ogg", + Character = "そ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1837), + IsDeleted = false, + Romaji = "so", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 16, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/d2/Ja-ta.ogg", + Character = "た", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1838), + IsDeleted = false, + Romaji = "ta", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 17, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/38/Ja-chi.ogg", + Character = "ち", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1838), + IsDeleted = false, + Romaji = "chi", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 18, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/32/Ja-tsu.ogg", + Character = "つ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1840), + IsDeleted = false, + Romaji = "tsu", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 19, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/10/Ja-te.ogg", + Character = "て", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1841), + IsDeleted = false, + Romaji = "te", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 20, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a5/Ja-to.ogg", + Character = "と", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1842), + IsDeleted = false, + Romaji = "to", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 21, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/92/Ja-na.ogg", + Character = "な", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1843), + IsDeleted = false, + Romaji = "na", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 22, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b7/Ja-ni.ogg", + Character = "に", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1844), + IsDeleted = false, + Romaji = "ni", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 23, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b1/Ja-nu.ogg", + Character = "ぬ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1845), + IsDeleted = false, + Romaji = "nu", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 24, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/86/Ja-ne.ogg", + Character = "ね", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1845), + IsDeleted = false, + Romaji = "ne", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 25, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/54/Ja-no.ogg", + Character = "の", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1846), + IsDeleted = false, + Romaji = "no", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 26, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/Ja-ha.ogg", + Character = "は", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1847), + IsDeleted = false, + Romaji = "ha", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 27, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/99/Ja-hi.ogg", + Character = "ひ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1848), + IsDeleted = false, + Romaji = "hi", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 28, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/70/Ja-fu.ogg", + Character = "ふ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1849), + IsDeleted = false, + Romaji = "fu", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 29, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2a/Ja-he.ogg", + Character = "へ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1849), + IsDeleted = false, + Romaji = "he", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 30, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Ja-ho.ogg", + Character = "ほ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1850), + IsDeleted = false, + Romaji = "ho", + StrokeCount = 4, + Type = "Hiragana" + }, + new + { + Id = 31, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Ja-ma.ogg", + Character = "ま", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1851), + IsDeleted = false, + Romaji = "ma", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 32, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/16/Ja-mi.ogg", + Character = "み", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1852), + IsDeleted = false, + Romaji = "mi", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 33, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ja-mu.ogg", + Character = "む", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1852), + IsDeleted = false, + Romaji = "mu", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 34, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/8b/Ja-me.ogg", + Character = "め", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1913), + IsDeleted = false, + Romaji = "me", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 35, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Ja-mo.ogg", + Character = "も", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1915), + IsDeleted = false, + Romaji = "mo", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 36, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/e8/Ja-ya.ogg", + Character = "や", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1915), + IsDeleted = false, + Romaji = "ya", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 37, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/7b/Ja-yu.ogg", + Character = "ゆ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1916), + IsDeleted = false, + Romaji = "yu", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 38, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c9/Ja-yo.ogg", + Character = "よ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1917), + IsDeleted = false, + Romaji = "yo", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 39, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/04/Ja-ra.ogg", + Character = "ら", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1918), + IsDeleted = false, + Romaji = "ra", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 40, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/76/Ja-ri.ogg", + Character = "り", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1919), + IsDeleted = false, + Romaji = "ri", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 41, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/56/Ja-ru.ogg", + Character = "る", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1920), + IsDeleted = false, + Romaji = "ru", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 42, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/57/Ja-re.ogg", + Character = "れ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1920), + IsDeleted = false, + Romaji = "re", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 43, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Ja-ro.ogg", + Character = "ろ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1922), + IsDeleted = false, + Romaji = "ro", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 44, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Ja-wa.ogg", + Character = "わ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1922), + IsDeleted = false, + Romaji = "wa", + StrokeCount = 2, + Type = "Hiragana" + }, + new + { + Id = 45, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/77/Ja-wo.ogg", + Character = "を", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1923), + IsDeleted = false, + Romaji = "wo", + StrokeCount = 3, + Type = "Hiragana" + }, + new + { + Id = 46, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0c/Ja-n.ogg", + Character = "ん", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1924), + IsDeleted = false, + Romaji = "n", + StrokeCount = 1, + Type = "Hiragana" + }, + new + { + Id = 47, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/22/Ja-a.ogg", + Character = "ア", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1955), + IsDeleted = false, + Romaji = "a", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 48, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/28/Ja-i.ogg", + Character = "イ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1958), + IsDeleted = false, + Romaji = "i", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 49, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a2/Ja-u.ogg", + Character = "ウ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1959), + IsDeleted = false, + Romaji = "u", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 50, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/21/Ja-e.ogg", + Character = "エ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1960), + IsDeleted = false, + Romaji = "e", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 51, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/df/Ja-o.ogg", + Character = "オ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1961), + IsDeleted = false, + Romaji = "o", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 52, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2e/Ja-ka.ogg", + Character = "カ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1961), + IsDeleted = false, + Romaji = "ka", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 53, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/87/Ja-ki.ogg", + Character = "キ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1962), + IsDeleted = false, + Romaji = "ki", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 54, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Ja-ku.ogg", + Character = "ク", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1963), + IsDeleted = false, + Romaji = "ku", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 55, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b3/Ja-ke.ogg", + Character = "ケ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(1964), + IsDeleted = false, + Romaji = "ke", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 56, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/18/Ja-ko.ogg", + Character = "コ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2006), + IsDeleted = false, + Romaji = "ko", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 57, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Ja-sa.ogg", + Character = "サ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2009), + IsDeleted = false, + Romaji = "sa", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 58, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/80/Ja-shi.ogg", + Character = "シ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2010), + IsDeleted = false, + Romaji = "shi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 59, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Ja-su.ogg", + Character = "ス", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2011), + IsDeleted = false, + Romaji = "su", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 60, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a8/Ja-se.ogg", + Character = "セ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2012), + IsDeleted = false, + Romaji = "se", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 61, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/00/Ja-so.ogg", + Character = "ソ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2014), + IsDeleted = false, + Romaji = "so", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 62, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/d/d2/Ja-ta.ogg", + Character = "タ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2015), + IsDeleted = false, + Romaji = "ta", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 63, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/38/Ja-chi.ogg", + Character = "チ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2016), + IsDeleted = false, + Romaji = "chi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 64, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/3/32/Ja-tsu.ogg", + Character = "ツ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2017), + IsDeleted = false, + Romaji = "tsu", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 65, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/10/Ja-te.ogg", + Character = "テ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2019), + IsDeleted = false, + Romaji = "te", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 66, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a5/Ja-to.ogg", + Character = "ト", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2022), + IsDeleted = false, + Romaji = "to", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 67, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/92/Ja-na.ogg", + Character = "ナ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2023), + IsDeleted = false, + Romaji = "na", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 68, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b7/Ja-ni.ogg", + Character = "ニ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2024), + IsDeleted = false, + Romaji = "ni", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 69, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b1/Ja-nu.ogg", + Character = "ヌ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2026), + IsDeleted = false, + Romaji = "nu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 70, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/86/Ja-ne.ogg", + Character = "ネ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2027), + IsDeleted = false, + Romaji = "ne", + StrokeCount = 4, + Type = "Katakana" + }, + new + { + Id = 71, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/54/Ja-no.ogg", + Character = "ノ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2028), + IsDeleted = false, + Romaji = "no", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 72, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/08/Ja-ha.ogg", + Character = "ハ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2029), + IsDeleted = false, + Romaji = "ha", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 73, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/9/99/Ja-hi.ogg", + Character = "ヒ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2030), + IsDeleted = false, + Romaji = "hi", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 74, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/70/Ja-fu.ogg", + Character = "フ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2032), + IsDeleted = false, + Romaji = "fu", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 75, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/2/2a/Ja-he.ogg", + Character = "ヘ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2033), + IsDeleted = false, + Romaji = "he", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 76, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Ja-ho.ogg", + Character = "ホ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2034), + IsDeleted = false, + Romaji = "ho", + StrokeCount = 4, + Type = "Katakana" + }, + new + { + Id = 77, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Ja-ma.ogg", + Character = "マ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2036), + IsDeleted = false, + Romaji = "ma", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 78, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/1/16/Ja-mi.ogg", + Character = "ミ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2037), + IsDeleted = false, + Romaji = "mi", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 79, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ja-mu.ogg", + Character = "ム", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2038), + IsDeleted = false, + Romaji = "mu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 80, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/8/8b/Ja-me.ogg", + Character = "メ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2039), + IsDeleted = false, + Romaji = "me", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 81, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c1/Ja-mo.ogg", + Character = "モ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2086), + IsDeleted = false, + Romaji = "mo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 82, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/e8/Ja-ya.ogg", + Character = "ヤ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2087), + IsDeleted = false, + Romaji = "ya", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 83, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/7b/Ja-yu.ogg", + Character = "ユ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2088), + IsDeleted = false, + Romaji = "yu", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 84, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/c/c9/Ja-yo.ogg", + Character = "ヨ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2089), + IsDeleted = false, + Romaji = "yo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 85, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/04/Ja-ra.ogg", + Character = "ラ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2090), + IsDeleted = false, + Romaji = "ra", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 86, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/76/Ja-ri.ogg", + Character = "リ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2092), + IsDeleted = false, + Romaji = "ri", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 87, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/56/Ja-ru.ogg", + Character = "ル", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2093), + IsDeleted = false, + Romaji = "ru", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 88, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/5/57/Ja-re.ogg", + Character = "レ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2094), + IsDeleted = false, + Romaji = "re", + StrokeCount = 1, + Type = "Katakana" + }, + new + { + Id = 89, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/e/ed/Ja-ro.ogg", + Character = "ロ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2096), + IsDeleted = false, + Romaji = "ro", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 90, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Ja-wa.ogg", + Character = "ワ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2097), + IsDeleted = false, + Romaji = "wa", + StrokeCount = 2, + Type = "Katakana" + }, + new + { + Id = 91, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/7/77/Ja-wo.ogg", + Character = "ヲ", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2098), + IsDeleted = false, + Romaji = "wo", + StrokeCount = 3, + Type = "Katakana" + }, + new + { + Id = 92, + AudioUrl = "https://upload.wikimedia.org/wikipedia/commons/0/0c/Ja-n.ogg", + Character = "ン", + CreatedDate = new DateTime(2026, 10, 26, 16, 6, 11, 768, DateTimeKind.Utc).AddTicks(2099), + IsDeleted = false, + Romaji = "n", + StrokeCount = 2, + Type = "Katakana" + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EaseFactor") + .HasColumnType("double precision"); + + b.Property("IntervalDays") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanaCharacterId") + .HasColumnType("integer"); + + b.Property("LastReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NextReviewDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Repetitions") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("KanaCharacterId"); + + b.HasIndex("UserId", "KanaCharacterId") + .IsUnique(); + + b.HasIndex("UserId", "NextReviewDate"); + + b.ToTable("KanaWritingPracticeCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KanaWritingPracticeCardId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Quality") + .HasColumnType("integer"); + + b.Property("Rating") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalMistakes") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("KanaWritingPracticeCardId"); + + b.ToTable("KanaWritingPracticeHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("Character") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KunYomi") + .HasColumnType("text"); + + b.Property("Meaning") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OnYomi") + .HasColumnType("text"); + + b.Property("SinoVietnamese") + .HasColumnType("text"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("StrokeCount") + .HasColumnType("integer"); + + b.Property("StrokeOrderImageUrl") + .HasColumnType("text"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("Character"); + + b.HasIndex("Status"); + + b.HasIndex("UserAccountId"); + + b.ToTable("Kanjis"); + + b.HasData( + new + { + Id = 910001, + Character = "日", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひ、か", + Meaning = "Mặt trời; ngày", + OnYomi = "ニチ、ジツ", + SinoVietnamese = "Nhật", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910002, + Character = "月", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "つき", + Meaning = "Mặt trăng; tháng", + OnYomi = "ゲツ、ガツ", + SinoVietnamese = "Nguyệt", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910003, + Character = "火", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひ、ほ", + Meaning = "Lửa", + OnYomi = "カ", + SinoVietnamese = "Hỏa", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910004, + Character = "水", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "みず", + Meaning = "Nước", + OnYomi = "スイ", + SinoVietnamese = "Thủy", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910005, + Character = "木", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "き、こ", + Meaning = "Cây; gỗ", + OnYomi = "モク、ボク", + SinoVietnamese = "Mộc", + Status = "Published", + StrokeCount = 4, + Version = 1 + }, + new + { + Id = 910006, + Character = "金", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "かね、かな", + Meaning = "Vàng; tiền", + OnYomi = "キン、コン", + SinoVietnamese = "Kim", + Status = "Published", + StrokeCount = 8, + Version = 1 + }, + new + { + Id = 910007, + Character = "土", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "つち", + Meaning = "Đất", + OnYomi = "ド、ト", + SinoVietnamese = "Thổ", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910008, + Character = "山", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "やま", + Meaning = "Núi", + OnYomi = "サン", + SinoVietnamese = "Sơn", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910009, + Character = "川", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "かわ", + Meaning = "Sông", + OnYomi = "セン", + SinoVietnamese = "Xuyên", + Status = "Published", + StrokeCount = 3, + Version = 1 + }, + new + { + Id = 910010, + Character = "人", + CreatedDate = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + IsDeleted = false, + KunYomi = "ひと", + Meaning = "Người", + OnYomi = "ジン、ニン", + SinoVietnamese = "Nhân", + Status = "Published", + StrokeCount = 2, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LanguageSkill", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Code") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique() + .HasFilter("\"Code\" IS NOT NULL"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("LanguageSkills"); + + b.HasData( + new + { + Id = 1, + Code = "VOCABULARY", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese vocabulary learning skill.", + IsDeleted = false, + Name = "Vocabulary" + }, + new + { + Id = 2, + Code = "KANJI", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese kanji learning skill.", + IsDeleted = false, + Name = "Kanji" + }, + new + { + Id = 3, + Code = "GRAMMAR", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese grammar learning skill.", + IsDeleted = false, + Name = "Grammar" + }, + new + { + Id = 4, + Code = "LISTENING", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese listening comprehension skill.", + IsDeleted = false, + Name = "Listening" + }, + new + { + Id = 5, + Code = "READING", + CreatedDate = new DateTime(2026, 9, 29, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Japanese reading comprehension skill.", + IsDeleted = false, + Name = "Reading" + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerEssay", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContentText") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageStoragePath") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageUrl") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OcrLanguage") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("OriginalOcrText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedDate"); + + b.ToTable("LearnerEssays"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("TargetId") + .HasColumnType("integer"); + + b.Property("TargetTitle") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("UpdatedAtUtc", "Id"); + + b.HasIndex("LearnerId", "TargetType", "TargetId") + .IsUnique(); + + b.ToTable("LearnerFeedback", null, t => + { + t.HasCheckConstraint("CK_LearnerFeedback_Rating", "\"Rating\" BETWEEN 1 AND 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerHighlight", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AnchorPrefix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AnchorSuffix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Color") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ContentVersionHash") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EndOffset") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LinkedNoteEntryId") + .HasColumnType("integer"); + + b.Property("LinkedReviewCardId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SelectedText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("StartOffset") + .HasColumnType("integer"); + + b.Property("TargetId") + .HasColumnType("integer"); + + b.Property("TargetKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TargetType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TranslationSnapshot") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LinkedNoteEntryId"); + + b.HasIndex("LinkedReviewCardId"); + + b.HasIndex("UserId", "CreatedDate"); + + b.HasIndex("UserId", "TargetKey"); + + b.HasIndex("UserId", "TargetType", "TargetId"); + + b.ToTable("LearnerHighlights"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FolderId") + .HasColumnType("integer"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("FolderId"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_LearnerNotes_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("UserId", "Name"); + + b.HasIndex("UserId", "FolderId", "IsDeleted", "SortOrder"); + + b.ToTable("LearnerNotes"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContextSnippet") + .HasMaxLength(600) + .HasColumnType("character varying(600)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleMeaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExampleSentence") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("HighlightColor") + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("ItemKind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("manual"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.Property("LearnerNoteId") + .HasColumnType("integer") + .HasColumnName("VocabularyListId"); + + b.Property("ManualMeaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ManualReading") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ManualWord") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("NotebookPageId") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TagsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'[]'::jsonb"); + + b.Property("VocabularyId") + .HasColumnType("integer") + .HasColumnName("VocabularyEntryId"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("LearnerNoteId", "IsDeleted"); + + b.HasIndex("NotebookPageId", "IsDeleted", "SortOrder"); + + b.ToTable("LearnerNoteEntries"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerPracticeAnswer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseAttemptId") + .HasColumnType("integer"); + + b.Property("PracticeQuestionId") + .HasColumnType("integer"); + + b.Property("SelectedOptionId") + .HasColumnType("integer"); + + b.Property("TextAnswer") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("PracticeQuestionId"); + + b.HasIndex("SelectedOptionId"); + + b.HasIndex("PracticeExerciseAttemptId", "PracticeQuestionId") + .IsUnique(); + + b.ToTable("LearnerPracticeAnswers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("EstimatedMinutes") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(15); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer") + .HasColumnName("SkillId"); + + b.Property("LearningObjectives") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PrerequisiteLessonId") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceProvenance") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("TopicId") + .HasColumnType("integer"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("PrerequisiteLessonId"); + + b.HasIndex("Status"); + + b.HasIndex("TopicId"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("CertificateLevelId", "LanguageSkillId"); + + b.ToTable("Lessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonGrammar", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("GrammarPatternId") + .HasColumnType("integer") + .HasColumnName("GrammarPointId"); + + b.HasKey("LessonId", "GrammarPatternId"); + + b.HasIndex("GrammarPatternId"); + + b.ToTable("LessonGrammars"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonKanji", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.HasKey("LessonId", "KanjiId"); + + b.HasIndex("KanjiId"); + + b.ToTable("LessonKanjis"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonProgress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FirstViewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("InteractionCount") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastInteractedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LastPositionSeconds") + .HasColumnType("integer"); + + b.Property("LastWatchedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ProgressPercent") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("LessonId"); + + b.HasIndex("UserId", "LessonId") + .IsUnique(); + + b.ToTable("LessonProgresses"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonVocabulary", b => + { + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("VocabularyId") + .HasColumnType("integer") + .HasColumnName("VocabularyEntryId"); + + b.HasKey("LessonId", "VocabularyId"); + + b.HasIndex("VocabularyId"); + + b.ToTable("LessonVocabularies"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAbuseReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ReporterId") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TargetUserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("ReporterId") + .HasDatabaseName("IX_MentorAbuseReports_ReporterId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorAbuseReports_Status"); + + b.HasIndex("TargetUserId") + .HasDatabaseName("IX_MentorAbuseReports_TargetUserId"); + + b.ToTable("MentorAbuseReports", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceApproval", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DecisionReason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceSummary") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("RawLearnerDurationSeconds") + .HasColumnType("integer"); + + b.Property("RawMentorDurationSeconds") + .HasColumnType("integer"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("ReviewedByAdminId"); + + b.ToTable("MentorAttendanceApprovals", t => + { + t.HasCheckConstraint("CK_MentorAttendanceApproval_Minutes", "\"ApprovedEligibleMinutes\" IS NULL OR (\"ApprovedEligibleMinutes\" > 0 AND \"ApprovedEligibleMinutes\" <= 90)"); + + t.HasCheckConstraint("CK_MentorAttendanceApproval_RawDuration", "\"RawMentorDurationSeconds\" >= 0 AND \"RawLearnerDurationSeconds\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("FirstJoinedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastJoinedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastSeenAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LeftAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ReconnectionCount") + .HasColumnType("integer"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("RoomId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TotalDurationSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CourseSessionId"); + + b.HasIndex("RoomId") + .HasDatabaseName("IX_MentorAttendanceRecords_RoomId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorAttendanceRecords_Status"); + + b.HasIndex("UserId") + .HasDatabaseName("IX_MentorAttendanceRecords_UserId"); + + b.HasIndex("MentorBookingId", "UserId") + .IsUnique() + .HasDatabaseName("IX_MentorAttendanceRecords_Booking_User"); + + b.HasIndex("RoomId", "UserId") + .IsUnique() + .HasFilter("\"MentorBookingId\" IS NULL"); + + b.ToTable("MentorAttendanceRecords", null, t => + { + t.HasCheckConstraint("CK_MentorAttendanceRecord_Duration", "\"TotalDurationSeconds\" >= 0"); + + t.HasCheckConstraint("CK_MentorAttendanceRecord_Reconnection", "\"ReconnectionCount\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminName") + .HasColumnType("text"); + + b.Property("AttendanceTrackingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("BookedCount") + .HasColumnType("integer"); + + b.Property("CancelReason") + .HasColumnType("text"); + + b.Property("CancelRejectedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CancelRejectionReason") + .HasColumnType("text"); + + b.Property("CancelRequestedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ChangeRequestReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ChangeRequestedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ChangeResolution") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EndTime") + .HasColumnType("timestamp without time zone"); + + b.Property("GenerationKey") + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("IsApproved") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("MaxLearners") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorScheduleRuleId") + .HasColumnType("bigint"); + + b.Property("MentorWeeklyAvailabilityId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectionReason") + .HasColumnType("text"); + + b.Property("RestMinutesSnapshot") + .HasColumnType("integer"); + + b.Property("RoomId") + .HasColumnType("uuid"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SessionMinutesSnapshot") + .HasColumnType("integer"); + + b.Property("StartTime") + .HasColumnType("timestamp without time zone"); + + b.Property("TeachingProposalId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("GenerationKey") + .IsUnique() + .HasFilter("\"GenerationKey\" IS NOT NULL"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorScheduleRuleId"); + + b.HasIndex("MentorWeeklyAvailabilityId"); + + b.HasIndex("RoomId") + .IsUnique(); + + b.HasIndex("TeachingProposalId") + .HasFilter("\"TeachingProposalId\" IS NOT NULL"); + + b.HasIndex("MentorId", "StartTime", "EndTime"); + + b.ToTable("MentorAvailabilities", t => + { + t.HasCheckConstraint("CK_MentorAvailability_BookedCount", "\"BookedCount\" >= 0 AND \"BookedCount\" <= \"MaxLearners\""); + + t.HasCheckConstraint("CK_MentorAvailability_GeneratedSlot", "(\"GenerationKey\" IS NULL AND \"PolicyVersion\" IS NULL AND \"MentorScheduleRuleId\" IS NULL AND \"LocalBusinessDate\" IS NULL AND \"GroupPolicyId\" IS NULL AND \"SessionMinutesSnapshot\" IS NULL AND \"RestMinutesSnapshot\" IS NULL) OR (\"GenerationKey\" IS NOT NULL AND \"PolicyVersion\" IS NOT NULL AND \"PolicyVersion\" > 0 AND (\"MentorScheduleRuleId\" IS NOT NULL OR \"TeachingProposalId\" IS NOT NULL) AND \"LocalBusinessDate\" IS NOT NULL AND ((\"GroupPolicyId\" IS NULL AND \"SessionMinutesSnapshot\" IS NULL AND \"RestMinutesSnapshot\" IS NULL AND \"MaxLearners\" = 1 AND \"EndTime\" = \"StartTime\" + INTERVAL '90 minutes') OR (\"GroupPolicyId\" IS NOT NULL AND \"SessionMinutesSnapshot\" > 0 AND \"RestMinutesSnapshot\" >= 0 AND \"MaxLearners\" BETWEEN 1 AND 50 AND \"EndTime\" = \"StartTime\" + \"SessionMinutesSnapshot\" * INTERVAL '1 minute')))"); + }); + + b.HasData( + new + { + Id = 990001, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 1, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 2, 10, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900002, + RoomId = new Guid("a1000000-0000-0000-0000-000000990001"), + StartTime = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990002, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 3, 14, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900002, + RoomId = new Guid("a1000000-0000-0000-0000-000000990002"), + StartTime = new DateTime(2026, 10, 3, 13, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990003, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 4, 10, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900003, + RoomId = new Guid("a1000000-0000-0000-0000-000000990003"), + StartTime = new DateTime(2026, 10, 4, 9, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }, + new + { + Id = 990004, + AdminName = "Seed Demo", + AttendanceTrackingEnabled = true, + BookedCount = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndTime = new DateTime(2026, 10, 5, 14, 0, 0, 0, DateTimeKind.Unspecified), + IsApproved = true, + IsDeleted = false, + MaxLearners = 4, + MentorId = 900003, + RoomId = new Guid("a1000000-0000-0000-0000-000000990004"), + StartTime = new DateTime(2026, 10, 5, 13, 0, 0, 0, DateTimeKind.Unspecified), + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBankAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountHolderName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("AccountNumberHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AccountVersion") + .HasColumnType("integer"); + + b.Property("BankCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("BankName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedAccountNumber") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsCurrent") + .HasColumnType("boolean"); + + b.Property("MaskedAccountNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("VerificationNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VerificationStatus") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedByAdminId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorUserId") + .IsUnique() + .HasDatabaseName("IX_MentorBankAccounts_MentorUserId_Current") + .HasFilter("\"IsCurrent\" = TRUE"); + + b.HasIndex("VerifiedByAdminId"); + + b.HasIndex("MentorUserId", "AccountVersion") + .IsUnique(); + + b.ToTable("MentorBankAccounts", t => + { + t.HasCheckConstraint("CK_MentorBankAccount_Version", "\"AccountVersion\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttendedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CancellationReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CancelledByRole") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CancelledByUserId") + .HasColumnType("integer"); + + b.Property("CompensationCurrency") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("CompensationFormulaVersion") + .HasColumnType("integer"); + + b.Property("CompensationLevelId") + .HasColumnType("integer"); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditGrantId") + .HasColumnType("bigint"); + + b.Property("ExceptionApproved") + .HasColumnType("boolean"); + + b.Property("ExceptionReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExceptionRequested") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MeetingLink") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeFeedback") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PracticeFeedbackAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeScore") + .HasColumnType("integer"); + + b.Property("Question") + .HasColumnType("text"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ScheduledCompensationAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserSubscriptionId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CompensationLevelId"); + + b.HasIndex("CreditGrantId"); + + b.HasIndex("MentorAvailabilityId", "LearnerId") + .IsUnique() + .HasFilter("\"MentorAvailabilityId\" IS NOT NULL AND \"LearnerId\" IS NOT NULL AND NOT \"IsDeleted\" AND \"Status\" <> 'Cancelled'"); + + b.HasIndex("MentorAvailabilityId", "UserSubscriptionId") + .IsUnique() + .HasFilter("NOT \"IsDeleted\" AND \"Status\" <> 'Cancelled'"); + + b.HasIndex("UserSubscriptionId", "Status"); + + b.ToTable("MentorBookings"); + + b.HasData( + new + { + Id = 990001, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Meeting demo để kiểm thử phòng họp trên frontend.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990001, + Version = 0u + }, + new + { + Id = 990002, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Em muốn nhờ Mentor giải đáp phần ngữ pháp N3 bài 5.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990002, + Version = 0u + }, + new + { + Id = 990003, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Hỏi về cách phân biệt giữa ~てくる và ~ていく.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990003, + Version = 0u + }, + new + { + Id = 990004, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + ExceptionRequested = false, + IsDeleted = false, + MeetingLink = "http://localhost:5173/mentor-meeting/a1000000-0000-0000-0000-000000990001", + MentorAvailabilityId = 990001, + Question = "Tư vấn phương pháp luyện nghe JLPT N3 hiệu quả.", + ScheduledAt = new DateTime(2026, 10, 2, 9, 0, 0, 0, DateTimeKind.Unspecified), + Status = "Assigned", + UserSubscriptionId = 990004, + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingDayGuard", b => + { + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("ActiveBookingCount") + .HasColumnType("integer"); + + b.HasKey("MentorId", "LocalBusinessDate"); + + b.ToTable("MentorBookingDayGuards", null, t => + { + t.HasCheckConstraint("CK_MentorBookingDayGuard_Count", "\"ActiveBookingCount\" >= 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingIntent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IntentKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("RequestHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId"); + + b.HasIndex("LearnerId", "IntentKey") + .IsUnique(); + + b.ToTable("MentorBookingIntents", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingReservation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EndUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LocalBusinessDate") + .HasColumnType("date"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("ReleasedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RestProtectedUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("StartUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MentorAvailabilityId") + .HasFilter("\"ReleasedAtUtc\" IS NULL"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("MentorAvailabilityId", "MentorId"); + + b.HasIndex("MentorId", "LocalBusinessDate", "ReleasedAtUtc"); + + b.ToTable("MentorBookingReservations", null, t => + { + t.HasCheckConstraint("CK_MentorBookingReservation_Interval", "\"EndUtc\" > \"StartUtc\""); + + t.HasCheckConstraint("CK_MentorBookingReservation_PolicyVersion", "\"PolicyVersion\" > 0"); + + t.HasCheckConstraint("CK_MentorBookingReservation_Rest", "\"RestProtectedUntilUtc\" >= \"EndUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingTerms", b => + { + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ConfirmedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("ScheduledEndUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduledStartUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MentorBookingId"); + + b.HasIndex("MentorAvailabilityId"); + + b.ToTable("MentorBookingTerms", null, t => + { + t.HasCheckConstraint("CK_MentorBookingTerms_Interval", "\"ScheduledEndUtc\" > \"ScheduledStartUtc\""); + + t.HasCheckConstraint("CK_MentorBookingTerms_PolicyVersion", "\"PolicyVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCalendarConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("LastSyncedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("ProtectedRefreshToken") + .HasColumnType("text"); + + b.Property("StateExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StateHash") + .HasColumnType("text"); + + b.Property("SyncedEventsJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("MentorId") + .IsUnique(); + + b.HasIndex("StateHash") + .IsUnique(); + + b.ToTable("MentorCalendarConnections", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorChatMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ReadAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderUserId") + .HasColumnType("integer"); + + b.Property("SentAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("SenderUserId"); + + b.HasIndex("MentorBookingId", "Id"); + + b.HasIndex("MentorBookingId", "ReadAt", "SenderUserId"); + + b.ToTable("MentorChatMessages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreditGrantId") + .HasColumnType("bigint"); + + b.Property("EntryType") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId"); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("CreditGrantId", "EntryType"); + + b.HasIndex("MentorBookingId", "EntryType"); + + b.ToTable("MentorCreditEntries", null, t => + { + t.HasCheckConstraint("CK_MentorCreditEntry_Amount", "\"Amount\" <> 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AvailableQuantity") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("InitialQuantity") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("UserSubscriptionId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserSubscriptionId") + .IsUnique(); + + b.HasIndex("LearnerId", "ExpiresAtUtc"); + + b.HasIndex("LearnerId", "CertificateLevelId", "ExpiresAtUtc"); + + b.ToTable("MentorCreditGrants", null, t => + { + t.HasCheckConstraint("CK_MentorCreditGrant_PolicyVersion", "\"PolicyVersion\" > 0"); + + t.HasCheckConstraint("CK_MentorCreditGrant_Quantity", "\"InitialQuantity\" > 0 AND \"AvailableQuantity\" >= 0 AND \"AvailableQuantity\" <= \"InitialQuantity\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminDecision") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("AdminNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Category") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CreditRefunded") + .HasColumnType("boolean"); + + b.Property("EvidenceUrls") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("IsRefundApproved") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRespondedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorResponse") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RefundOperationKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ResolvedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ResolvedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId") + .HasDatabaseName("IX_MentorDisputes_LearnerId"); + + b.HasIndex("MentorBookingId") + .HasDatabaseName("IX_MentorDisputes_MentorBookingId"); + + b.HasIndex("MentorId") + .HasDatabaseName("IX_MentorDisputes_MentorId"); + + b.HasIndex("ResolvedByAdminId"); + + b.HasIndex("Status") + .HasDatabaseName("IX_MentorDisputes_Status"); + + b.ToTable("MentorDisputes", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDisputeHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ActorId") + .HasColumnType("integer"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("DisputeId") + .HasColumnType("integer"); + + b.Property("NewStatus") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("PreviousStatus") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DisputeId") + .HasDatabaseName("IX_MentorDisputeHistories_DisputeId"); + + b.ToTable("MentorDisputeHistories", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorEarningEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("AttendanceApprovalId") + .HasColumnType("bigint"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("FormulaVersion") + .HasColumnType("integer"); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("GrossAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("JlptLevelCode") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("AttendanceApprovalId") + .IsUnique(); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.HasIndex("MentorUserId", "Status"); + + b.ToTable("MentorEarningEntries", t => + { + t.HasCheckConstraint("CK_MentorEarningEntry_Positive", "\"FrozenHourlyRate\" > 0 AND \"FrozenLevelCoefficient\" > 0 AND \"ApprovedEligibleMinutes\" > 0 AND \"ApprovedEligibleMinutes\" <= 90 AND \"GrossAmount\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorGroupPolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CancellationLeadHours") + .HasColumnType("integer"); + + b.Property("CheckoutHoldMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("DeletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedByAdminId") + .HasColumnType("integer"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("HomeworkDeadlineDays") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsArchivedRevision") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KpiReportingPeriodDays") + .HasColumnType("integer"); + + b.Property("LastAppliedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedByAdminId") + .HasColumnType("integer"); + + b.Property("LearnerTransferEnabled") + .HasColumnType("boolean"); + + b.Property("MaxLearners") + .HasColumnType("integer"); + + b.Property("MentorReplacementEnabled") + .HasColumnType("boolean"); + + b.Property("MentorReplacementLeadHours") + .HasColumnType("integer"); + + b.Property("MinimumPreparationDays") + .HasColumnType("integer"); + + b.Property("MinimumPublishedEnrollmentDays") + .HasColumnType("integer"); + + b.Property("PlacementAttemptLimit") + .HasColumnType("integer"); + + b.Property("RemediationAttendanceThresholdPercent") + .ValueGeneratedOnAdd() + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasDefaultValue(90m); + + b.Property("RemediationCompletionThresholdPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("RemediationThresholdComparison") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("RequireAdminRemediationReview") + .HasColumnType("boolean"); + + b.Property("RequireOfficialExamEvidence") + .HasColumnType("boolean"); + + b.Property("ReschedulingLeadHours") + .HasColumnType("integer"); + + b.Property("RestMinutes") + .HasColumnType("integer"); + + b.Property("RetakeSupportEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("TransferAllowedAfterSourceStart") + .HasColumnType("boolean"); + + b.Property("TuitionPerSessionN2") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN3") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN4") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionN5") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedByAdminId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("DeletedByAdminId"); + + b.HasIndex("EffectiveFromUtc"); + + b.HasIndex("IsActive") + .IsUnique() + .HasDatabaseName("IX_MentorGroupPolicies_SingleActive") + .HasFilter("\"IsActive\" = TRUE"); + + b.HasIndex("LastAppliedByAdminId"); + + b.HasIndex("UpdatedByAdminId"); + + b.HasIndex("Version") + .IsUnique() + .HasDatabaseName("IX_MentorGroupPolicies_LiveVersion") + .HasFilter("\"IsArchivedRevision\" = FALSE"); + + b.ToTable("MentorGroupPolicies", null, t => + { + t.HasCheckConstraint("CK_MentorGroupPolicy_Capacity", "\"MaxLearners\" BETWEEN 1 AND 50"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_CheckoutHold", "\"CheckoutHoldMinutes\" BETWEEN 1 AND 60"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Comparison", "\"RemediationThresholdComparison\" IN ('>', '>=')"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_EnrollmentDays", "\"MinimumPublishedEnrollmentDays\" BETWEEN 1 AND 180"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Evidence", "\"RequireOfficialExamEvidence\" AND \"RequireAdminRemediationReview\""); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Positive", "\"Version\" > 0 AND \"SessionMinutes\" > 0 AND \"RestMinutes\" >= 0 AND \"MinimumPreparationDays\" >= 1 AND \"CancellationLeadHours\" >= 0 AND \"ReschedulingLeadHours\" >= 0 AND \"HomeworkDeadlineDays\" > 0 AND \"PlacementAttemptLimit\" > 0 AND \"KpiReportingPeriodDays\" > 0"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Remediation", "\"RemediationCompletionThresholdPercent\" > 0 AND \"RemediationCompletionThresholdPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_RemediationAttendance", "\"RemediationAttendanceThresholdPercent\" > 0 AND \"RemediationAttendanceThresholdPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_ReplacementLead", "\"MentorReplacementLeadHours\" BETWEEN 0 AND 720"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_State", "\"Revision\" > 0 AND NOT (\"IsActive\" AND (\"IsArchivedRevision\" OR \"IsDeleted\"))"); + + t.HasCheckConstraint("CK_MentorGroupPolicy_TransferAfterStart", "\"LearnerTransferEnabled\" OR NOT \"TransferAllowedAfterSourceStart\""); + + t.HasCheckConstraint("CK_MentorGroupPolicy_Tuition", "\"TuitionPerSessionN5\" >= 0 AND \"TuitionPerSessionN4\" >= 0 AND \"TuitionPerSessionN3\" >= 0 AND \"TuitionPerSessionN2\" >= 0"); + }); + + b.HasData( + new + { + Id = 1, + CancellationLeadHours = 24, + CheckoutHoldMinutes = 10, + CreatedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + EffectiveFromUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + HomeworkDeadlineDays = 7, + IsActive = true, + IsArchivedRevision = false, + IsDeleted = false, + KpiReportingPeriodDays = 30, + LastAppliedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + LearnerTransferEnabled = true, + MaxLearners = 4, + MentorReplacementEnabled = true, + MentorReplacementLeadHours = 24, + MinimumPreparationDays = 1, + MinimumPublishedEnrollmentDays = 7, + PlacementAttemptLimit = 2, + RemediationAttendanceThresholdPercent = 90m, + RemediationCompletionThresholdPercent = 90m, + RemediationThresholdComparison = ">", + RequireAdminRemediationReview = true, + RequireOfficialExamEvidence = true, + ReschedulingLeadHours = 24, + RestMinutes = 15, + RetakeSupportEnabled = true, + Revision = 1, + SessionMinutes = 90, + TransferAllowedAfterSourceStart = false, + TuitionPerSessionN2 = 110000m, + TuitionPerSessionN3 = 90000m, + TuitionPerSessionN4 = 75000m, + TuitionPerSessionN5 = 60000m, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorHourlyRate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountPerHour") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ConfiguredByAdminId"); + + b.HasIndex("MentorUserId", "EffectiveFromUtc") + .IsUnique(); + + b.ToTable("MentorHourlyRates", t => + { + t.HasCheckConstraint("CK_MentorHourlyRate_Positive", "\"AmountPerHour\" > 0"); + + t.HasCheckConstraint("CK_MentorHourlyRate_Range", "\"EffectiveUntilUtc\" IS NULL OR \"EffectiveUntilUtc\" > \"EffectiveFromUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorKpiPolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AverageRatingTarget") + .HasPrecision(3, 2) + .HasColumnType("numeric(3,2)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("DeletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedByAdminId") + .HasColumnType("integer"); + + b.Property("EffectiveFromMonth") + .HasColumnType("date"); + + b.Property("GradingCompletionTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("HomeworkMinimumCount") + .HasColumnType("integer"); + + b.Property("HomeworkPerSessionCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MinimumPresencePercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OnTimeResponseTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("PositiveReviewTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("ResponseSlaHours") + .HasColumnType("integer"); + + b.Property("TeachingCompletionTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("EffectiveFromMonth") + .IsUnique() + .HasFilter("\"IsDeleted\" = FALSE"); + + b.HasIndex("Version") + .IsUnique(); + + b.ToTable("MentorKpiPolicies", null, t => + { + t.HasCheckConstraint("CK_MentorKpiPolicy_Homework", "\"HomeworkMinimumCount\" >= 0 AND \"HomeworkPerSessionCount\" > 0"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Month", "EXTRACT(DAY FROM \"EffectiveFromMonth\") = 1"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Percents", "\"MinimumPresencePercent\" > 0 AND \"MinimumPresencePercent\" <= 100 AND \"TeachingCompletionTargetPercent\" > 0 AND \"TeachingCompletionTargetPercent\" <= 100 AND \"GradingCompletionTargetPercent\" > 0 AND \"GradingCompletionTargetPercent\" <= 100 AND \"OnTimeResponseTargetPercent\" > 0 AND \"OnTimeResponseTargetPercent\" <= 100 AND \"PositiveReviewTargetPercent\" > 0 AND \"PositiveReviewTargetPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Rating", "\"AverageRatingTarget\" >= 1 AND \"AverageRatingTarget\" <= 5"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Sla", "\"ResponseSlaHours\" > 0"); + }); + + b.HasData( + new + { + Id = 1, + AverageRatingTarget = 4m, + CreatedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + EffectiveFromMonth = new DateOnly(2026, 1, 1), + GradingCompletionTargetPercent = 90m, + HomeworkMinimumCount = 1, + HomeworkPerSessionCount = 2, + IsDeleted = false, + MinimumPresencePercent = 80m, + Note = "Phiên bản khởi tạo", + OnTimeResponseTargetPercent = 90m, + PositiveReviewTargetPercent = 80m, + ResponseSlaHours = 24, + TeachingCompletionTargetPercent = 90m, + Version = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorOutboxEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AggregateId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("AggregateType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("AvailableAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeliveredAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EventKey") + .IsRequired() + .HasMaxLength(160) + .HasColumnType("character varying(160)"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("character varying(80)"); + + b.Property("EventVersion") + .HasColumnType("integer"); + + b.Property("PayloadJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("EventKey") + .IsUnique(); + + b.HasIndex("DeliveredAtUtc", "AvailableAtUtc", "CreatedAtUtc"); + + b.ToTable("MentorOutboxEvents", null, t => + { + t.HasCheckConstraint("CK_MentorOutbox_Attempts", "\"Attempts\" >= 0"); + + t.HasCheckConstraint("CK_MentorOutbox_EventVersion", "\"EventVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("AttemptNumber") + .HasColumnType("integer"); + + b.Property("BatchId") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ConfirmedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("ErrorCode") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ErrorMessage") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("EvidenceStorageKey") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ExecutionMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("IdempotencyKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("InitiatedByAdminId") + .HasColumnType("integer"); + + b.Property("InternalStatus") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("LockedBankAccountId") + .HasColumnType("bigint"); + + b.Property("PayoutObligationId") + .HasColumnType("bigint"); + + b.Property("ProviderPayoutId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProviderStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("TransferReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ConfirmedByAdminId"); + + b.HasIndex("IdempotencyKey") + .IsUnique(); + + b.HasIndex("InitiatedByAdminId"); + + b.HasIndex("LockedBankAccountId"); + + b.HasIndex("PayoutObligationId") + .IsUnique() + .HasDatabaseName("IX_MentorPayoutAttempts_OneSucceededPerObligation") + .HasFilter("\"InternalStatus\" = 'Succeeded'"); + + b.HasIndex("TransferReference") + .IsUnique() + .HasDatabaseName("IX_MentorPayoutAttempts_SucceededTransferReference") + .HasFilter("\"TransferReference\" IS NOT NULL AND \"InternalStatus\" = 'Succeeded'"); + + b.HasIndex("PayoutObligationId", "AttemptNumber") + .IsUnique(); + + b.ToTable("MentorPayoutAttempts", t => + { + t.HasCheckConstraint("CK_MentorPayoutAttempt_ManualEvidence", "(\"ExecutionMethod\" <> 'ManualBankTransfer' OR \"InternalStatus\" <> 'Succeeded') OR (\"TransferReference\" IS NOT NULL AND \"EvidenceStorageKey\" IS NOT NULL)"); + + t.HasCheckConstraint("CK_MentorPayoutAttempt_Positive", "\"Amount\" > 0 AND \"AttemptNumber\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActiveAttemptId") + .HasColumnType("bigint"); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("LockedBankAccountId") + .HasColumnType("bigint"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("OrganizationPayoutAccountId") + .HasColumnType("bigint"); + + b.Property("PayableAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("SelectedMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SettledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SettledAttemptId") + .HasColumnType("bigint"); + + b.Property("SettledReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("LockedBankAccountId"); + + b.HasIndex("MentorUserId"); + + b.HasIndex("OrganizationPayoutAccountId"); + + b.HasIndex("PayrollPeriodId") + .IsUnique(); + + b.ToTable("MentorPayoutObligations", t => + { + t.HasCheckConstraint("CK_MentorPayoutObligation_Positive", "\"PayableAmount\" > 0"); + + t.HasCheckConstraint("CK_MentorPayoutObligation_Settlement", "(\"Status\" <> 'Paid') OR (\"SettledAttemptId\" IS NOT NULL AND \"SettledReference\" IS NOT NULL AND \"SettledAtUtc\" IS NOT NULL)"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollAdjustment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OperationKey") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RelatedBookingId") + .HasColumnType("integer"); + + b.Property("RelatedEarningEntryId") + .HasColumnType("bigint"); + + b.Property("SignedAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("OperationKey") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.ToTable("MentorPayrollAdjustments", t => + { + t.HasCheckConstraint("CK_MentorPayrollAdjustment_NonZero", "\"SignedAmount\" <> 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollLine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovedEligibleMinutes") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EarningEntryId") + .HasColumnType("bigint"); + + b.Property("FrozenHourlyRate") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("FrozenLevelCoefficient") + .HasPrecision(10, 4) + .HasColumnType("numeric(10,4)"); + + b.Property("LineAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("PayrollPeriodId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("EarningEntryId") + .IsUnique(); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("PayrollPeriodId"); + + b.ToTable("MentorPayrollLines", t => + { + t.HasCheckConstraint("CK_MentorPayrollLine_Positive", "\"LineAmount\" > 0 AND \"ApprovedEligibleMinutes\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApprovalNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ApprovedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ApprovedByAdminId") + .HasColumnType("integer"); + + b.Property("ClosedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("GrossPayableAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("Month") + .HasColumnType("integer"); + + b.Property("PreparedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PreparedByAdminId") + .HasColumnType("integer"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SupplementalReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("TotalAdjustmentsAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("TotalEarningsAmount") + .HasPrecision(18, 2) + .HasColumnType("numeric(18,2)"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.Property("Year") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByAdminId"); + + b.HasIndex("PreparedByAdminId"); + + b.HasIndex("MentorUserId", "Year", "Month", "SequenceNumber", "Currency") + .IsUnique(); + + b.ToTable("MentorPayrollPeriods", t => + { + t.HasCheckConstraint("CK_MentorPayrollPeriod_Payable", "\"TotalEarningsAmount\" >= 0 AND \"GrossPayableAmount\" >= 0"); + + t.HasCheckConstraint("CK_MentorPayrollPeriod_Period", "\"Year\" >= 2020 AND \"Year\" <= 2100 AND \"Month\" >= 1 AND \"Month\" <= 12 AND \"SequenceNumber\" >= 1"); + + t.HasCheckConstraint("CK_MentorPayrollPeriod_Supplemental", "\"SequenceNumber\" = 1 OR (\"SupplementalReason\" IS NOT NULL AND length(trim(\"SupplementalReason\")) > 0)"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorProfile", b => + { + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Bio") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Expertise") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IntroductionVideoUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("RejectionReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewNotes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("VerificationDocumentUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VerificationStatus") + .IsConcurrencyToken() + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Workplace") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("YearsOfExperience") + .HasColumnType("integer"); + + b.HasKey("MentorId"); + + b.ToTable("MentorProfiles", (string)null); + + b.HasData( + new + { + MentorId = 900002, + Bio = "Chuyên gia tiếng Nhật với 8 năm kinh nghiệm giảng dạy JLPT N1, N2 và tiếng Nhật doanh nghiệp.", + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + Expertise = "Luyện thi JLPT N1-N2, Tiếng Nhật thương mại, Phỏng vấn xin việc", + IsDeleted = false, + JlptLevel = "N1", + ReviewedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + ReviewedByAdminName = "Admin System", + SubmittedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + VerificationStatus = "Approved", + Workplace = "Riki Nihongo Academy", + YearsOfExperience = 8 + }, + new + { + MentorId = 900003, + Bio = "Giảng viên tiếng Nhật bản xứ, chuyên sâu về phát âm và giao tiếp Kaiwa thực tế.", + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + Expertise = "Giao tiếp Kaiwa tự nhiên, Luyện phát âm chuẩn Tokyo, JLPT N3-N2", + IsDeleted = false, + JlptLevel = "N1", + ReviewedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + ReviewedByAdminName = "Admin System", + SubmittedAt = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + VerificationStatus = "Approved", + Workplace = "Riki Nihongo Academy", + YearsOfExperience = 5 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("IsPublic") + .HasColumnType("boolean"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorRepliedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorReply") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModerationStatus") + .HasColumnType("integer"); + + b.Property("Rating") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id"); + + b.HasIndex("LearnerId") + .HasDatabaseName("IX_MentorReviews_LearnerId"); + + b.HasIndex("MentorBookingId") + .IsUnique() + .HasDatabaseName("IX_MentorReviews_MentorBookingId"); + + b.HasIndex("MentorId", "IsPublic", "ModerationStatus") + .HasDatabaseName("IX_MentorReviews_Mentor_Public_Status"); + + b.ToTable("MentorReviews", null, t => + { + t.HasCheckConstraint("CK_MentorReview_Rating_Range", "\"Rating\" >= 1 AND \"Rating\" <= 5"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AutoPublish") + .HasColumnType("boolean"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("GeneratedThrough") + .HasColumnType("date"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyVersion") + .HasColumnType("integer"); + + b.Property("TimeZoneId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("MentorId", "PolicyVersion") + .IsUnique(); + + b.ToTable("MentorSchedules", null, t => + { + t.HasCheckConstraint("CK_MentorSchedule_PolicyVersion", "\"PolicyVersion\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorScheduleRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DaypartCode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("LocalEnd") + .HasColumnType("time without time zone"); + + b.Property("LocalStart") + .HasColumnType("time without time zone"); + + b.Property("ScheduleId") + .HasColumnType("bigint"); + + b.Property("Weekday") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleId", "Weekday", "DaypartCode", "EffectiveFrom") + .IsUnique(); + + b.ToTable("MentorScheduleRules", null, t => + { + t.HasCheckConstraint("CK_MentorScheduleRule_Daypart", "\"DaypartCode\" IN ('Morning', 'Noon', 'Afternoon', 'Evening')"); + + t.HasCheckConstraint("CK_MentorScheduleRule_Time", "\"LocalEnd\" > \"LocalStart\""); + + t.HasCheckConstraint("CK_MentorScheduleRule_Weekday", "\"Weekday\" BETWEEN 0 AND 6"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CourseDurationWeeks") + .HasColumnType("integer"); + + b.Property("CourseObjective") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("CoursePlanId") + .HasColumnType("integer"); + + b.Property("CourseTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpectedStartDate") + .HasColumnType("date"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("HiddenFromMentorAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHiddenFromMentorHistory") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastSavedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("OpenEnrollmentIdempotencyKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OpenedClassAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OptionalAttachmentsJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("OptionalNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("ProgramType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ReviewReason") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionDurationMinutes") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("SubmissionIdempotencyKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("WeeklySessionsJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CoursePlanId"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("ReviewedByAdminId"); + + b.HasIndex("MentorId", "OpenEnrollmentIdempotencyKey") + .IsUnique() + .HasDatabaseName("IX_MentorTeachingProposals_MentorId_OpenEnrollmentIdempotencyKey") + .HasFilter("\"OpenEnrollmentIdempotencyKey\" IS NOT NULL"); + + b.HasIndex("MentorId", "SubmissionIdempotencyKey") + .IsUnique() + .HasDatabaseName("IX_MentorTeachingProposals_MentorId_SubmissionIdempotencyKey") + .HasFilter("\"SubmissionIdempotencyKey\" IS NOT NULL"); + + b.HasIndex("Status", "SubmittedAtUtc"); + + b.HasIndex("MentorId", "Status", "UpdatedAtUtc"); + + b.ToTable("MentorTeachingProposals", null, t => + { + t.HasCheckConstraint("CK_MentorTeachingProposal_Duration", "\"CourseDurationWeeks\" BETWEEN 1 AND 104 AND \"SessionDurationMinutes\" BETWEEN 30 AND 240"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_ProgramType", "\"ProgramType\" IN ('StandardJlpt', 'IntensiveJlpt', 'ExamPrepJlpt', 'CustomJlpt')"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_Revision", "\"Revision\" > 0"); + + t.HasCheckConstraint("CK_MentorTeachingProposal_Status", "\"Status\" IN ('Draft', 'PendingReview', 'ChangesRequested', 'Approved', 'OpenedClass', 'Rejected', 'Withdrawn')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposalEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(48) + .HasColumnType("character varying(48)"); + + b.Property("ActorRole") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ActorUserId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("FromStatus") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("ProposalId") + .HasColumnType("integer"); + + b.Property("Reason") + .HasMaxLength(1500) + .HasColumnType("character varying(1500)"); + + b.Property("RevisionAfter") + .HasColumnType("integer"); + + b.Property("SnapshotJson") + .HasColumnType("jsonb"); + + b.Property("ToStatus") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("ProposalId", "CreatedAtUtc"); + + b.ToTable("MentorTeachingProposalEvents", null, t => + { + t.HasCheckConstraint("CK_MentorTeachingProposalEvent_RevisionAfter", "\"RevisionAfter\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingQualification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("MentorUserId") + .HasColumnType("integer"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("VerifiedByAdminId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("VerifiedByAdminId"); + + b.HasIndex("MentorUserId", "CertificateLevelId") + .IsUnique() + .HasFilter("\"IsActive\" = TRUE"); + + b.ToTable("MentorTeachingQualifications", t => + { + t.HasCheckConstraint("CK_MentorTeachingQualification_Revoked", "\"RevokedAtUtc\" IS NULL OR \"RevokedAtUtc\" >= \"VerifiedAtUtc\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTimesheetAdjustment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminId") + .HasColumnType("integer"); + + b.Property("CohortSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Evidence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("NewConfirmedMinutes") + .HasColumnType("integer"); + + b.Property("NewStatus") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PreviousConfirmedMinutes") + .HasColumnType("integer"); + + b.Property("PreviousStatus") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.HasKey("Id"); + + b.HasIndex("MentorId"); + + b.HasIndex("CohortSessionId", "CreatedAtUtc"); + + b.ToTable("MentorTimesheetAdjustments", null, t => + { + t.HasCheckConstraint("CK_MentorTimesheetAdjustment_Minutes", "\"NewConfirmedMinutes\" >= 0 AND \"PreviousConfirmedMinutes\" >= 0"); + + t.HasCheckConstraint("CK_MentorTimesheetAdjustment_Status", "\"NewStatus\" IN ('Taught', 'Absent')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Date") + .HasColumnType("date"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Period") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("MentorId", "Date", "Period") + .IsUnique() + .HasFilter("NOT \"IsDeleted\""); + + b.ToTable("MentorWeeklyAvailabilities", t => + { + t.HasCheckConstraint("CK_MentorWeeklyAvailability_Period", "\"Period\" IN ('Morning', 'Afternoon', 'Evening')"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("AnswerKeyJson") + .HasColumnType("jsonb"); + + b.Property("AudioTranscript") + .HasColumnType("text"); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("ContentFingerprint") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Difficulty") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("GroupSortOrder") + .HasColumnType("integer"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("InteractionDataJson") + .HasColumnType("jsonb"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("MockTestSectionId") + .HasColumnType("integer") + .HasColumnName("PracticeTestSectionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionsJson") + .HasColumnType("jsonb"); + + b.Property("ParentQuestionId") + .HasColumnType("integer"); + + b.Property("PassageId") + .HasColumnType("integer"); + + b.Property("PlaybackPolicyJson") + .HasColumnType("jsonb"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("QuestionGroupTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("QuestionIdentity") + .HasColumnType("uuid"); + + b.Property("QuestionText") + .IsRequired() + .HasColumnType("text"); + + b.Property("QuestionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("SingleChoice"); + + b.Property("QuestionVersion") + .HasColumnType("integer"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SkillMetadataJson") + .HasColumnType("jsonb"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("SourceQuestionId") + .HasColumnType("integer"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("Manual"); + + b.Property("TagsJson") + .HasColumnType("jsonb"); + + b.Property("TemplateKind") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Topic") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.HasKey("Id"); + + b.HasIndex("ContentFingerprint"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("PassageId"); + + b.HasIndex("QuestionIdentity"); + + b.HasIndex("SourceQuestionId"); + + b.HasIndex("MockTestSectionId", "IsArchivedVersion"); + + b.HasIndex("CertificateLevelId", "LanguageSkillId", "PublishStatus", "IsArchivedVersion"); + + b.ToTable("MockQuestions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestionOption", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockQuestionId") + .HasColumnType("integer") + .HasColumnName("PracticeQuestionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionText") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockQuestionId"); + + b.ToTable("MockQuestionOptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiProvenanceJson") + .HasColumnType("jsonb"); + + b.Property("BlueprintPolicyJson") + .HasColumnType("jsonb"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ExamKind") + .HasColumnType("integer"); + + b.Property("FocusSkillId") + .HasColumnType("integer"); + + b.Property("IncludedSkillsJson") + .HasColumnType("jsonb"); + + b.Property("IsArchivedVersion") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsManagedWorkflow") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ParentExamId") + .HasColumnType("integer"); + + b.Property("PublishStatus") + .HasColumnType("integer"); + + b.Property("PublishedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("RightsStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SourceReference") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("TagsJson") + .HasColumnType("jsonb"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserAccountId"); + + b.ToTable("MockTests"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAnswer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiExplanationGeneratedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AiExplanationInputJson") + .HasColumnType("jsonb"); + + b.Property("AiExplanationJson") + .HasColumnType("jsonb"); + + b.Property("AiExplanationVersion") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockQuestionId") + .HasColumnType("integer") + .HasColumnName("PracticeQuestionId"); + + b.Property("MockTestAttemptId") + .HasColumnType("integer") + .HasColumnName("PracticeTestAttemptId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ResponseJson") + .HasColumnType("jsonb"); + + b.Property("SelectedOptionId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockQuestionId"); + + b.HasIndex("SelectedOptionId"); + + b.HasIndex("MockTestAttemptId", "MockQuestionId") + .IsUnique(); + + b.ToTable("MockTestAnswers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AttemptKind") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsPlacementAssessment") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("QuestionSnapshotJson") + .HasColumnType("text"); + + b.Property("StartedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalScore") + .HasColumnType("double precision"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StartedAt"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "AttemptKind") + .IsUnique() + .HasFilter("\"AttemptKind\" = 1 AND \"IsCompleted\" = false AND \"IsDeleted\" = false"); + + b.ToTable("MockTestAttempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateSectionId") + .HasColumnType("integer") + .HasColumnName("CertificationSectionId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DurationMinutes") + .HasColumnType("integer"); + + b.Property("Instructions") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer") + .HasColumnName("SkillId"); + + b.Property("MockTestId") + .HasColumnType("integer") + .HasColumnName("MockTestId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SectionPolicyJson") + .HasColumnType("jsonb"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateSectionId"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("MockTestId", "CertificateSectionId"); + + b.ToTable("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSectionResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CorrectCount") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MockTestAttemptId") + .HasColumnType("integer") + .HasColumnName("MockTestAttemptId"); + + b.Property("MockTestSectionId") + .HasColumnType("integer") + .HasColumnName("MockTestSectionId"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ScorePercent") + .HasColumnType("double precision"); + + b.Property("TotalCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MockTestSectionId"); + + b.HasIndex("MockTestAttemptId", "MockTestSectionId") + .IsUnique(); + + b.ToTable("MockTestSectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Note", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AnsweredAt") + .HasColumnType("timestamp without time zone"); + + b.Property("AuthorRole") + .IsRequired() + .HasColumnType("text"); + + b.Property("Content") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorBookingId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("MentorBookingId") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("Notes"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("NormalizedName") + .IsRequired() + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_NotebookFolders_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("UserId", "NormalizedName") + .IsUnique() + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("UserId", "IsDeleted", "SortOrder"); + + b.ToTable("NotebookFolders", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChecklistCompletedCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ChecklistTotalCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ContentFormatVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("ContentJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'{\"type\":\"doc\",\"version\":1,\"blocks\":[]}'::jsonb"); + + b.Property("ContentPlainText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue(""); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("FavoritedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDefault") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("LastAutosavedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerNoteId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourcePath") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceTitle") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasDatabaseName("IX_NotebookPages_UserId_IsDefault") + .HasFilter("\"IsDeleted\" = false AND \"IsDefault\" = true"); + + b.HasIndex("LearnerNoteId", "IsDeleted", "SortOrder"); + + b.HasIndex("UserId", "IsDeleted", "IsFavorite"); + + b.ToTable("NotebookPages", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DeliveredTokens") + .HasColumnType("text"); + + b.Property("IdempotencyKey") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("LinkUrl") + .HasColumnType("text"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.OrganizationPayoutAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccountHolderName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("BankCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("BankName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ChannelCode") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ConfiguredByAdminId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("MaskedAccountNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ProviderAccountReference") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProviderType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("VerifiedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelCode") + .IsUnique(); + + b.HasIndex("ConfiguredByAdminId"); + + b.ToTable("OrganizationPayoutAccounts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LanguageSkillId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PassingScorePercent") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(70.0); + + b.Property("Scope") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("LessonQuickCheck"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("TopicId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("LanguageSkillId"); + + b.HasIndex("TopicId"); + + b.HasIndex("LessonId", "LanguageSkillId"); + + b.HasIndex("Scope", "CertificateLevelId"); + + b.HasIndex("Scope", "TopicId"); + + b.ToTable("PracticeExercises"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("HomeworkAssignmentId") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.Property("ScorePercent") + .HasColumnType("double precision"); + + b.Property("StartedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeExerciseId"); + + b.HasIndex("HomeworkAssignmentId", "PracticeExerciseId") + .IsUnique(); + + b.HasIndex("UserId", "PracticeExerciseId", "StartedAt"); + + b.ToTable("PracticeExerciseAttempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Explanation") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PracticeExerciseId") + .HasColumnType("integer"); + + b.Property("QuestionText") + .IsRequired() + .HasColumnType("text"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeExerciseId"); + + b.ToTable("PracticeQuestions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestionOption", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("OptionText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("PracticeQuestionId") + .HasColumnType("integer"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PracticeQuestionId"); + + b.ToTable("PracticeQuestionOptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CertificateLevelId") + .HasColumnType("integer") + .HasColumnName("CertificationLevelId"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("TextContent") + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("UserId", "Type", "SubmittedAt"); + + b.ToTable("PracticeSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.RecommendedLearningPath", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BaseActivePathId") + .HasColumnType("integer"); + + b.Property("ConfirmedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("GeneratedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsViewed") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PreviewExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StartingCertificateLevelId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SuggestionJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Summary") + .HasColumnType("text"); + + b.Property("TargetCertificateLevelId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique() + .HasFilter("\"Status\" = 'Active'"); + + b.HasIndex("UserId", "GeneratedAt"); + + b.HasIndex("UserId", "Version") + .IsUnique(); + + b.ToTable("RecommendedLearningPaths"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcceptedReadingsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ArchivedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("AudioUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("BackText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)") + .HasDefaultValue(""); + + b.Property("CardType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("character varying(30)") + .HasDefaultValue("Vocabulary"); + + b.Property("ContextSnippet") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CorrectCount") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("EaseFactor") + .HasColumnType("double precision"); + + b.Property("ExampleMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FrontText") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasDefaultValue(""); + + b.Property("GrammarPatternId") + .HasColumnType("integer") + .HasColumnName("GrammarPointId"); + + b.Property("IncorrectCount") + .HasColumnType("integer"); + + b.Property("IntervalDays") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("KanjiId") + .HasColumnType("integer") + .HasColumnName("KanjiEntryId"); + + b.Property("Lapses") + .HasColumnType("integer"); + + b.Property("LastReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("LearnerNoteEntryId") + .HasColumnType("integer") + .HasColumnName("VocabularyNoteEntryId"); + + b.Property("LearningState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("New"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("MasteredAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Meaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Mode") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NextReviewDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NormalizedContentKey") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(300) + .HasColumnType("character varying(300)") + .HasDefaultValue(""); + + b.Property("PersonalNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Reading") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Repetitions") + .HasColumnType("integer"); + + b.Property("Revision") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SourceId") + .HasColumnType("integer"); + + b.Property("SourceLabel") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SourceLinksJson") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("SourceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasDefaultValue("Manual"); + + b.Property("SourceVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SrsCardTemplateId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Active"); + + b.Property("SuspendedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SynonymsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.Property("WritingCorrectStrokeCount") + .HasColumnType("integer"); + + b.Property("WritingPracticeMode") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("WritingScore") + .HasColumnType("integer"); + + b.Property("WritingScoreUpdatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("WritingTotalStrokeCount") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("LearnerNoteEntryId"); + + b.HasIndex("LessonId"); + + b.HasIndex("SrsCardTemplateId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("UserId", "NextReviewDate"); + + b.HasIndex("UserId", "GrammarPatternId", "Mode") + .IsUnique() + .HasFilter("\"GrammarPointId\" IS NOT NULL"); + + b.HasIndex("UserId", "KanjiId", "Mode") + .IsUnique() + .HasFilter("\"KanjiEntryId\" IS NOT NULL"); + + b.HasIndex("UserId", "NormalizedContentKey", "Mode") + .IsUnique() + .HasFilter("\"NormalizedContentKey\" <> '' AND \"IsDeleted\" = false"); + + b.HasIndex("UserId", "VocabularyId", "Mode") + .IsUnique() + .HasFilter("\"VocabularyId\" IS NOT NULL"); + + b.HasIndex("UserId", "Status", "LearningState", "NextReviewDate"); + + b.ToTable("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IdempotencyKey") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("IsCorrect") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NewEaseFactor") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(2.5); + + b.Property("NewIntervalDays") + .HasColumnType("integer"); + + b.Property("NewState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Learning"); + + b.Property("PreviousEaseFactor") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(2.5); + + b.Property("PreviousIntervalDays") + .HasColumnType("integer"); + + b.Property("PreviousState") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("New"); + + b.Property("Quality") + .HasColumnType("integer"); + + b.Property("Rating") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("ResponseTimeMs") + .HasColumnType("integer"); + + b.Property("ReviewCardId") + .HasColumnType("integer") + .HasColumnName("ReviewItemId"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("SessionReference") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("StudyMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("flip"); + + b.Property("UserAnswer") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.HasKey("Id"); + + b.HasIndex("SessionReference"); + + b.HasIndex("ReviewCardId", "IdempotencyKey") + .IsUnique() + .HasFilter("\"IdempotencyKey\" IS NOT NULL"); + + b.HasIndex("ReviewCardId", "ReviewedAt"); + + b.ToTable("ReviewHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsCardTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcceptedReadingsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("AudioUrl") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("BackText") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CardType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleMeaning") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ExampleSentence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("FrontText") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GrammarPatternId") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("JlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("KanjiId") + .HasColumnType("integer"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("Meaning") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NormalizedContentKey") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("Reading") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ReviewNote") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ReviewedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ReviewedByAdminId") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("SubmittedByUserId") + .HasColumnType("integer"); + + b.Property("SynonymsJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UsageNotes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("VocabularyId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("GrammarPatternId"); + + b.HasIndex("KanjiId"); + + b.HasIndex("LessonId"); + + b.HasIndex("NormalizedContentKey"); + + b.HasIndex("ReviewedByAdminId"); + + b.HasIndex("VocabularyId"); + + b.HasIndex("SubmittedByUserId", "Status"); + + b.HasIndex("Status", "JlptLevel", "CardType"); + + b.ToTable("SrsCardTemplates"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsReviewSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CompletedCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DeadlineAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("FilterCardType") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("FilterJlptLevel") + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("FilterLearningState") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("FilterSourceType") + .HasMaxLength(40) + .HasColumnType("character varying(40)"); + + b.Property("ForgotCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastActivityAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ProcessedStepKeysJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)") + .HasDefaultValue("[]"); + + b.Property("QueueCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("RememberedCount") + .HasColumnType("integer"); + + b.Property("RequestedCount") + .HasColumnType("integer"); + + b.Property("RetryCardIdsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("character varying(8000)"); + + b.Property("ReviewedCount") + .HasColumnType("integer"); + + b.Property("SelectionScope") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("SessionKey") + .HasColumnType("uuid"); + + b.Property("SessionKind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Scheduled"); + + b.Property("ShuffleEnabled") + .HasColumnType("boolean"); + + b.Property("StartedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StudyMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TotalInitialCards") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SessionKey") + .IsUnique(); + + b.HasIndex("UserId", "Status", "LastActivityAtUtc"); + + b.HasIndex("UserId", "SessionKind", "Status", "LastActivityAtUtc"); + + b.ToTable("SrsReviewSessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CancellationReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Capacity") + .HasColumnType("integer"); + + b.Property("CapacitySnapshot") + .HasColumnType("integer"); + + b.Property("CourseDurationWeeks") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("EndsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("EnrollmentClosedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentClosesAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentOpensAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SourceProposalId") + .HasColumnType("integer"); + + b.Property("StartsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TotalTuitionSnapshot") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPerSessionSnapshot") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("TuitionPolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("TuitionSnapshotAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PlanId"); + + b.HasIndex("SourceProposalId") + .IsUnique() + .HasFilter("\"SourceProposalId\" IS NOT NULL"); + + b.ToTable("StudyCohorts", null, t => + { + t.HasCheckConstraint("CK_StudyCohort_Capacity", "\"Capacity\" > 0"); + + t.HasCheckConstraint("CK_StudyCohort_DurationWeeks", "\"CourseDurationWeeks\" >= 1"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortMentorAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AffectedSessionCount") + .HasColumnType("integer"); + + b.Property("AssignedById") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EffectiveFromSessionNumber") + .HasColumnType("integer"); + + b.Property("EffectiveFromUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IdempotencyKey") + .HasColumnType("uuid"); + + b.Property("ImpactSnapshot") + .IsRequired() + .HasColumnType("text"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PolicyId") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("PreviousMentorId") + .HasColumnType("integer"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.HasKey("Id"); + + b.HasIndex("AssignedById"); + + b.HasIndex("IdempotencyKey") + .IsUnique(); + + b.HasIndex("MentorId"); + + b.HasIndex("PolicyId"); + + b.HasIndex("PreviousMentorId"); + + b.HasIndex("CohortId", "Id"); + + b.ToTable("StudyCohortMentorAssignments", null, t => + { + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_DifferentMentor", "\"MentorId\" <> \"PreviousMentorId\""); + + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_Reason", "length(btrim(\"Reason\")) > 0"); + + t.HasCheckConstraint("CK_StudyCohortMentorAssignment_Sessions", "\"EffectiveFromSessionNumber\" > 0 AND \"AffectedSessionCount\" > 0"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActualEndedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ActualStartedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AvailabilityId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("Number") + .HasColumnType("integer"); + + b.Property("Status") + .IsConcurrencyToken() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.HasKey("Id"); + + b.HasIndex("AvailabilityId") + .IsUnique(); + + b.HasIndex("CohortId", "Number") + .IsUnique(); + + b.ToTable("StudyCohortSessions", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Amount") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("CancellationReason") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("CancelledAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("CapacitySnapshot") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CheckoutUrl") + .HasColumnType("text"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(3) + .HasColumnType("character varying(3)"); + + b.Property("DurationMonths") + .HasColumnType("integer"); + + b.Property("EndsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("GroupPolicyId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("MaximumAbsencePercent") + .HasColumnType("integer"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MinimumHomeworkPercent") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("OrderSnapshot") + .HasColumnType("text"); + + b.Property("PaymentConfirmedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentReference") + .HasColumnType("text"); + + b.Property("PaymentReviewReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PaymentStatus") + .IsRequired() + .HasColumnType("text"); + + b.Property("PlanId") + .HasColumnType("integer"); + + b.Property("PlanRevision") + .HasColumnType("integer"); + + b.Property("PolicyVersionSnapshot") + .HasColumnType("integer"); + + b.Property("ProviderPaymentReference") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("PurchaseKey") + .HasColumnType("uuid"); + + b.Property("RefundedAmount") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("RefundedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("RetakeClaimDays") + .HasColumnType("integer"); + + b.Property("RetakeOfId") + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("SessionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("Individual"); + + b.Property("SessionsPerWeek") + .HasColumnType("integer"); + + b.Property("StartsAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.Property("TransferredAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("TransferredFromCourseId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("CohortId"); + + b.HasIndex("GroupPolicyId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PlanId"); + + b.HasIndex("ProviderPaymentReference") + .IsUnique() + .HasDatabaseName("IX_StudyCourses_ProviderPaymentReference") + .HasFilter("\"ProviderPaymentReference\" IS NOT NULL"); + + b.HasIndex("RetakeOfId") + .IsUnique(); + + b.HasIndex("TransferredFromCourseId") + .IsUnique() + .HasFilter("\"TransferredFromCourseId\" IS NOT NULL"); + + b.HasIndex("CohortId", "LearnerId") + .IsUnique() + .HasDatabaseName("IX_StudyCourses_Cohort_ActiveLearner") + .HasFilter("\"CohortId\" IS NOT NULL AND \"Status\" = 'Active'"); + + b.HasIndex("LearnerId", "PurchaseKey") + .IsUnique(); + + b.ToTable("StudyCourses", null, t => + { + t.HasCheckConstraint("CK_StudyCourses_RefundedAmount", "\"RefundedAmount\" >= 0 AND \"RefundedAmount\" <= \"Amount\""); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseHomework", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("DueAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Feedback") + .HasColumnType("text"); + + b.Property("Instructions") + .IsRequired() + .HasColumnType("text"); + + b.Property("Passed") + .HasColumnType("boolean"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Submission") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CourseId"); + + b.ToTable("StudyCourseHomework", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCoursePlan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Capacity") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("DurationMonths") + .HasColumnType("integer"); + + b.Property("IsPublished") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Price") + .HasPrecision(18) + .HasColumnType("numeric(18,0)"); + + b.Property("RetakeClaimDays") + .HasColumnType("integer"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SessionMinutes") + .HasColumnType("integer"); + + b.Property("SessionType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("Individual"); + + b.Property("SessionsPerWeek") + .HasColumnType("integer"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TotalSessions") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.ToTable("StudyCoursePlans", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Attempt") + .HasColumnType("integer"); + + b.Property("AvailabilityId") + .HasColumnType("integer"); + + b.Property("ConfirmedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ConfirmedById") + .HasColumnType("integer"); + + b.Property("CourseId") + .HasColumnType("integer"); + + b.Property("MeetingUrl") + .HasColumnType("text"); + + b.Property("Note") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Number") + .HasColumnType("integer"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp without time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.HasKey("Id"); + + b.HasIndex("AvailabilityId"); + + b.HasIndex("CourseId", "Number", "Attempt") + .IsUnique(); + + b.ToTable("StudyCourseSessions", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiGradingQuota") + .HasColumnType("integer"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DurationDays") + .HasColumnType("integer"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsPopular") + .HasColumnType("boolean"); + + b.Property("IsTrial") + .HasColumnType("boolean"); + + b.Property("MeetingSessionCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PlanCategory") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasDefaultValue("self_study"); + + b.Property("Price") + .HasColumnType("decimal(18,0)"); + + b.Property("Revision") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.ToTable("SubscriptionPlans", t => + { + t.HasCheckConstraint("CK_SubscriptionPlans_AiGradingQuota", "\"AiGradingQuota\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_DurationDays", "\"DurationDays\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_Price", "\"Price\" >= 0"); + + t.HasCheckConstraint("CK_SubscriptionPlans_SortOrder", "\"SortOrder\" >= 0"); + }); + + b.HasData( + new + { + Id = 1, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 1 tuần.", + DurationDays = 7, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 1 tuần", + PlanCategory = "self_study", + Price = 1000m, + Revision = 1, + SortOrder = 6 + }, + new + { + Id = 2, + AiGradingQuota = 2, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 2 tuần.", + DurationDays = 14, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 2 tuần", + PlanCategory = "self_study", + Price = 1000m, + Revision = 1, + SortOrder = 5 + }, + new + { + Id = 3, + AiGradingQuota = 3, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 3 tuần.", + DurationDays = 21, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 3 tuần", + PlanCategory = "self_study", + Price = 2000m, + Revision = 1, + SortOrder = 4 + }, + new + { + Id = 4, + AiGradingQuota = 5, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 1 tháng.", + DurationDays = 30, + IsActive = true, + IsDeleted = false, + IsPopular = true, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 1 tháng", + PlanCategory = "self_study", + Price = 2000m, + Revision = 1, + SortOrder = 3 + }, + new + { + Id = 5, + AiGradingQuota = 10, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 2 tháng.", + DurationDays = 60, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 2 tháng", + PlanCategory = "self_study", + Price = 3000m, + Revision = 1, + SortOrder = 2 + }, + new + { + Id = 6, + AiGradingQuota = 15, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Truy cập nội dung ôn luyện các chứng chỉ tiếng Nhật trong 3 tháng.", + DurationDays = 90, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Tự học tiếng Nhật - 3 tháng", + PlanCategory = "self_study", + Price = 3000m, + Revision = 1, + SortOrder = 1 + }, + new + { + Id = 7, + AiGradingQuota = 0, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Gói demo gồm 12 buổi ôn luyện 1-1 với Mentor, thời hạn 90 ngày. Dữ liệu thanh toán demo được seed để kiểm thử đặt lịch trên frontend.", + DurationDays = 90, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 12, + Name = "Meeting 1-1 với Mentor - 12 buổi", + PlanCategory = "mentor_legacy", + Price = 1000m, + Revision = 1, + SortOrder = 7 + }, + new + { + Id = 8101, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt luyện nói và chấm phát âm tiếng Nhật bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Luyện nói AI - 1 lượt", + PlanCategory = "speaking", + Price = 1000m, + Revision = 1, + SortOrder = 10 + }, + new + { + Id = 8102, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt chấm bài viết tiếng Nhật bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Luyện viết AI - 1 lượt", + PlanCategory = "writing", + Price = 1000m, + Revision = 1, + SortOrder = 11 + }, + new + { + Id = 8103, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt giải thích chi tiết đáp án đề thi thử bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Giải thích đáp án AI - 1 lượt", + PlanCategory = "ai_grading", + Price = 1000m, + Revision = 1, + SortOrder = 12 + }, + new + { + Id = 8104, + AiGradingQuota = 1, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một lượt tạo lộ trình học cá nhân hóa bằng AI.", + DurationDays = 0, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 0, + Name = "Lộ trình học AI - 1 lượt", + PlanCategory = "learning_path", + Price = 1000m, + Revision = 1, + SortOrder = 13 + }, + new + { + Id = 8105, + AiGradingQuota = 0, + CreatedDate = new DateTime(2026, 11, 23, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Một buổi ôn luyện với mentor.", + DurationDays = 30, + IsActive = true, + IsDeleted = false, + IsPopular = false, + IsTrial = false, + MeetingSessionCount = 1, + Name = "Mentor - 1 buổi", + PlanCategory = "mentor_legacy", + Price = 1000m, + Revision = 1, + SortOrder = 14 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LearningObjectives") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("StageCode") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId", "SortOrder"); + + b.ToTable("Topics"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssessedCertificateLevelId") + .HasColumnType("integer"); + + b.Property("AvatarUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("CurrentStreak") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutes") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutesMax") + .HasColumnType("integer"); + + b.Property("DailyStudyMinutesMin") + .HasColumnType("integer"); + + b.Property("DeclaredJlptCertificateCode") + .HasColumnType("text"); + + b.Property("Email") + .HasColumnType("text"); + + b.Property("EmailNotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("FirebaseUid") + .HasColumnType("text"); + + b.Property("FirstName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("GoogleSubject") + .IsConcurrencyToken() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsEmailVerified") + .HasColumnType("boolean"); + + b.Property("IsPhoneVerified") + .HasColumnType("boolean"); + + b.Property("LastName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LastStudyDate") + .HasColumnType("timestamp without time zone"); + + b.Property("LearningGoalVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("LearningMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LongestStreak") + .HasColumnType("integer"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("NotificationPreferencesJson") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("PendingEmail") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PendingEmailRequestedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("PhoneNumber") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PlacementDecision") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("SelfDeclaredCertificateLevelId") + .HasColumnType("integer"); + + b.Property("StartingCertificateLevelId") + .HasColumnType("integer"); + + b.Property("StudyTimePreference") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("SystemNotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("TargetCertificateLevelId") + .HasColumnType("integer") + .HasColumnName("TargetCertificationLevelId"); + + b.Property("TargetExamDate") + .HasColumnType("timestamp without time zone"); + + b.Property("TokenVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.HasKey("Id"); + + b.HasIndex("AssessedCertificateLevelId"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("GoogleSubject") + .IsUnique(); + + b.HasIndex("SelfDeclaredCertificateLevelId"); + + b.HasIndex("StartingCertificateLevelId"); + + b.HasIndex("TargetCertificateLevelId"); + + b.ToTable("Users"); + + b.HasData( + new + { + Id = 900001, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "admin@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Admin", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "System", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 91, 215, 217, 54, 239, 206, 181, 216, 143, 33, 82, 211, 9, 70, 197, 173, 197, 0, 72, 71, 59, 150, 46, 114, 96, 137, 52, 174, 137, 29, 196, 61, 50, 254, 249, 101, 114, 92, 149, 32, 55, 127, 205, 126, 216, 147, 197, 192, 248, 173, 158, 92, 104, 42, 195, 107, 150, 15, 3, 74, 103, 104, 3, 229 }, + PasswordSalt = new byte[] { 61, 240, 150, 172, 239, 48, 224, 17, 192, 54, 50, 58, 91, 100, 55, 168, 18, 69, 137, 112, 110, 59, 180, 37, 201, 241, 143, 238, 139, 33, 128, 70, 87, 158, 235, 219, 229, 184, 94, 72, 41, 160, 160, 197, 158, 217, 128, 188, 156, 255, 147, 13, 151, 37, 133, 164, 9, 252, 175, 124, 21, 15, 152, 196 }, + PlacementDecision = "NotTaken", + Role = "Admin", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900002, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "mentor1@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Mentor", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "One", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 17, 253, 106, 25, 89, 176, 204, 31, 142, 252, 245, 31, 64, 101, 213, 135, 164, 116, 40, 46, 173, 175, 8, 0, 69, 101, 65, 4, 90, 25, 176, 223, 153, 237, 220, 94, 55, 133, 227, 181, 70, 97, 155, 122, 50, 139, 216, 136, 88, 52, 76, 98, 250, 64, 52, 71, 146, 221, 225, 137, 106, 6, 178, 239 }, + PasswordSalt = new byte[] { 233, 77, 244, 252, 171, 97, 38, 140, 50, 138, 10, 54, 122, 165, 186, 85, 129, 82, 49, 10, 98, 44, 165, 57, 50, 7, 238, 166, 142, 224, 94, 49, 134, 226, 247, 110, 154, 139, 99, 204, 95, 39, 171, 235, 212, 26, 217, 87, 139, 118, 253, 125, 241, 255, 57, 22, 140, 171, 11, 168, 174, 202, 32, 17 }, + PlacementDecision = "NotTaken", + Role = "Mentor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900003, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "mentor2@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Mentor", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Two", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 93, 130, 109, 171, 238, 187, 245, 15, 202, 89, 247, 220, 95, 192, 246, 138, 5, 75, 250, 28, 208, 28, 51, 79, 127, 28, 214, 237, 93, 221, 108, 26, 152, 66, 73, 65, 11, 147, 154, 102, 113, 49, 51, 24, 51, 197, 248, 254, 22, 98, 87, 249, 250, 104, 131, 74, 16, 18, 179, 200, 3, 3, 79, 47 }, + PasswordSalt = new byte[] { 240, 155, 254, 183, 129, 162, 74, 247, 41, 9, 67, 242, 128, 8, 226, 85, 5, 104, 104, 72, 101, 75, 130, 95, 47, 101, 116, 89, 207, 23, 119, 178, 38, 180, 185, 145, 58, 115, 14, 30, 85, 216, 169, 133, 94, 115, 11, 117, 96, 87, 227, 240, 204, 48, 51, 144, 170, 248, 167, 56, 175, 194, 253, 135 }, + PlacementDecision = "NotTaken", + Role = "Mentor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900004, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "author1@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Content", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Author One", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 168, 249, 82, 144, 178, 145, 94, 164, 34, 152, 2, 74, 204, 105, 84, 145, 96, 199, 153, 136, 110, 82, 114, 113, 22, 139, 117, 143, 50, 239, 197, 4, 51, 189, 137, 48, 175, 14, 104, 164, 218, 249, 148, 217, 33, 44, 202, 128, 237, 183, 110, 228, 185, 36, 209, 254, 183, 182, 55, 1, 78, 16, 234, 50 }, + PasswordSalt = new byte[] { 19, 216, 84, 143, 3, 184, 50, 39, 209, 137, 149, 82, 224, 206, 6, 240, 237, 242, 172, 27, 55, 92, 242, 101, 149, 76, 104, 38, 176, 43, 40, 8, 102, 202, 146, 224, 62, 43, 147, 132, 2, 158, 81, 170, 29, 103, 76, 248, 101, 105, 213, 205, 32, 51, 59, 39, 221, 11, 135, 250, 193, 8, 78, 219 }, + PlacementDecision = "NotTaken", + Role = "ContentAuthor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900005, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "author2@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Content", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Author Two", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 189, 121, 9, 1, 230, 137, 43, 239, 79, 56, 195, 196, 66, 116, 42, 1, 137, 55, 54, 249, 55, 231, 79, 224, 182, 182, 199, 133, 100, 39, 138, 5, 223, 215, 48, 46, 60, 214, 49, 88, 42, 186, 232, 116, 237, 89, 55, 144, 4, 78, 215, 231, 237, 220, 96, 225, 202, 97, 61, 165, 246, 28, 126, 198 }, + PasswordSalt = new byte[] { 66, 178, 77, 56, 234, 206, 29, 78, 136, 190, 160, 142, 226, 249, 14, 17, 26, 101, 167, 36, 193, 55, 150, 94, 239, 81, 69, 54, 81, 171, 80, 22, 208, 38, 242, 2, 55, 171, 64, 38, 48, 224, 36, 216, 133, 132, 147, 100, 174, 32, 65, 134, 128, 35, 50, 138, 204, 59, 167, 96, 11, 128, 101, 102 }, + PlacementDecision = "NotTaken", + Role = "ContentAuthor", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900006, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Meeting", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Test Learner", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 9, 206, 219, 58, 155, 234, 107, 145, 121, 174, 134, 51, 96, 253, 64, 216, 157, 114, 92, 36, 123, 206, 67, 217, 207, 166, 54, 71, 254, 251, 156, 200, 185, 110, 198, 135, 221, 146, 243, 40, 237, 229, 16, 133, 163, 161, 156, 79, 138, 103, 85, 25, 114, 81, 99, 182, 25, 73, 212, 198, 212, 192, 54, 129 }, + PasswordSalt = new byte[] { 231, 202, 97, 95, 11, 9, 242, 47, 62, 77, 67, 36, 170, 78, 120, 81, 56, 69, 47, 36, 209, 212, 107, 244, 15, 34, 189, 110, 57, 66, 205, 213, 224, 19, 245, 192, 104, 146, 130, 44, 54, 107, 2, 15, 109, 136, 118, 220, 228, 44, 110, 219, 31, 100, 161, 164, 63, 231, 196, 79, 120, 106, 181, 71 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900007, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner2.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Linh", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Nguyen", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 217, 79, 50, 159, 85, 88, 67, 15, 23, 182, 103, 80, 220, 85, 86, 173, 204, 186, 57, 67, 183, 165, 253, 243, 150, 250, 150, 190, 122, 252, 55, 169, 85, 236, 69, 106, 19, 219, 244, 42, 239, 30, 189, 176, 52, 47, 30, 28, 125, 31, 162, 255, 61, 3, 238, 201, 168, 88, 161, 42, 216, 86, 172, 219 }, + PasswordSalt = new byte[] { 85, 97, 108, 158, 219, 70, 81, 106, 73, 23, 205, 163, 105, 159, 117, 19, 175, 147, 178, 99, 112, 116, 163, 243, 109, 178, 129, 229, 245, 175, 91, 174, 66, 198, 122, 88, 80, 68, 160, 64, 85, 118, 105, 41, 135, 89, 49, 160, 120, 13, 116, 148, 255, 27, 157, 207, 106, 203, 127, 74, 19, 61, 148, 120 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900008, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner3.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Minh", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Tran", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 84, 97, 164, 196, 63, 151, 182, 39, 139, 242, 152, 22, 179, 33, 174, 113, 0, 236, 253, 114, 234, 242, 209, 76, 196, 162, 143, 195, 180, 3, 178, 193, 205, 230, 18, 114, 49, 151, 198, 217, 254, 21, 94, 176, 146, 214, 235, 122, 28, 241, 164, 161, 4, 161, 209, 38, 102, 179, 31, 107, 157, 25, 35, 63 }, + PasswordSalt = new byte[] { 26, 188, 78, 205, 57, 115, 100, 129, 148, 135, 165, 205, 148, 203, 245, 36, 244, 177, 9, 104, 120, 140, 21, 164, 36, 75, 122, 51, 115, 69, 174, 180, 120, 155, 62, 37, 97, 227, 212, 134, 200, 7, 66, 255, 219, 10, 140, 149, 67, 86, 164, 170, 142, 165, 181, 103, 47, 100, 238, 24, 178, 29, 171, 226 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }, + new + { + Id = 900009, + CreatedDate = new DateTime(2026, 9, 28, 0, 0, 0, 0, DateTimeKind.Utc), + CurrentStreak = 0, + DailyStudyMinutes = 30, + Email = "learner4.meeting@rikipath.local", + EmailNotificationsEnabled = true, + FirstName = "Hoang", + IsDeleted = false, + IsEmailVerified = true, + IsPhoneVerified = false, + LastName = "Pham", + LearningGoalVersion = 0, + LearningMode = "Standard", + LongestStreak = 0, + PasswordHash = new byte[] { 42, 30, 236, 129, 234, 192, 63, 84, 148, 163, 154, 246, 107, 147, 189, 95, 33, 141, 196, 67, 181, 51, 157, 136, 93, 228, 237, 165, 164, 49, 4, 146, 87, 84, 9, 47, 28, 59, 33, 130, 37, 63, 43, 229, 8, 178, 123, 74, 61, 159, 235, 68, 217, 51, 225, 29, 201, 104, 44, 152, 53, 255, 199, 28 }, + PasswordSalt = new byte[] { 83, 214, 138, 3, 142, 91, 229, 97, 238, 61, 48, 237, 80, 82, 112, 249, 166, 81, 53, 95, 170, 120, 13, 87, 113, 159, 60, 37, 75, 229, 226, 107, 229, 89, 60, 57, 109, 196, 235, 81, 145, 154, 110, 120, 141, 13, 142, 77, 41, 132, 58, 80, 154, 57, 226, 168, 176, 251, 113, 167, 242, 139, 7, 177 }, + PlacementDecision = "NotTaken", + Role = "Learner", + SystemNotificationsEnabled = true, + TokenVersion = 1 + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserDeviceToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceIdentifier") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("FcmToken") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastSeenAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("FcmToken") + .HasDatabaseName("IX_UserDeviceTokens_FcmToken"); + + b.HasIndex("UserId", "DeviceIdentifier") + .HasDatabaseName("IX_UserDeviceTokens_UserId_DeviceIdentifier"); + + b.HasIndex("UserId", "IsActive") + .HasDatabaseName("IX_UserDeviceTokens_UserId_IsActive"); + + b.ToTable("UserDeviceTokens", (string)null); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSrsPreference", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AutoEnrollAfterLesson") + .HasColumnType("boolean"); + + b.Property("AutoPlayAudio") + .HasColumnType("boolean"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DailyNewLimit") + .HasColumnType("integer"); + + b.Property("DailyReminderEnabled") + .HasColumnType("boolean"); + + b.Property("DailyReviewLimit") + .HasColumnType("integer"); + + b.Property("EmailReminderEnabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastReminderSentAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("LastReminderSentLocalDate") + .HasColumnType("date"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PreferredLocale") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)"); + + b.Property("PreferredReviewMode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("ReminderDaysJson") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ReminderFrequency") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("ReminderHour") + .HasColumnType("integer"); + + b.Property("ReminderMinute") + .HasColumnType("integer"); + + b.Property("ShowFuriganaHint") + .HasColumnType("boolean"); + + b.Property("TimezoneId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.HasIndex("DailyReminderEnabled", "LastReminderSentLocalDate"); + + b.ToTable("UserSrsPreferences"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AiGradingQuota") + .HasColumnType("integer"); + + b.Property("AiGradingUsedCount") + .HasColumnType("integer"); + + b.Property("AmountPaid") + .HasColumnType("decimal(18,2)"); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("DurationDaysSnapshot") + .HasColumnType("integer"); + + b.Property("EndDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MeetingSessionsIncluded") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("MeetingSessionsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("MentorPracticeOutcomeJson") + .HasColumnType("text"); + + b.Property("MentorReviewCompletedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("MentorReviewPlan") + .HasMaxLength(6000) + .HasColumnType("character varying(6000)"); + + b.Property("MentorReviewSessionAt") + .HasColumnType("timestamp without time zone"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentExpiresAt") + .HasColumnType("timestamp without time zone"); + + b.Property("PaymentStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("PaymentTransactionId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PendingMentorAvailabilityId") + .HasColumnType("integer"); + + b.Property("PendingMentorQuestion") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PlanCategorySnapshot") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PlanNameSnapshot") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.Property("PlanRevisionSnapshot") + .HasColumnType("integer"); + + b.Property("PurchasedAt") + .HasColumnType("timestamp without time zone"); + + b.Property("StartDate") + .HasColumnType("timestamp without time zone"); + + b.Property("SubscriptionPlanId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("PendingMentorAvailabilityId"); + + b.HasIndex("SubscriptionPlanId"); + + b.HasIndex("UserId", "PaymentStatus", "EndDate"); + + b.ToTable("UserSubscriptions"); + + b.HasData( + new + { + Id = 990001, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 90, + EndDate = new DateTime(2099, 12, 31, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS", + PlanCategorySnapshot = "mentor_legacy", + PlanNameSnapshot = "Meeting 1-1 với Mentor - 12 buổi", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900006, + Version = 0u + }, + new + { + Id = 990002, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-2", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900007, + Version = 0u + }, + new + { + Id = 990003, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-3", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900008, + Version = 0u + }, + new + { + Id = 990004, + AiGradingQuota = 0, + AiGradingUsedCount = 0, + AmountPaid = 459000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + EndDate = new DateTime(2026, 12, 30, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 12, + MeetingSessionsUsed = 1, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-MENTOR-12-SESSIONS-4", + PurchasedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 7, + UserId = 900009, + Version = 0u + }, + new + { + Id = 990005, + AiGradingQuota = 15, + AiGradingUsedCount = 0, + AmountPaid = 3000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 90, + EndDate = new DateTime(2099, 12, 31, 23, 59, 59, 0, DateTimeKind.Unspecified), + IsDeleted = false, + MeetingSessionsIncluded = 0, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-FULL-ACCESS-SELF-STUDY", + PlanCategorySnapshot = "self_study", + PlanNameSnapshot = "Tự học tiếng Nhật - 3 tháng", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + StartDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 6, + UserId = 900006, + Version = 0u + }, + new + { + Id = 990006, + AiGradingQuota = 1, + AiGradingUsedCount = 0, + AmountPaid = 1000m, + CreatedDate = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + DurationDaysSnapshot = 0, + IsDeleted = false, + MeetingSessionsIncluded = 0, + MeetingSessionsUsed = 0, + PaymentStatus = "Paid", + PaymentTransactionId = "DEMO-FULL-ACCESS-LEARNING-PATH", + PlanCategorySnapshot = "learning_path", + PlanNameSnapshot = "Mua 1 lượt AI đề xuất lộ trình", + PlanRevisionSnapshot = 1, + PurchasedAt = new DateTime(2026, 10, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), + SubscriptionPlanId = 8104, + UserId = 900006, + Version = 0u + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AudioUrl") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("uuid"); + + b.Property("CreatedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("ExampleSentence") + .HasColumnType("text"); + + b.Property("ExampleSentenceMeaning") + .HasColumnType("text"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Meaning") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ModifiedBy") + .HasColumnType("uuid"); + + b.Property("ModifiedDate") + .HasColumnType("timestamp without time zone"); + + b.Property("Reading") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("Published"); + + b.Property("UnpublishedAtUtc") + .HasColumnType("timestamp without time zone"); + + b.Property("UnpublishedReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("UserAccountId") + .HasColumnType("integer"); + + b.Property("Version") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1); + + b.Property("Word") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("UserAccountId"); + + b.HasIndex("Word", "Reading"); + + b.ToTable("Vocabularies"); + }); + + modelBuilder.Entity("FeatureSubscriptionPlan", b => + { + b.HasOne("RikiPath.Domain.Entities.Feature", null) + .WithMany() + .HasForeignKey("FeaturesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.SubscriptionPlan", null) + .WithMany() + .HasForeignKey("SubscriptionPlansId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.AiCreditTopUp", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("AiCreditTopUps") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateType", "CertificateType") + .WithMany("Levels") + .HasForeignKey("CertificateTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateType"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "Attempt") + .WithMany() + .HasForeignKey("AttemptId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Enrollment") + .WithMany() + .HasForeignKey("EnrollmentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.ClassQuiz", "Quiz") + .WithMany("Assignments") + .HasForeignKey("QuizId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Attempt"); + + b.Navigation("Enrollment"); + + b.Navigation("Learner"); + + b.Navigation("Quiz"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("DecidedById") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("Course"); + + b.Navigation("CourseSession"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaintEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortComplaint", "Complaint") + .WithMany("History") + .HasForeignKey("ComplaintId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Complaint"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortEnrollmentEntitlement", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "StudyCohort") + .WithMany() + .HasForeignKey("StudyCohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Learner"); + + b.Navigation("Plan"); + + b.Navigation("StudyCohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortLearningFeedback", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("RespondedById") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Course"); + + b.Navigation("CourseSession"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortMentorReview", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cohort"); + + b.Navigation("Course"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "RequestedBy") + .WithMany() + .HasForeignKey("RequestedById") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("ReviewedById") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("RequestedBy"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequestEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortScheduleRequest", "Request") + .WithMany("History") + .HasForeignKey("RequestId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Request"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "DestinationCourse") + .WithMany() + .HasForeignKey("DestinationCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", null) + .WithMany() + .HasForeignKey("PolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "RequestedTargetCohort") + .WithMany() + .HasForeignKey("RequestedTargetCohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("ReviewedById") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "SourceCohort") + .WithMany() + .HasForeignKey("SourceCohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "SourceCourse") + .WithMany() + .HasForeignKey("SourceCourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "TargetCohort") + .WithMany() + .HasForeignKey("TargetCohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("DestinationCourse"); + + b.Navigation("Learner"); + + b.Navigation("RequestedTargetCohort"); + + b.Navigation("SourceCohort"); + + b.Navigation("SourceCourse"); + + b.Navigation("TargetCohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequestEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.CohortTransferRequest", "Request") + .WithMany("History") + .HasForeignKey("RequestId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Request"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentApprovalRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "SubmittedBy") + .WithMany() + .HasForeignKey("SubmittedByUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("SubmittedBy"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentAudioTranscription", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CreatedByUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentBankItem", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Owner") + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentLevelMapping", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("ContentLevelMappings") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("ContentLevelMappings") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("ContentLevelMappings") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("ContentLevelMappings") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("CertificateLevel"); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("Passages") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockTestSection"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseAuditEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Audit") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseRetakeRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("RetakeRequests") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CourseScheduleRequest", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany() + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.EmailVerification", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "User") + .WithMany("EmailVerifications") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GradingResult", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkSubmission") + .WithOne("GradingResult") + .HasForeignKey("RikiPath.Domain.Entities.GradingResult", "HomeworkSubmissionId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.PracticeSubmission", "PracticeSubmission") + .WithOne("GradingResult") + .HasForeignKey("RikiPath.Domain.Entities.GradingResult", "PracticeSubmissionId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("HomeworkSubmission"); + + b.Navigation("PracticeSubmission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredGrammarPatterns") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "StudyCourse") + .WithMany() + .HasForeignKey("StudyCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Cohort"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + + b.Navigation("StudyCourse"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentAttachment", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("Attachments") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentExercise", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("Exercises") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany() + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("PracticeExercise"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignmentLesson", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany("HomeworkAssignmentLessons") + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("HomeworkAssignmentLessons") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithOne("Submission") + .HasForeignKey("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("Learner"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmissionFile", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkSubmission", "HomeworkSubmission") + .WithMany("Files") + .HasForeignKey("HomeworkSubmissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkSubmission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.JlptLevelPayCoefficient", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("ConfiguredByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.HasOne("RikiPath.Domain.Entities.KanaCharacter", "KanaCharacter") + .WithMany("PracticeCards") + .HasForeignKey("KanaCharacterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("KanaCharacter"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.KanaWritingPracticeCard", "Card") + .WithMany("Histories") + .HasForeignKey("KanaWritingPracticeCardId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Card"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredKanjis") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerEssay", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LearnerEssays") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerFeedback", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Learner"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerHighlight", b => + { + b.HasOne("RikiPath.Domain.Entities.LearnerNoteEntry", "LinkedNoteEntry") + .WithMany() + .HasForeignKey("LinkedNoteEntryId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.ReviewCard", "LinkedReviewCard") + .WithMany() + .HasForeignKey("LinkedReviewCardId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LinkedNoteEntry"); + + b.Navigation("LinkedReviewCard"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.HasOne("RikiPath.Domain.Entities.NotebookFolder", "Folder") + .WithMany("Files") + .HasForeignKey("FolderId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LearnerNotes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Folder"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany() + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("LearnerNoteEntries") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.LearnerNote", "LearnerNote") + .WithMany("LearnerNoteEntries") + .HasForeignKey("LearnerNoteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.NotebookPage", "NotebookPage") + .WithMany("SavedItems") + .HasForeignKey("NotebookPageId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("LearnerNoteEntries") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("LearnerNote"); + + b.Navigation("NotebookPage"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerPracticeAnswer", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeExerciseAttempt", "PracticeExerciseAttempt") + .WithMany("Answers") + .HasForeignKey("PracticeExerciseAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeQuestion", "PracticeQuestion") + .WithMany("Answers") + .HasForeignKey("PracticeQuestionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.PracticeQuestionOption", "SelectedOption") + .WithMany() + .HasForeignKey("SelectedOptionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("PracticeExerciseAttempt"); + + b.Navigation("PracticeQuestion"); + + b.Navigation("SelectedOption"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("Lessons") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany("Lessons") + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "PrerequisiteLesson") + .WithMany() + .HasForeignKey("PrerequisiteLessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Topic", "Topic") + .WithMany("Lessons") + .HasForeignKey("TopicId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredLessons") + .HasForeignKey("UserAccountId"); + + b.Navigation("CertificateLevel"); + + b.Navigation("LanguageSkill"); + + b.Navigation("PrerequisiteLesson"); + + b.Navigation("Topic"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonGrammar", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("LessonGrammars") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonGrammars") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("GrammarPattern"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonKanji", b => + { + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("LessonKanjis") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonKanjis") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Kanji"); + + b.Navigation("Lesson"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonProgress", b => + { + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonProgresses") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("LessonProgresses") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lesson"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LessonVocabulary", b => + { + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany("LessonVocabularies") + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany("LessonVocabularies") + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lesson"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAbuseReport", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Reporter") + .WithMany() + .HasForeignKey("ReporterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "TargetUser") + .WithMany() + .HasForeignKey("TargetUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("Reporter"); + + b.Navigation("TargetUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceApproval", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("MentorBooking"); + + b.Navigation("ReviewedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAttendanceRecord", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourseSession", "CourseSession") + .WithMany() + .HasForeignKey("CourseSessionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CourseSession"); + + b.Navigation("MentorBooking"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany("MentorAvailabilities") + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorScheduleRule", "ScheduleRule") + .WithMany() + .HasForeignKey("MentorScheduleRuleId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorWeeklyAvailability", "WeeklyAvailability") + .WithMany("Slots") + .HasForeignKey("MentorWeeklyAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "TeachingProposal") + .WithMany("GeneratedAvailabilities") + .HasForeignKey("TeachingProposalId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("ScheduleRule"); + + b.Navigation("TeachingProposal"); + + b.Navigation("WeeklyAvailability"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBankAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "VerifiedByAdmin") + .WithMany() + .HasForeignKey("VerifiedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("MentorUser"); + + b.Navigation("VerifiedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CompensationLevel") + .WithMany() + .HasForeignKey("CompensationLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorCreditGrant", "CreditGrant") + .WithMany() + .HasForeignKey("CreditGrantId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany("MentorBookings") + .HasForeignKey("MentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserSubscription", "UserSubscription") + .WithMany("MentorBookings") + .HasForeignKey("UserSubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CompensationLevel"); + + b.Navigation("CreditGrant"); + + b.Navigation("MentorAvailability"); + + b.Navigation("UserSubscription"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingDayGuard", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingIntent", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Learner"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingReservation", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany() + .HasForeignKey("MentorAvailabilityId", "MentorId") + .HasPrincipalKey("Id", "MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + + b.Navigation("MentorAvailability"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBookingTerms", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "MentorAvailability") + .WithMany() + .HasForeignKey("MentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithOne() + .HasForeignKey("RikiPath.Domain.Entities.MentorBookingTerms", "MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorAvailability"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCalendarConnection", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorChatMessage", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Sender") + .WithMany() + .HasForeignKey("SenderUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("Sender"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorCreditGrant", "CreditGrant") + .WithMany("Entries") + .HasForeignKey("CreditGrantId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreditGrant"); + + b.Navigation("Learner"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserSubscription", "UserSubscription") + .WithMany() + .HasForeignKey("UserSubscriptionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Learner"); + + b.Navigation("UserSubscription"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ResolvedByAdmin") + .WithMany() + .HasForeignKey("ResolvedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + + b.Navigation("ResolvedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDisputeHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorDispute", "Dispute") + .WithMany("Histories") + .HasForeignKey("DisputeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Dispute"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorEarningEntry", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAttendanceApproval", "AttendanceApproval") + .WithMany() + .HasForeignKey("AttendanceApprovalId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany() + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("AttendanceApproval"); + + b.Navigation("CertificateLevel"); + + b.Navigation("CreatedByAdmin"); + + b.Navigation("MentorBooking"); + + b.Navigation("MentorUser"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorGroupPolicy", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "DeletedByAdmin") + .WithMany() + .HasForeignKey("DeletedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "LastAppliedByAdmin") + .WithMany() + .HasForeignKey("LastAppliedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UpdatedByAdmin") + .WithMany() + .HasForeignKey("UpdatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreatedByAdmin"); + + b.Navigation("DeletedByAdmin"); + + b.Navigation("LastAppliedByAdmin"); + + b.Navigation("UpdatedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorHourlyRate", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfiguredByAdmin"); + + b.Navigation("MentorUser"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorKpiPolicy", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreatedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfirmedByAdmin") + .WithMany() + .HasForeignKey("ConfirmedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "InitiatedByAdmin") + .WithMany() + .HasForeignKey("InitiatedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBankAccount", "LockedBankAccount") + .WithMany() + .HasForeignKey("LockedBankAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorPayoutObligation", "PayoutObligation") + .WithMany("Attempts") + .HasForeignKey("PayoutObligationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfirmedByAdmin"); + + b.Navigation("InitiatedByAdmin"); + + b.Navigation("LockedBankAccount"); + + b.Navigation("PayoutObligation"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBankAccount", "LockedBankAccount") + .WithMany() + .HasForeignKey("LockedBankAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.OrganizationPayoutAccount", "OrganizationPayoutAccount") + .WithMany() + .HasForeignKey("OrganizationPayoutAccountId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany() + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("LockedBankAccount"); + + b.Navigation("MentorUser"); + + b.Navigation("OrganizationPayoutAccount"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollAdjustment", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany("Adjustments") + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollLine", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorEarningEntry", "EarningEntry") + .WithMany() + .HasForeignKey("EarningEntryId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorPayrollPeriod", "PayrollPeriod") + .WithMany("Lines") + .HasForeignKey("PayrollPeriodId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("EarningEntry"); + + b.Navigation("MentorBooking"); + + b.Navigation("PayrollPeriod"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ApprovedByAdmin") + .WithMany() + .HasForeignKey("ApprovedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "PreparedByAdmin") + .WithMany() + .HasForeignKey("PreparedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByAdmin"); + + b.Navigation("MentorUser"); + + b.Navigation("PreparedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorProfile", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithOne("MentorProfile") + .HasForeignKey("RikiPath.Domain.Entities.MentorProfile", "MentorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorReview", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithMany() + .HasForeignKey("MentorBookingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("MentorBooking"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorScheduleRule", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorSchedule", "Schedule") + .WithMany("Rules") + .HasForeignKey("ScheduleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Schedule"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "CoursePlan") + .WithMany() + .HasForeignKey("CoursePlanId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + + b.Navigation("CoursePlan"); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("ReviewedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposalEvent", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "Proposal") + .WithMany("Events") + .HasForeignKey("ProposalId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Proposal"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingQualification", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "MentorUser") + .WithMany() + .HasForeignKey("MentorUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "VerifiedByAdmin") + .WithMany() + .HasForeignKey("VerifiedByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("MentorUser"); + + b.Navigation("VerifiedByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTimesheetAdjustment", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohortSession", "CohortSession") + .WithMany() + .HasForeignKey("CohortSessionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CohortSession"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", null) + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", null) + .WithMany() + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("Questions") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.ContentPassage", "Passage") + .WithMany("Questions") + .HasForeignKey("PassageId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.MockQuestion", null) + .WithMany() + .HasForeignKey("SourceQuestionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockTestSection"); + + b.Navigation("Passage"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestionOption", b => + { + b.HasOne("RikiPath.Domain.Entities.MockQuestion", "MockQuestion") + .WithMany("Options") + .HasForeignKey("MockQuestionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MockQuestion"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("MockTests") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredMockTests") + .HasForeignKey("UserAccountId"); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAnswer", b => + { + b.HasOne("RikiPath.Domain.Entities.MockQuestion", "MockQuestion") + .WithMany("Answers") + .HasForeignKey("MockQuestionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "MockTestAttempt") + .WithMany("Answers") + .HasForeignKey("MockTestAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockQuestionOption", "SelectedOption") + .WithMany() + .HasForeignKey("SelectedOptionId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("MockQuestion"); + + b.Navigation("MockTestAttempt"); + + b.Navigation("SelectedOption"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("MockTestAttempts") + .HasForeignKey("UserAccountId"); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateSection", "CertificateSection") + .WithMany("MockTestSections") + .HasForeignKey("CertificateSectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany("MockTestSections") + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTest", "MockTest") + .WithMany("Sections") + .HasForeignKey("MockTestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CertificateSection"); + + b.Navigation("LanguageSkill"); + + b.Navigation("MockTest"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSectionResult", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "MockTestAttempt") + .WithMany("SectionResults") + .HasForeignKey("MockTestAttemptId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MockTestSection", "MockTestSection") + .WithMany("SectionResults") + .HasForeignKey("MockTestSectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MockTestAttempt"); + + b.Navigation("MockTestSection"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Note", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorBooking", "MentorBooking") + .WithOne("Note") + .HasForeignKey("RikiPath.Domain.Entities.Note", "MentorBookingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("Notes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("MentorBooking"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.HasOne("RikiPath.Domain.Entities.LearnerNote", "LearnerNote") + .WithMany("Pages") + .HasForeignKey("LearnerNoteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("LearnerNote"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Notification", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("Notifications") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.OrganizationPayoutAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfiguredByAdmin") + .WithMany() + .HasForeignKey("ConfiguredByAdminId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ConfiguredByAdmin"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.LanguageSkill", "LanguageSkill") + .WithMany() + .HasForeignKey("LanguageSkillId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Topic", "Topic") + .WithMany() + .HasForeignKey("TopicId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CertificateLevel"); + + b.Navigation("LanguageSkill"); + + b.Navigation("Lesson"); + + b.Navigation("Topic"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.HasOne("RikiPath.Domain.Entities.HomeworkAssignment", "HomeworkAssignment") + .WithMany() + .HasForeignKey("HomeworkAssignmentId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany("Attempts") + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("HomeworkAssignment"); + + b.Navigation("PracticeExercise"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeExercise", "PracticeExercise") + .WithMany("Questions") + .HasForeignKey("PracticeExerciseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PracticeExercise"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestionOption", b => + { + b.HasOne("RikiPath.Domain.Entities.PracticeQuestion", "PracticeQuestion") + .WithMany("Options") + .HasForeignKey("PracticeQuestionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PracticeQuestion"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany("PracticeSubmissions") + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("PracticeSubmissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.RecommendedLearningPath", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("RecommendedLearningPaths") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany("ReviewCards") + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany("ReviewCards") + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.LearnerNoteEntry", "LearnerNoteEntry") + .WithMany("ReviewCards") + .HasForeignKey("LearnerNoteEntryId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.SrsCardTemplate", "SrsCardTemplate") + .WithMany() + .HasForeignKey("SrsCardTemplateId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("ReviewCards") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany() + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("LearnerNoteEntry"); + + b.Navigation("Lesson"); + + b.Navigation("SrsCardTemplate"); + + b.Navigation("UserAccount"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewHistory", b => + { + b.HasOne("RikiPath.Domain.Entities.ReviewCard", "ReviewCard") + .WithMany("ReviewHistories") + .HasForeignKey("ReviewCardId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ReviewCard"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsCardTemplate", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.GrammarPattern", "GrammarPattern") + .WithMany() + .HasForeignKey("GrammarPatternId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Kanji", "Kanji") + .WithMany() + .HasForeignKey("KanjiId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Lesson", "Lesson") + .WithMany() + .HasForeignKey("LessonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "ReviewedByAdmin") + .WithMany() + .HasForeignKey("ReviewedByAdminId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "SubmittedByUser") + .WithMany() + .HasForeignKey("SubmittedByUserId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.Vocabulary", "Vocabulary") + .WithMany() + .HasForeignKey("VocabularyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CertificateLevel"); + + b.Navigation("GrammarPattern"); + + b.Navigation("Kanji"); + + b.Navigation("Lesson"); + + b.Navigation("ReviewedByAdmin"); + + b.Navigation("SubmittedByUser"); + + b.Navigation("Vocabulary"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SrsReviewSession", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorTeachingProposal", "SourceProposal") + .WithMany() + .HasForeignKey("SourceProposalId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("GroupPolicy"); + + b.Navigation("Mentor"); + + b.Navigation("Plan"); + + b.Navigation("SourceProposal"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortMentorAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("AssignedById") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", null) + .WithMany() + .HasForeignKey("PolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany() + .HasForeignKey("PreviousMentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohortSession", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "Availability") + .WithMany() + .HasForeignKey("AvailabilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany("Sessions") + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Availability"); + + b.Navigation("Cohort"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany("Enrollments") + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorGroupPolicy", "GroupPolicy") + .WithMany() + .HasForeignKey("GroupPolicyId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCoursePlan", "Plan") + .WithMany() + .HasForeignKey("PlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "RetakeOf") + .WithMany() + .HasForeignKey("RetakeOfId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", null) + .WithMany() + .HasForeignKey("TransferredFromCourseId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("GroupPolicy"); + + b.Navigation("Learner"); + + b.Navigation("Mentor"); + + b.Navigation("Plan"); + + b.Navigation("RetakeOf"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseHomework", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Homework") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCoursePlan", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourseSession", b => + { + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "Availability") + .WithMany() + .HasForeignKey("AvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Course") + .WithMany("Sessions") + .HasForeignKey("CourseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Availability"); + + b.Navigation("Course"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "AssessedCertificateLevel") + .WithMany() + .HasForeignKey("AssessedCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "SelfDeclaredCertificateLevel") + .WithMany() + .HasForeignKey("SelfDeclaredCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "StartingCertificateLevel") + .WithMany() + .HasForeignKey("StartingCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "TargetCertificateLevel") + .WithMany("LearnersTargeting") + .HasForeignKey("TargetCertificateLevelId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("AssessedCertificateLevel"); + + b.Navigation("SelfDeclaredCertificateLevel"); + + b.Navigation("StartingCertificateLevel"); + + b.Navigation("TargetCertificateLevel"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserDeviceToken", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSrsPreference", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.MentorAvailability", "PendingMentorAvailability") + .WithMany() + .HasForeignKey("PendingMentorAvailabilityId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.SubscriptionPlan", "SubscriptionPlan") + .WithMany("UserSubscriptions") + .HasForeignKey("SubscriptionPlanId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "UserAccount") + .WithMany("UserSubscriptions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Mentor"); + + b.Navigation("PendingMentorAvailability"); + + b.Navigation("SubscriptionPlan"); + + b.Navigation("UserAccount"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", null) + .WithMany("AuthoredVocabularies") + .HasForeignKey("UserAccountId"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateLevel", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnersTargeting"); + + b.Navigation("Lessons"); + + b.Navigation("MockTests"); + + b.Navigation("PracticeSubmissions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateSection", b => + { + b.Navigation("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CertificateType", b => + { + b.Navigation("Levels"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Navigation("Assignments"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortScheduleRequest", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.CohortTransferRequest", b => + { + b.Navigation("History"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ContentPassage", b => + { + b.Navigation("Questions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.GrammarPattern", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LessonGrammars"); + + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkAssignment", b => + { + b.Navigation("Attachments"); + + b.Navigation("Exercises"); + + b.Navigation("HomeworkAssignmentLessons"); + + b.Navigation("Submission"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.HomeworkSubmission", b => + { + b.Navigation("Files"); + + b.Navigation("GradingResult"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaCharacter", b => + { + b.Navigation("PracticeCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.KanaWritingPracticeCard", b => + { + b.Navigation("Histories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Kanji", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnerNoteEntries"); + + b.Navigation("LessonKanjis"); + + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LanguageSkill", b => + { + b.Navigation("Lessons"); + + b.Navigation("MockTestSections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNote", b => + { + b.Navigation("LearnerNoteEntries"); + + b.Navigation("Pages"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.LearnerNoteEntry", b => + { + b.Navigation("ReviewCards"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Lesson", b => + { + b.Navigation("HomeworkAssignmentLessons"); + + b.Navigation("LessonGrammars"); + + b.Navigation("LessonKanjis"); + + b.Navigation("LessonProgresses"); + + b.Navigation("LessonVocabularies"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorAvailability", b => + { + b.Navigation("MentorBookings"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorBooking", b => + { + b.Navigation("Note"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorCreditGrant", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorDispute", b => + { + b.Navigation("Histories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutObligation", b => + { + b.Navigation("Attempts"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayrollPeriod", b => + { + b.Navigation("Adjustments"); + + b.Navigation("Lines"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorSchedule", b => + { + b.Navigation("Rules"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTeachingProposal", b => + { + b.Navigation("Events"); + + b.Navigation("GeneratedAvailabilities"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => + { + b.Navigation("Slots"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockQuestion", b => + { + b.Navigation("Answers"); + + b.Navigation("Options"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTest", b => + { + b.Navigation("Sections"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestAttempt", b => + { + b.Navigation("Answers"); + + b.Navigation("SectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.MockTestSection", b => + { + b.Navigation("Passages"); + + b.Navigation("Questions"); + + b.Navigation("SectionResults"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookFolder", b => + { + b.Navigation("Files"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.NotebookPage", b => + { + b.Navigation("SavedItems"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExercise", b => + { + b.Navigation("Attempts"); + + b.Navigation("Questions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeExerciseAttempt", b => + { + b.Navigation("Answers"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeQuestion", b => + { + b.Navigation("Answers"); + + b.Navigation("Options"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.PracticeSubmission", b => + { + b.Navigation("GradingResult"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ReviewCard", b => + { + b.Navigation("ReviewHistories"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCohort", b => + { + b.Navigation("Enrollments"); + + b.Navigation("Sessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.StudyCourse", b => + { + b.Navigation("Audit"); + + b.Navigation("Homework"); + + b.Navigation("RetakeRequests"); + + b.Navigation("Sessions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.SubscriptionPlan", b => + { + b.Navigation("UserSubscriptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Topic", b => + { + b.Navigation("Lessons"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserAccount", b => + { + b.Navigation("AiCreditTopUps"); + + b.Navigation("AuthoredGrammarPatterns"); + + b.Navigation("AuthoredKanjis"); + + b.Navigation("AuthoredLessons"); + + b.Navigation("AuthoredMockTests"); + + b.Navigation("AuthoredVocabularies"); + + b.Navigation("EmailVerifications"); + + b.Navigation("LearnerEssays"); + + b.Navigation("LearnerNotes"); + + b.Navigation("LessonProgresses"); + + b.Navigation("MentorAvailabilities"); + + b.Navigation("MentorProfile"); + + b.Navigation("MockTestAttempts"); + + b.Navigation("Notes"); + + b.Navigation("Notifications"); + + b.Navigation("PracticeSubmissions"); + + b.Navigation("RecommendedLearningPaths"); + + b.Navigation("ReviewCards"); + + b.Navigation("UserSubscriptions"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.UserSubscription", b => + { + b.Navigation("MentorBookings"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.Vocabulary", b => + { + b.Navigation("ContentLevelMappings"); + + b.Navigation("LearnerNoteEntries"); + + b.Navigation("LessonVocabularies"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.cs b/RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.cs new file mode 100644 index 0000000..8833a0f --- /dev/null +++ b/RikiPath.Infrastructure/Migrations/20261201123934_AddMentorKpiPolicyAndTimesheetAdjustments.cs @@ -0,0 +1,129 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace RikiPath.Infrastructure.Migrations +{ + /// + public partial class AddMentorKpiPolicyAndTimesheetAdjustments : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MentorKpiPolicies", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Version = table.Column(type: "integer", nullable: false), + EffectiveFromMonth = table.Column(type: "date", nullable: false), + MinimumPresencePercent = table.Column(type: "numeric(5,2)", precision: 5, scale: 2, nullable: false), + TeachingCompletionTargetPercent = table.Column(type: "numeric(5,2)", precision: 5, scale: 2, nullable: false), + HomeworkMinimumCount = table.Column(type: "integer", nullable: false), + HomeworkPerSessionCount = table.Column(type: "integer", nullable: false), + GradingCompletionTargetPercent = table.Column(type: "numeric(5,2)", precision: 5, scale: 2, nullable: false), + ResponseSlaHours = table.Column(type: "integer", nullable: false), + OnTimeResponseTargetPercent = table.Column(type: "numeric(5,2)", precision: 5, scale: 2, nullable: false), + AverageRatingTarget = table.Column(type: "numeric(3,2)", precision: 3, scale: 2, nullable: false), + PositiveReviewTargetPercent = table.Column(type: "numeric(5,2)", precision: 5, scale: 2, nullable: false), + Note = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + CreatedByAdminId = table.Column(type: "integer", nullable: true), + CreatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + IsDeleted = table.Column(type: "boolean", nullable: false), + DeletedAtUtc = table.Column(type: "timestamp with time zone", nullable: true), + DeletedByAdminId = table.Column(type: "integer", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MentorKpiPolicies", x => x.Id); + table.CheckConstraint("CK_MentorKpiPolicy_Homework", "\"HomeworkMinimumCount\" >= 0 AND \"HomeworkPerSessionCount\" > 0"); + table.CheckConstraint("CK_MentorKpiPolicy_Month", "EXTRACT(DAY FROM \"EffectiveFromMonth\") = 1"); + table.CheckConstraint("CK_MentorKpiPolicy_Percents", "\"MinimumPresencePercent\" > 0 AND \"MinimumPresencePercent\" <= 100 AND \"TeachingCompletionTargetPercent\" > 0 AND \"TeachingCompletionTargetPercent\" <= 100 AND \"GradingCompletionTargetPercent\" > 0 AND \"GradingCompletionTargetPercent\" <= 100 AND \"OnTimeResponseTargetPercent\" > 0 AND \"OnTimeResponseTargetPercent\" <= 100 AND \"PositiveReviewTargetPercent\" > 0 AND \"PositiveReviewTargetPercent\" <= 100"); + table.CheckConstraint("CK_MentorKpiPolicy_Rating", "\"AverageRatingTarget\" >= 1 AND \"AverageRatingTarget\" <= 5"); + table.CheckConstraint("CK_MentorKpiPolicy_Sla", "\"ResponseSlaHours\" > 0"); + table.ForeignKey( + name: "FK_MentorKpiPolicies_Users_CreatedByAdminId", + column: x => x.CreatedByAdminId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "MentorTimesheetAdjustments", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + CohortSessionId = table.Column(type: "integer", nullable: false), + MentorId = table.Column(type: "integer", nullable: false), + PreviousStatus = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + NewStatus = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + PreviousConfirmedMinutes = table.Column(type: "integer", nullable: false), + NewConfirmedMinutes = table.Column(type: "integer", nullable: false), + Reason = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: false), + Evidence = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + AdminId = table.Column(type: "integer", nullable: false), + CreatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MentorTimesheetAdjustments", x => x.Id); + table.CheckConstraint("CK_MentorTimesheetAdjustment_Minutes", "\"NewConfirmedMinutes\" >= 0 AND \"PreviousConfirmedMinutes\" >= 0"); + table.CheckConstraint("CK_MentorTimesheetAdjustment_Status", "\"NewStatus\" IN ('Taught', 'Absent')"); + table.ForeignKey( + name: "FK_MentorTimesheetAdjustments_StudyCohortSessions_CohortSessio~", + column: x => x.CohortSessionId, + principalTable: "StudyCohortSessions", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.InsertData( + table: "MentorKpiPolicies", + columns: new[] { "Id", "AverageRatingTarget", "CreatedAtUtc", "CreatedByAdminId", "DeletedAtUtc", "DeletedByAdminId", "EffectiveFromMonth", "GradingCompletionTargetPercent", "HomeworkMinimumCount", "HomeworkPerSessionCount", "IsDeleted", "MinimumPresencePercent", "Note", "OnTimeResponseTargetPercent", "PositiveReviewTargetPercent", "ResponseSlaHours", "TeachingCompletionTargetPercent", "Version" }, + values: new object[] { 1, 4m, new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), null, null, null, new DateOnly(2026, 1, 1), 90m, 1, 2, false, 80m, "Phiên bản khởi tạo", 90m, 80m, 24, 90m, 1 }); + + migrationBuilder.CreateIndex( + name: "IX_MentorKpiPolicies_CreatedByAdminId", + table: "MentorKpiPolicies", + column: "CreatedByAdminId"); + + migrationBuilder.CreateIndex( + name: "IX_MentorKpiPolicies_EffectiveFromMonth", + table: "MentorKpiPolicies", + column: "EffectiveFromMonth", + unique: true, + filter: "\"IsDeleted\" = FALSE"); + + migrationBuilder.CreateIndex( + name: "IX_MentorKpiPolicies_Version", + table: "MentorKpiPolicies", + column: "Version", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_MentorTimesheetAdjustments_CohortSessionId_CreatedAtUtc", + table: "MentorTimesheetAdjustments", + columns: new[] { "CohortSessionId", "CreatedAtUtc" }); + + migrationBuilder.CreateIndex( + name: "IX_MentorTimesheetAdjustments_MentorId", + table: "MentorTimesheetAdjustments", + column: "MentorId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MentorKpiPolicies"); + + migrationBuilder.DropTable( + name: "MentorTimesheetAdjustments"); + } + } +} diff --git a/RikiPath.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/RikiPath.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 47e9450..ba8d835 100644 --- a/RikiPath.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/RikiPath.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -810,6 +810,129 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CertificateLevelId") + .HasColumnType("integer"); + + b.Property("CohortId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DueAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("PublishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("QuestionCount") + .HasColumnType("integer"); + + b.Property("QuestionSnapshotJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Revision") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.Property("SkillCodes") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("StructureKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CertificateLevelId"); + + b.HasIndex("MentorId"); + + b.HasIndex("CohortId", "IsDeleted", "DueAtUtc"); + + b.ToTable("ClassQuizzes", null, t => + { + t.HasCheckConstraint("CK_ClassQuiz_QuestionCount", "\"QuestionCount\" BETWEEN 1 AND 200"); + + t.HasCheckConstraint("CK_ClassQuiz_Status", "\"Status\" IN ('Published','Cancelled')"); + + t.HasCheckConstraint("CK_ClassQuiz_TimeLimit", "\"TimeLimitMinutes\" BETWEEN 1 AND 240"); + }); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AssignedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AttemptId") + .HasColumnType("integer"); + + b.Property("CompletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("integer"); + + b.Property("LearnerId") + .HasColumnType("integer"); + + b.Property("QuizId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AttemptId") + .IsUnique() + .HasFilter("\"AttemptId\" IS NOT NULL"); + + b.HasIndex("EnrollmentId"); + + b.HasIndex("LearnerId", "EnrollmentId"); + + b.HasIndex("QuizId", "LearnerId") + .IsUnique(); + + b.ToTable("ClassQuizAssignments", (string)null); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => { b.Property("Id") @@ -6603,6 +6726,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("PlacementAttemptLimit") .HasColumnType("integer"); + b.Property("RemediationAttendanceThresholdPercent") + .ValueGeneratedOnAdd() + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)") + .HasDefaultValue(90m); + b.Property("RemediationCompletionThresholdPercent") .HasPrecision(5, 2) .HasColumnType("numeric(5,2)"); @@ -6624,6 +6753,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("RestMinutes") .HasColumnType("integer"); + b.Property("RetakeSupportEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + b.Property("Revision") .IsConcurrencyToken() .HasColumnType("integer"); @@ -6697,6 +6831,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("CK_MentorGroupPolicy_Remediation", "\"RemediationCompletionThresholdPercent\" > 0 AND \"RemediationCompletionThresholdPercent\" <= 100"); + t.HasCheckConstraint("CK_MentorGroupPolicy_RemediationAttendance", "\"RemediationAttendanceThresholdPercent\" > 0 AND \"RemediationAttendanceThresholdPercent\" <= 100"); + t.HasCheckConstraint("CK_MentorGroupPolicy_ReplacementLead", "\"MentorReplacementLeadHours\" BETWEEN 0 AND 720"); t.HasCheckConstraint("CK_MentorGroupPolicy_State", "\"Revision\" > 0 AND NOT (\"IsActive\" AND (\"IsArchivedRevision\" OR \"IsDeleted\"))"); @@ -6727,12 +6863,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) MinimumPreparationDays = 1, MinimumPublishedEnrollmentDays = 7, PlacementAttemptLimit = 2, + RemediationAttendanceThresholdPercent = 90m, RemediationCompletionThresholdPercent = 90m, RemediationThresholdComparison = ">", RequireAdminRemediationReview = true, RequireOfficialExamEvidence = true, ReschedulingLeadHours = 24, RestMinutes = 15, + RetakeSupportEnabled = true, Revision = 1, SessionMinutes = 90, TransferAllowedAfterSourceStart = false, @@ -6786,6 +6924,117 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorKpiPolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AverageRatingTarget") + .HasPrecision(3, 2) + .HasColumnType("numeric(3,2)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByAdminId") + .HasColumnType("integer"); + + b.Property("DeletedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DeletedByAdminId") + .HasColumnType("integer"); + + b.Property("EffectiveFromMonth") + .HasColumnType("date"); + + b.Property("GradingCompletionTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("HomeworkMinimumCount") + .HasColumnType("integer"); + + b.Property("HomeworkPerSessionCount") + .HasColumnType("integer"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("MinimumPresencePercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OnTimeResponseTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("PositiveReviewTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("ResponseSlaHours") + .HasColumnType("integer"); + + b.Property("TeachingCompletionTargetPercent") + .HasPrecision(5, 2) + .HasColumnType("numeric(5,2)"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByAdminId"); + + b.HasIndex("EffectiveFromMonth") + .IsUnique() + .HasFilter("\"IsDeleted\" = FALSE"); + + b.HasIndex("Version") + .IsUnique(); + + b.ToTable("MentorKpiPolicies", null, t => + { + t.HasCheckConstraint("CK_MentorKpiPolicy_Homework", "\"HomeworkMinimumCount\" >= 0 AND \"HomeworkPerSessionCount\" > 0"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Month", "EXTRACT(DAY FROM \"EffectiveFromMonth\") = 1"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Percents", "\"MinimumPresencePercent\" > 0 AND \"MinimumPresencePercent\" <= 100 AND \"TeachingCompletionTargetPercent\" > 0 AND \"TeachingCompletionTargetPercent\" <= 100 AND \"GradingCompletionTargetPercent\" > 0 AND \"GradingCompletionTargetPercent\" <= 100 AND \"OnTimeResponseTargetPercent\" > 0 AND \"OnTimeResponseTargetPercent\" <= 100 AND \"PositiveReviewTargetPercent\" > 0 AND \"PositiveReviewTargetPercent\" <= 100"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Rating", "\"AverageRatingTarget\" >= 1 AND \"AverageRatingTarget\" <= 5"); + + t.HasCheckConstraint("CK_MentorKpiPolicy_Sla", "\"ResponseSlaHours\" > 0"); + }); + + b.HasData( + new + { + Id = 1, + AverageRatingTarget = 4m, + CreatedAtUtc = new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), + EffectiveFromMonth = new DateOnly(2026, 1, 1), + GradingCompletionTargetPercent = 90m, + HomeworkMinimumCount = 1, + HomeworkPerSessionCount = 2, + IsDeleted = false, + MinimumPresencePercent = 80m, + Note = "Phiên bản khởi tạo", + OnTimeResponseTargetPercent = 90m, + PositiveReviewTargetPercent = 80m, + ResponseSlaHours = 24, + TeachingCompletionTargetPercent = 90m, + Version = 1 + }); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorOutboxEvent", b => { b.Property("Id") @@ -7743,6 +7992,65 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTimesheetAdjustment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdminId") + .HasColumnType("integer"); + + b.Property("CohortSessionId") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Evidence") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("MentorId") + .HasColumnType("integer"); + + b.Property("NewConfirmedMinutes") + .HasColumnType("integer"); + + b.Property("NewStatus") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("PreviousConfirmedMinutes") + .HasColumnType("integer"); + + b.Property("PreviousStatus") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.HasKey("Id"); + + b.HasIndex("MentorId"); + + b.HasIndex("CohortSessionId", "CreatedAtUtc"); + + b.ToTable("MentorTimesheetAdjustments", null, t => + { + t.HasCheckConstraint("CK_MentorTimesheetAdjustment_Minutes", "\"NewConfirmedMinutes\" >= 0 AND \"PreviousConfirmedMinutes\" >= 0"); + + t.HasCheckConstraint("CK_MentorTimesheetAdjustment_Status", "\"NewStatus\" IN ('Taught', 'Absent')"); + }); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => { b.Property("Id") @@ -11568,6 +11876,67 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("CertificateLevel"); }); + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.HasOne("RikiPath.Domain.Entities.CertificateLevel", "CertificateLevel") + .WithMany() + .HasForeignKey("CertificateLevelId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") + .WithMany() + .HasForeignKey("CohortId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") + .WithMany() + .HasForeignKey("MentorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CertificateLevel"); + + b.Navigation("Cohort"); + + b.Navigation("Mentor"); + }); + + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuizAssignment", b => + { + b.HasOne("RikiPath.Domain.Entities.MockTestAttempt", "Attempt") + .WithMany() + .HasForeignKey("AttemptId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("RikiPath.Domain.Entities.StudyCourse", "Enrollment") + .WithMany() + .HasForeignKey("EnrollmentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.UserAccount", "Learner") + .WithMany() + .HasForeignKey("LearnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("RikiPath.Domain.Entities.ClassQuiz", "Quiz") + .WithMany("Assignments") + .HasForeignKey("QuizId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Attempt"); + + b.Navigation("Enrollment"); + + b.Navigation("Learner"); + + b.Navigation("Quiz"); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => { b.HasOne("RikiPath.Domain.Entities.StudyCohort", "Cohort") @@ -12855,6 +13224,16 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("MentorUser"); }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorKpiPolicy", b => + { + b.HasOne("RikiPath.Domain.Entities.UserAccount", "CreatedByAdmin") + .WithMany() + .HasForeignKey("CreatedByAdminId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("CreatedByAdmin"); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorPayoutAttempt", b => { b.HasOne("RikiPath.Domain.Entities.UserAccount", "ConfirmedByAdmin") @@ -13138,6 +13517,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("VerifiedByAdmin"); }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorTimesheetAdjustment", b => + { + b.HasOne("RikiPath.Domain.Entities.StudyCohortSession", "CohortSession") + .WithMany() + .HasForeignKey("CohortSessionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("CohortSession"); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.MentorWeeklyAvailability", b => { b.HasOne("RikiPath.Domain.Entities.UserAccount", "Mentor") @@ -13933,6 +14323,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Levels"); }); + modelBuilder.Entity("RikiPath.Domain.Entities.ClassQuiz", b => + { + b.Navigation("Assignments"); + }); + modelBuilder.Entity("RikiPath.Domain.Entities.CohortComplaint", b => { b.Navigation("History"); diff --git a/RikiPath.Infrastructure/Repositories/MockTestAttemptRepository.cs b/RikiPath.Infrastructure/Repositories/MockTestAttemptRepository.cs index fb55372..733c850 100644 --- a/RikiPath.Infrastructure/Repositories/MockTestAttemptRepository.cs +++ b/RikiPath.Infrastructure/Repositories/MockTestAttemptRepository.cs @@ -95,7 +95,7 @@ public async Task> GetPlacementByUserAsync( .FirstOrDefaultAsync(x => x.Id == attemptId, cancellationToken); } - if (attempt is null || attempt.AttemptKind != AttemptKind.Placement) + if (attempt is null || attempt.AttemptKind is not (AttemptKind.Placement or AttemptKind.CourseAssessment)) { return null; } diff --git a/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs b/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs index 50133d3..d971180 100644 --- a/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs +++ b/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs @@ -94,7 +94,7 @@ public bool TryGetContentReference(string reference, out string canonicalUrl) // A filename in Excel is resolved against the selected directory, never guessed as an S3 object. if (!Uri.TryCreate(reference, UriKind.Absolute, out var uri) || uri.Scheme is not ("s3" or "https" or "http") || !TryGetObjectKey(reference, out var key) || IsPrivateKey(key) || - !key.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) return false; + (!key.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) && !key.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))) return false; var prefix = Settings.ContentPrefix.Trim('/') + "/"; if (key.StartsWith(prefix, StringComparison.Ordinal)) { diff --git a/RikiPath.Infrastructure/Services/CohortEnrollmentDeadlineService.cs b/RikiPath.Infrastructure/Services/CohortEnrollmentDeadlineService.cs index 4bab287..f31ddc9 100644 --- a/RikiPath.Infrastructure/Services/CohortEnrollmentDeadlineService.cs +++ b/RikiPath.Infrastructure/Services/CohortEnrollmentDeadlineService.cs @@ -515,7 +515,7 @@ private void MarkPendingPaymentForAdminReview( { CourseId = course.Id, Action = "PaidEnrollmentUnresolved", - Detail = "Thanh toán được ghi nhận sau khi đóng tuyển sinh; chuyển Quản trị viên xem xét hoàn tiền hoặc chuyển lớp.", + Detail = "Thanh toán được ghi nhận sau khi đóng tuyển sinh; chuyển Quản trị viên xem xét hoàn tiền hoặc hỗ trợ học viên.", At = nowUtc, }); @@ -536,7 +536,7 @@ private void MarkPendingPaymentForAdminReview( { UserId = adminId, Title = "Giao dịch ghi danh cần xem xét", - Message = $"Có giao dịch thanh toán muộn khi đóng tuyển sinh lớp học. Vui lòng xem xét hoàn tiền hoặc chuyển lớp.", + Message = $"Có giao dịch thanh toán muộn khi đóng tuyển sinh lớp học. Vui lòng xem xét hoàn tiền hoặc liên hệ hỗ trợ học viên.", Type = "PaymentReview", LinkUrl = $"/admin/payments?stream=study_course&id={course.Id}", }); diff --git a/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs b/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs index ad02387..c219d95 100644 --- a/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs +++ b/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs @@ -24,8 +24,9 @@ public async Task UploadAsync( Stream audio, string fileName, int authorId, CancellationToken ct) { if (authorId <= 0) throw new ArgumentException("Không xác định được người tải audio."); - if (!Path.GetExtension(fileName).Equals(".mp3", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException("Vui lòng chọn file MP3."); + var extension = Path.GetExtension(fileName); + if (!ListeningAudioFilePolicy.IsSupportedExtension(extension)) + throw new ArgumentException("Vui lòng chọn file MP3 hoặc WAV."); await using var buffered = new MemoryStream(); var buffer = new byte[81920]; @@ -33,14 +34,15 @@ public async Task UploadAsync( while ((count = await audio.ReadAsync(buffer, ct)) > 0) { if (buffered.Length + count > ListeningAudioFilePolicy.MaxBytes) - throw new ArgumentException("File MP3 không được vượt quá 500 MB."); + throw new ArgumentException("File âm thanh không được vượt quá 500 MB."); await buffered.WriteAsync(buffer.AsMemory(0, count), ct); } buffered.Position = 0; - if (!await ListeningAudioFilePolicy.HasMp3HeaderAsync(buffered, ct)) - throw new ArgumentException("File nghe không có định dạng MP3 hợp lệ."); + if (!await ListeningAudioFilePolicy.HasSupportedAudioHeaderAsync(buffered, fileName, ct)) + throw new ArgumentException("File nghe không có định dạng MP3 hoặc WAV hợp lệ."); buffered.Position = 0; - var uploaded = await files.UploadAsync(buffered, fileName, "audio/mpeg", "jlpt-listening", ct); + var contentType = ListeningAudioFilePolicy.GetContentType(extension); + var uploaded = await files.UploadAsync(buffered, fileName, contentType, "jlpt-listening", ct); try { var transcription = await QueueAsync(uploaded.Url, authorId, ct) @@ -254,7 +256,7 @@ await db.ContentAudioTranscriptions.Where(x => x.Id == item.Id && x.LeaseId == l .SetProperty(x => x.ErrorCode, code) .SetProperty(x => x.ErrorMessage, code == "AUDIO_TRANSCRIPTION_ACCESS_DENIED" ? "AWS chưa cấp đủ quyền đọc audio hoặc nhận dạng tiếng Nhật." - : "Chưa nhận dạng được audio. Kiểm tra file MP3 và cấu hình AWS rồi thử lại.") + : "Chưa nhận dạng được audio. Kiểm tra file âm thanh (MP3/WAV) và cấu hình AWS rồi thử lại.") .SetProperty(x => x.NextAttemptAtUtc, now) .SetProperty(x => x.UpdatedAtUtc, now).SetProperty(x => x.LeaseId, (Guid?)null) .SetProperty(x => x.LeaseExpiresAtUtc, (DateTime?)null), ct); @@ -283,7 +285,7 @@ private ContentAudioTranscriptionResponse Response(ContentAudioTranscription ite uri.Query.Length != 0 || uri.Fragment.Length != 0 || uri.AbsoluteUri.Length > 2048 || !uri.AbsolutePath.StartsWith("/storage/v1/object/public/" + Uri.EscapeDataString(settings.Supabase.Bucket) + "/", StringComparison.Ordinal) || - !uri.AbsolutePath.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) + !ListeningAudioFilePolicy.IsSupportedExtension(Path.GetExtension(uri.AbsolutePath))) return null; return uri.AbsoluteUri; } diff --git a/RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs b/RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs new file mode 100644 index 0000000..38923f1 --- /dev/null +++ b/RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs @@ -0,0 +1,2122 @@ +using System.Globalization; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using RikiPath.Application; +using RikiPath.Application.Helpers; +using RikiPath.Application.IServices; +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.Content; +using RikiPath.Application.Services; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Infrastructure.Services; + +/// +/// Imports the RikiPath Unified Content V2 + N5–N2 Resource ZIP packages strictly as Draft items +/// in dependency order with deterministic identity keys, idempotent duplicate detection, and asset upload. +/// +public sealed class CurriculumPackageImportService( + IUnitOfWork unitOfWork, + IFileStorageService fileStorage, + IConfiguration configuration, + ILogger logger, + IContentAudioTranscriptionService? audioTranscriptions = null) : ICurriculumPackageImportService +{ + private const string SystemZipName = "RIKIPATH_SYSTEM_INTEGRATION.zip"; + private const string SourceTypeTag = "CurriculumV2"; + private const string PendingRightsStatus = "Pending"; + private static readonly string[] SupportedLevels = ["N5", "N4", "N3", "N2"]; + private static readonly JsonSerializerOptions PascalJson = new(); + private static readonly Regex PythonListRegex = new(@"^\[(.*)\]$", RegexOptions.Compiled | RegexOptions.Singleline); + + private static readonly (string FileName, string? LevelCode)[] ExpectedArchives = + [ + (SystemZipName, null), + ("RIKIPATH_N5_RESOURCES.zip", "N5"), + ("RIKIPATH_N4_RESOURCES.zip", "N4"), + ("RIKIPATH_N3_RESOURCES.zip", "N3"), + ("RIKIPATH_N2_RESOURCES.zip", "N2"), + ]; + + public async Task> GetInventoryAsync(CancellationToken cancellationToken) + { + var root = FindResourcesDirectory(); + var response = new CurriculumPackageInventoryResponse + { + PackageRootFound = root is not null, + PackageRootDisplay = root is null ? null : Path.GetFileName(root), + }; + + if (root is null) + { + response.Warnings.Add("Không tìm thấy thư mục resources chứa gói dữ liệu RIKIPATH_SYSTEM_INTEGRATION.zip."); + return ApiResponse.Success(response); + } + + foreach (var (fileName, levelCode) in ExpectedArchives) + { + var fullPath = Path.Combine(root, fileName); + response.Archives.Add(InspectArchive(fullPath, fileName, levelCode)); + } + + var systemZipPath = Path.Combine(root, SystemZipName); + if (!File.Exists(systemZipPath)) + { + response.Warnings.Add($"Thiếu tệp chính {SystemZipName}."); + return ApiResponse.Success(response); + } + + var dbSnapshot = await LoadDatabaseSnapshotAsync(cancellationToken); + using var systemZip = ZipFile.OpenRead(systemZipPath); + var entries = IndexSafeEntries(systemZip); + + var assetRows = LoadAssetMappings(systemZip, entries); + var srsNodes = ReadJsonArray(systemZip, entries, "01_CORE_COMPATIBLE_DATA/GLOBAL/srs_card_templates.json"); + response.TotalGlobalSrsTemplates = srsNodes.Count; + + foreach (var lvl in SupportedLevels) + { + dbSnapshot.LevelIdByCode.TryGetValue(lvl, out var levelId); + var topics = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/topics.json"); + var lessons = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/lessons.json"); + var vocabs = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/vocabulary.json"); + var kanjis = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/kanji.json"); + var grammars = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/grammar_patterns.json"); + var practices = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/practice_exercises.json"); + var mocks = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/mock_tests_public.json"); + + var lessonCountByTopic = lessons + .GroupBy(l => Str(l, "topicExternalId") ?? "", StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + + var levelAssets = assetRows.Where(a => a.Level.Equals(lvl, StringComparison.OrdinalIgnoreCase)).ToList(); + var levelSrsCount = srsNodes.Count(s => string.Equals(Str(s, "firstIntroducedLevel"), lvl, StringComparison.OrdinalIgnoreCase)); + + response.Levels.Add(new CurriculumPackageLevelSummary + { + LevelCode = lvl, + CertificateLevelId = levelId > 0 ? levelId : null, + TopicCount = topics.Count, + LessonCount = lessons.Count, + VocabularyCount = vocabs.Count, + KanjiCount = kanjis.Count, + GrammarCount = grammars.Count, + PracticeExerciseCount = practices.Count, + MockTestCount = mocks.Count, + AudioCount = levelAssets.Count(a => a.AssetType.Contains("WAV", StringComparison.OrdinalIgnoreCase)), + ImageCount = levelAssets.Count(a => a.AssetType.Contains("IMAGE", StringComparison.OrdinalIgnoreCase)), + SrsTemplateCount = levelSrsCount, + }); + + foreach (var t in topics.OrderBy(x => IntVal(x, "orderIndex"))) + { + var topicCode = Str(t, "externalStableId") ?? ""; + var chapterLessons = lessonCountByTopic.GetValueOrDefault(topicCode) ?? []; + var publishedCount = 0; + var draftCount = 0; + + foreach (var cl in chapterLessons) + { + var extId = Str(cl, "externalStableId") ?? ""; + var title = Truncate(Str(cl, "titleVi") ?? extId, 300); + var prov = $"{SourceTypeTag}:{extId}"; + if (dbSnapshot.Lessons.Any(l => + l.SourceProvenance == prov || + (levelId > 0 && l.CertificateLevelId == levelId && l.Title.Equals(title, StringComparison.OrdinalIgnoreCase)))) + { + publishedCount++; + } + else if (dbSnapshot.OpenOrApprovedRowKeys.Contains((ImportEntityType.Lesson, extId))) + { + draftCount++; + } + } + + response.Chapters.Add(new CurriculumPackageChapterInfo + { + LevelCode = lvl, + TopicCode = topicCode, + OrderIndex = IntVal(t, "orderIndex"), + TitleVi = Str(t, "titleVi") ?? topicCode, + TitleJa = Str(t, "titleJa"), + Description = Str(t, "description"), + LessonCount = chapterLessons.Count, + ExistingPublishedLessonCount = publishedCount, + ExistingDraftCount = draftCount, + }); + } + } + + return ApiResponse.Success(response); + } + + public async Task> PreviewAsync( + CurriculumPackagePreviewRequest request, + CancellationToken cancellationToken) + { + var root = FindResourcesDirectory(); + if (root is null || !File.Exists(Path.Combine(root, SystemZipName))) + return ApiResponse.Fail("Không tìm thấy gói giáo trình hợp lệ trong thư mục resources."); + + var scope = NormalizeScope(request.Levels, request.TopicCodes, request.MockTestIds, + request.IncludeLessons, request.IncludeVocabKanjiGrammar, request.IncludePracticeExercises, + request.IncludeSrsTemplates, request.IncludeMockTests, request.UploadAssets); + + var built = await BuildPackageCandidatesAsync(root, scope, uploadAssets: false, actorUserId: 0, cancellationToken); + + var pageSize = Math.Clamp(request.PageSize <= 0 ? 25 : request.PageSize, 5, 200); + var totalPages = Math.Max(1, (int)Math.Ceiling(built.Items.Count / (double)pageSize)); + var page = Math.Clamp(request.Page <= 0 ? 1 : request.Page, 1, totalPages); + + var pagedItems = built.Items + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(x => x.Preview) + .ToList(); + + var response = new CurriculumPackagePreviewResponse + { + SelectedLevels = scope.Levels, + SelectedTopicCodes = scope.TopicCodes.ToList(), + TotalItems = built.Items.Count, + NewCount = built.Items.Count(x => x.Preview.Action == "New"), + ExistingCount = built.Items.Count(x => x.Preview.Action == "Existing"), + ModifiedCount = built.Items.Count(x => x.Preview.Action == "Modified"), + WarningCount = built.Issues.Count(i => i.Severity == "Warning"), + ErrorCount = built.Issues.Count(i => i.Severity == "Error"), + AudioAssetCount = built.ReferencedAudioKeys.Count, + ImageAssetCount = built.ReferencedImageKeys.Count, + CanConfirm = built.Items.Any(x => x.CanStage && x.Preview.Action != "Existing") && built.Issues.All(i => i.Severity != "Error"), + ByEntityType = built.Items + .GroupBy(x => x.Preview.EntityType) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase), + DependencyOrder = + [ + "1. Chủ đề & Bài học (Topic / Lesson)", + "2. Từ vựng, Hán tự, Ngữ pháp & Liên kết bài học", + "3. Bài luyện tập nhanh & Kiểm tra cuối chặng", + "4. Thẻ mẫu SRS", + "5. Đề thi thử JLPT chuẩn (MockTest + Passage + Audio/Illustration)", + ], + Issues = built.Issues.Take(100).ToList(), + Page = page, + PageSize = pageSize, + TotalPages = totalPages, + Items = pagedItems, + }; + + return ApiResponse.Success(response); + } + + public async Task> ConfirmAsync( + CurriculumPackageConfirmRequest request, + int actorUserId, + CancellationToken cancellationToken) + { + if (actorUserId <= 0) + return ApiResponse.Fail("Không xác định được tài khoản tác giả nội dung."); + + var root = FindResourcesDirectory(); + if (root is null || !File.Exists(Path.Combine(root, SystemZipName))) + return ApiResponse.Fail("Không tìm thấy gói giáo trình hợp lệ trong thư mục resources."); + + if (!string.IsNullOrWhiteSpace(request.IdempotencyKey)) + { + var idemKey = Truncate(request.IdempotencyKey.Trim(), 100); + var existingByIdem = await unitOfWork.ContentApprovalRequests.Query() + .AsNoTracking() + .Where(x => !x.IsDeleted && x.SubmittedByUserId == actorUserId && x.IdempotencyKey == idemKey) + .ToListAsync(cancellationToken); + if (existingByIdem.Count > 0) + { + return ApiResponse.Success(new CurriculumPackageConfirmResponse + { + BatchId = existingByIdem[0].BatchId, + Status = "Draft", + PublishedReady = false, + RightsStatus = PendingRightsStatus, + DraftsCreatedCount = 0, + SkippedExistingCount = existingByIdem.Count, + CreatedRequestIds = existingByIdem.Select(x => x.Id).ToList(), + ByEntityType = existingByIdem.GroupBy(x => x.EntityType.ToString()) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase), + Warnings = ["Yêu cầu đã được xử lý trước đó (IdempotencyKey trùng khớp). Không tạo bản sao mới."], + }); + } + } + + var scope = NormalizeScope(request.Levels, request.TopicCodes, request.MockTestIds, + request.IncludeLessons, request.IncludeVocabKanjiGrammar, request.IncludePracticeExercises, + request.IncludeSrsTemplates, request.IncludeMockTests, request.UploadAssets); + + var built = await BuildPackageCandidatesAsync(root, scope, scope.UploadAssets, actorUserId, cancellationToken); + var fatalErrors = built.Issues.Where(i => i.Severity == "Error").ToList(); + if (fatalErrors.Count > 0) + { + return ApiResponse.Fail( + $"Phát hiện {fatalErrors.Count} lỗi cấu trúc gói dữ liệu: {fatalErrors[0].Target} — {fatalErrors[0].Message}"); + } + + var batchId = Guid.NewGuid(); + var now = DateTime.UtcNow; + var scopeLabel = scope.TopicCodes.Count > 0 + ? $"{string.Join(",", scope.Levels)}:{string.Join(",", scope.TopicCodes.Take(4))}" + : string.Join(",", scope.Levels); + var sourceFileName = Truncate($"CurriculumV2:{scopeLabel}", 260); + var trimmedIdemKey = string.IsNullOrWhiteSpace(request.IdempotencyKey) ? null : Truncate(request.IdempotencyKey.Trim(), 100); + + var drafts = new List(); + var skippedCount = 0; + + foreach (var candidate in built.Items) + { + if (!candidate.CanStage || candidate.Action == ImportRowAction.Unchanged || candidate.PayloadJson is null) + { + skippedCount++; + continue; + } + + var key = Truncate(candidate.Preview.RowKey, 500); + if (built.Snapshot.OpenOrApprovedRowKeys.Contains((candidate.EntityType, key))) + { + skippedCount++; + continue; + } + if (candidate.TargetEntityId.HasValue && + built.Snapshot.OpenTargetIds.Contains((candidate.EntityType, candidate.TargetEntityId.Value))) + { + skippedCount++; + continue; + } + + built.Snapshot.OpenOrApprovedRowKeys.Add((candidate.EntityType, key)); + if (candidate.TargetEntityId.HasValue) + built.Snapshot.OpenTargetIds.Add((candidate.EntityType, candidate.TargetEntityId.Value)); + + drafts.Add(new ContentApprovalRequest + { + BatchId = batchId, + EntityType = candidate.EntityType, + Action = candidate.Action, + TargetEntityId = candidate.Action == ImportRowAction.Modified ? candidate.TargetEntityId : null, + RowKey = key, + SourceRowNumber = drafts.Count + 1, + SourceFileName = sourceFileName, + SourceType = SourceTypeTag, + SourceReference = Truncate(candidate.Preview.ExternalId, 300), + RightsStatus = PendingRightsStatus, + RightsConfirmed = false, + IdempotencyKey = drafts.Count == 0 ? trimmedIdemKey : null, + PayloadJson = candidate.PayloadJson, + Status = ContentApprovalStatus.Draft, + SubmittedByUserId = actorUserId, + SubmittedAt = now, + }); + } + + if (drafts.Count > 0) + { + await unitOfWork.ContentApprovalRequests.AddRangeAsync(drafts, cancellationToken); + await SyncContentBankDraftsAsync(drafts, actorUserId, batchId, cancellationToken); + await unitOfWork.SaveChangesAsync(cancellationToken); + } + + return ApiResponse.Success(new CurriculumPackageConfirmResponse + { + BatchId = batchId, + Status = "Draft", + PublishedReady = false, + RightsStatus = PendingRightsStatus, + DraftsCreatedCount = drafts.Count, + SkippedExistingCount = skippedCount, + UploadedAudioCount = built.UploadedAudioCount, + UploadedImageCount = built.UploadedImageCount, + CreatedRequestIds = drafts.Select(d => d.Id).ToList(), + ByEntityType = drafts.GroupBy(d => d.EntityType.ToString()) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase), + Warnings = built.Issues.Where(i => i.Severity == "Warning") + .Select(i => $"{i.Target}: {i.Message}") + .Distinct() + .Take(25) + .ToList(), + }); + } + + private async Task BuildPackageCandidatesAsync( + string resourcesRoot, + PackageScope scope, + bool uploadAssets, + int actorUserId, + CancellationToken ct) + { + var result = new BuiltPackageResult(await LoadDatabaseSnapshotAsync(ct)); + using var systemZip = ZipFile.OpenRead(Path.Combine(resourcesRoot, SystemZipName)); + var sysEntries = IndexSafeEntries(systemZip); + + var pathResolver = ReadAssetMappingsResolver(systemZip, sysEntries); + var csvAssets = LoadAssetMappings(systemZip, sysEntries); + var kaiwaByLesson = LoadKaiwaByLesson(systemZip, sysEntries); + var srsNodes = scope.IncludeSrsTemplates + ? ReadJsonArray(systemZip, sysEntries, "01_CORE_COMPATIBLE_DATA/GLOBAL/srs_card_templates.json") + : []; + + // Open level resource ZIPs lazily as needed. + var resourceZips = new Dictionary Entries, Dictionary ByFileName)>(StringComparer.OrdinalIgnoreCase); + var uploadedUrlCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + + try + { + foreach (var levelCode in scope.Levels) + { + if (!result.Snapshot.LevelIdByCode.TryGetValue(levelCode, out var levelId)) + { + result.Issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Error", + Code = "LEVEL_NOT_FOUND", + Target = levelCode, + Message = $"Cấp độ {levelCode} chưa được kích hoạt trong DB.", + }); + continue; + } + + var topics = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/topics.json"); + var selectedTopics = topics + .Where(t => scope.TopicCodes.Count == 0 || scope.TopicCodes.Contains(Str(t, "externalStableId") ?? "")) + .OrderBy(t => IntVal(t, "orderIndex")) + .ToList(); + var topicMap = selectedTopics.ToDictionary( + t => Str(t, "externalStableId") ?? "", + t => t, + StringComparer.OrdinalIgnoreCase); + + var allLessons = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lessons.json"); + var selectedLessons = allLessons + .Where(l => topicMap.ContainsKey(Str(l, "topicExternalId") ?? "")) + .OrderBy(l => IntVal(l, "orderIndex")) + .ToList(); + var selectedLessonIds = selectedLessons + .Select(l => Str(l, "externalStableId") ?? "") + .Where(id => id.Length > 0) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + var resTuple = OpenLevelResourceZip(resourcesRoot, levelCode, resourceZips); + var richData = ExtractRichCurriculumData(levelCode, resTuple?.Zip, resTuple?.Entries); + + var lessonTitleByExtId = selectedLessons.ToDictionary( + l => Str(l, "externalStableId") ?? "", + l => Truncate(Str(l, "titleVi") ?? Str(l, "externalStableId") ?? "", 300), + StringComparer.OrdinalIgnoreCase); + + var lvLinks = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lesson_vocabulary.json"); + var lkLinks = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lesson_kanji.json"); + var lgLinks = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lesson_grammar.json"); + + var primaryLessonForVocab = FirstLessonLookup(lvLinks, "vocabularyExternalId", selectedLessonIds, lessonTitleByExtId); + var primaryLessonForKanji = FirstLessonLookup(lkLinks, "kanjiExternalId", selectedLessonIds, lessonTitleByExtId); + var primaryLessonForGrammar = FirstLessonLookup(lgLinks, "grammarExternalId", selectedLessonIds, lessonTitleByExtId); + + var assetByLesson = csvAssets + .Where(a => a.Level.Equals(levelCode, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(a.LinkedLessonId)) + .GroupBy(a => a.LinkedLessonId!, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + + // Helper to resolve + optionally upload asset inside the level ZIPs. + async Task<(string? Url, string? LogicalRef)> ResolveMediaAsync(string? logicalOrRelativePath, bool isAudio) + { + if (string.IsNullOrWhiteSpace(logicalOrRelativePath)) return (null, null); + var (zipArchive, entry) = LocateZipEntry(logicalOrRelativePath, levelCode, pathResolver, resourceZips); + if (zipArchive is null || entry is null) + { + result.Issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Warning", + Code = "ASSET_NOT_FOUND", + Target = logicalOrRelativePath, + Message = "Không tìm thấy tệp tài nguyên tương ứng trong gói nén RESOURCES.", + }); + return (null, logicalOrRelativePath); + } + + var cacheKey = $"{zipArchive.GetHashCode()}:{entry.FullName}"; + if (isAudio) result.ReferencedAudioKeys.Add(entry.FullName); + else result.ReferencedImageKeys.Add(entry.FullName); + + if (!uploadAssets) + return (null, entry.FullName); + + if (uploadedUrlCache.TryGetValue(cacheKey, out var cached)) + return (cached, entry.FullName); + + var url = await UploadZipEntryAsync(entry, isAudio, actorUserId, ct); + uploadedUrlCache[cacheKey] = url; + if (isAudio) result.UploadedAudioCount++; + else result.UploadedImageCount++; + return (url, entry.FullName); + } + + // 1. Lessons (Dependency 1 — Lesson creates Topic & links Knowledge + QuickCheck in ContentApprovalService) + var globalSortOffsetByTopic = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (scope.IncludeLessons) + { + var vocabMapForPrompt = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/vocabulary.json") + .GroupBy(v => Str(v, "externalStableId") ?? "", StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + + foreach (var l in selectedLessons) + { + var extId = Str(l, "externalStableId") ?? ""; + var topicExtId = Str(l, "topicExternalId") ?? ""; + topicMap.TryGetValue(topicExtId, out var topicJson); + var topicTitle = Truncate(Str(topicJson, "titleVi") ?? topicExtId, 300); + var title = Truncate(Str(l, "titleVi") ?? extId, 300); + JsonElement? richLesson = richData.LessonsById.TryGetValue(extId, out var rl) ? rl : null; + + var audioPath = assetByLesson.GetValueOrDefault(extId)?.FirstOrDefault(a => a.AssetType.Contains("WAV", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath + ?? FirstResolvedAudio(richLesson); + var (audioUrl, audioDisplay) = await ResolveMediaAsync(audioPath, isAudio: true); + + var lessonImgPath = assetByLesson.GetValueOrDefault(extId)?.FirstOrDefault(a => a.AssetType.Contains("IMAGE", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath; + var (imageUrl, imgDisplay) = await ResolveMediaAsync(lessonImgPath, isAudio: false); + + var orderInChapter = IntVal(l, "orderIndex"); + var chapterOrder = IntVal(topicJson, "orderIndex"); + var globalSort = chapterOrder * 100 + Math.Max(1, orderInChapter); + globalSortOffsetByTopic[topicExtId] = globalSort; + + var prereqTitle = ResolvePrerequisiteTitle(richLesson, lessonTitleByExtId); + var kaiwaList = kaiwaByLesson.GetValueOrDefault(extId) ?? []; + var description = BuildLessonMarkdown(l, richLesson, kaiwaList, vocabMapForPrompt); + var objectives = BuildLearningObjectives(richLesson, l); + + var skillId = ResolveSkillId(result.Snapshot, Str(l, "primaryLanguageSkillRef") ?? Str(l, "lessonType")); + var payload = new LessonImportPayloadResponse + { + Title = title, + Description = description, + AudioUrl = audioUrl, + ImageUrl = imageUrl, + SortOrder = globalSort, + EstimatedMinutes = Math.Max(10, IntVal(richLesson, "estimatedDurationMinutes", 25)), + LearningObjectives = TruncateNullable(objectives, 1000), + PrerequisiteLessonTitle = prereqTitle, + SourceProvenance = Truncate($"{SourceTypeTag}:{extId}", 300), + CertificateLevelId = levelId, + CertificateLevelCode = levelCode, + LanguageSkillId = skillId, + TopicTitle = topicTitle, + StageCode = TruncateNullable(topicExtId, 60), + StageSortOrder = chapterOrder + 1, + StageObjectives = TruncateNullable(Str(topicJson, "description"), 1000), + }; + + var existingLesson = FindExistingLesson(result.Snapshot, payload.SourceProvenance, title, levelId); + AddCandidate( + result, + ImportEntityType.Lesson, + extId, + levelCode, + topicExtId, + extId, + title, + existingLesson?.Id, + JsonSerializer.Serialize(payload, PascalJson), + audioDisplay, + imgDisplay, + richLesson is not null && richLesson.Value.TryGetProperty("practiceQuestions", out var pq) && pq.ValueKind == JsonValueKind.Array ? pq.GetArrayLength() : 0); + } + } + + // 2. Vocabulary, Kanji, Grammar (Dependency 2 — auto-linked to Lesson via LessonTitle in ContentApprovalService) + var selectedVocabItems = new List(); + var selectedKanjiItems = new List(); + var selectedGrammarItems = new List(); + + if (scope.IncludeVocabKanjiGrammar || scope.IncludeSrsTemplates) + { + var allVocab = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/vocabulary.json"); + var allKanji = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/kanji.json"); + var allGrammar = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/grammar_patterns.json"); + + var linkedVocabIds = lvLinks.Where(x => selectedLessonIds.Contains(Str(x, "lessonExternalId") ?? "")) + .Select(x => Str(x, "vocabularyExternalId") ?? "").ToHashSet(StringComparer.OrdinalIgnoreCase); + var linkedKanjiIds = lkLinks.Where(x => selectedLessonIds.Contains(Str(x, "lessonExternalId") ?? "")) + .Select(x => Str(x, "kanjiExternalId") ?? "").ToHashSet(StringComparer.OrdinalIgnoreCase); + var linkedGrammarIds = lgLinks.Where(x => selectedLessonIds.Contains(Str(x, "lessonExternalId") ?? "")) + .Select(x => Str(x, "grammarExternalId") ?? "").ToHashSet(StringComparer.OrdinalIgnoreCase); + + selectedVocabItems = scope.TopicCodes.Count > 0 + ? allVocab.Where(x => linkedVocabIds.Contains(Str(x, "externalStableId") ?? "")).ToList() + : allVocab; + selectedKanjiItems = scope.TopicCodes.Count > 0 + ? allKanji.Where(x => linkedKanjiIds.Contains(Str(x, "externalStableId") ?? "")).ToList() + : allKanji; + selectedGrammarItems = scope.TopicCodes.Count > 0 + ? allGrammar.Where(x => linkedGrammarIds.Contains(Str(x, "externalStableId") ?? "")).ToList() + : allGrammar; + } + + if (scope.IncludeVocabKanjiGrammar) + { + var seenVocabNatural = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var v in selectedVocabItems) + { + var extId = Str(v, "externalStableId") ?? ""; + var word = Truncate(Str(v, "Word") ?? "", 200); + var reading = Truncate(string.IsNullOrWhiteSpace(Str(v, "Reading")) ? word : Str(v, "Reading")!, 200); + var meaning = Truncate(Str(v, "Meaning") ?? "", 300); + if (word.Length == 0 || meaning.Length == 0) continue; + + var natural = $"{word}\u001f{reading}"; + if (!seenVocabNatural.Add(natural)) continue; + + primaryLessonForVocab.TryGetValue(extId, out var lessonTitle); + var existingId = result.Snapshot.VocabIdByWordReading.TryGetValue(natural, out var vid) ? vid : (int?)null; + + var payload = new VocabularyImportPayloadResponse + { + Word = word, + Reading = reading, + Meaning = meaning, + ExampleSentence = TruncateNullable(Str(v, "ExampleSentence"), 1000), + ExampleSentenceMeaning = TruncateNullable(Str(v, "ExampleSentenceMeaning"), 1000), + AudioUrl = TruncateNullable(Str(v, "AudioUrl"), 1000), + ImageUrl = TruncateNullable(Str(v, "ImageUrl"), 1000), + CertificateLevelCode = levelCode, + CertificateLevelId = levelId, + LessonTitle = lessonTitle, + }; + + AddCandidate(result, ImportEntityType.Vocabulary, extId, levelCode, null, extId, + $"{word} ({reading})", existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0, + skipIfAlreadyLinkedToLesson: existingId.HasValue && lessonTitle is not null && + result.Snapshot.LessonVocabPairs.Contains((lessonTitle, levelId, existingId.Value))); + } + + var seenKanjiChars = new HashSet(StringComparer.Ordinal); + foreach (var k in selectedKanjiItems) + { + var extId = Str(k, "externalStableId") ?? ""; + var ch = Truncate(Str(k, "Character") ?? "", 10); + var meaning = Truncate(Str(k, "Meaning") ?? "", 300); + if (ch.Length == 0 || meaning.Length == 0) continue; + if (!seenKanjiChars.Add(ch)) continue; + + primaryLessonForKanji.TryGetValue(extId, out var lessonTitle); + var existingId = result.Snapshot.KanjiIdByChar.TryGetValue(ch, out var kid) ? kid : (int?)null; + + var payload = new KanjiImportPayloadResponse + { + Character = ch, + Meaning = meaning, + SinoVietnamese = TruncateNullable(Str(k, "SinoVietnamese"), 100), + OnYomi = TruncateNullable(CleanPythonList(Str(k, "OnYomi")), 200), + KunYomi = TruncateNullable(CleanPythonList(Str(k, "KunYomi")), 200), + StrokeCount = Math.Max(1, IntVal(k, "StrokeCount", 1)), + StrokeOrderImageUrl = TruncateNullable(Str(k, "StrokeOrderImageUrl"), 500), + AudioUrl = TruncateNullable(Str(k, "AudioUrl"), 500), + CertificateLevelCode = levelCode, + CertificateLevelId = levelId, + LessonTitle = lessonTitle, + }; + + AddCandidate(result, ImportEntityType.Kanji, extId, levelCode, null, extId, + $"{ch} — {meaning}", existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0, + skipIfAlreadyLinkedToLesson: existingId.HasValue && lessonTitle is not null && + result.Snapshot.LessonKanjiPairs.Contains((lessonTitle, levelId, existingId.Value))); + } + + var seenGrammarTitles = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var g in selectedGrammarItems) + { + var extId = Str(g, "externalStableId") ?? ""; + var title = Truncate(Str(g, "Title") ?? "", 300); + var structure = Truncate(string.IsNullOrWhiteSpace(Str(g, "Structure")) ? title : Str(g, "Structure")!, 300); + if (title.Length == 0) continue; + if (!seenGrammarTitles.Add(title)) continue; + + primaryLessonForGrammar.TryGetValue(extId, out var lessonTitle); + var existingId = result.Snapshot.GrammarIdByTitle.TryGetValue(title, out var gid) ? gid : (int?)null; + + var payload = new GrammarImportPayloadResponse + { + Title = title, + Structure = structure, + UsageNotes = TruncateNullable(Str(g, "UsageNotes"), 2000), + ExampleSentence = TruncateNullable(Str(g, "ExampleSentence"), 1000), + ExampleSentenceMeaning = TruncateNullable(Str(g, "ExampleSentenceMeaning"), 1000), + CertificateLevelCode = levelCode, + CertificateLevelId = levelId, + LessonTitle = lessonTitle, + }; + + AddCandidate(result, ImportEntityType.Grammar, extId, levelCode, null, extId, + title, existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0, + skipIfAlreadyLinkedToLesson: existingId.HasValue && lessonTitle is not null && + result.Snapshot.LessonGrammarPairs.Contains((lessonTitle, levelId, existingId.Value))); + } + } + + // 3. Practice Exercises (LessonQuickCheck + GroupQuiz) + if (scope.IncludePracticeExercises) + { + foreach (var l in selectedLessons) + { + var extId = Str(l, "externalStableId") ?? ""; + var topicExtId = Str(l, "topicExternalId") ?? ""; + if (!richData.LessonsById.TryGetValue(extId, out var richLesson)) continue; + var parsedQuestions = ExtractPracticeQuestions(richLesson, extId, result.Issues); + if (parsedQuestions.Count == 0) continue; + + lessonTitleByExtId.TryGetValue(extId, out var lessonTitle); + var exRowKey = $"{extId}-PRACTICE"; + var exTitle = Truncate($"Luyện tập nhanh: {lessonTitle}", 300); + var existingId = result.Snapshot.ExerciseIdByLevelTitle.TryGetValue((levelId, exTitle), out var peId) ? peId : (int?)null; + var skillId = ResolveSkillId(result.Snapshot, Str(l, "primaryLanguageSkillRef") ?? Str(l, "lessonType")); + + var payload = new PracticeExerciseImportPayloadResponse + { + Title = exTitle, + Description = TruncateNullable($"Bài luyện tập củng cố kiến thức cho {lessonTitle}.", 1000), + SortOrder = Math.Max(1, IntVal(l, "orderIndex")), + Scope = PracticeExerciseScopes.LessonQuickCheck, + PassingScorePercent = 70, + LessonTitle = lessonTitle ?? "", + CertificateLevelId = levelId, + CertificateLevelCode = levelCode, + LanguageSkillId = skillId, + LanguageSkillName = result.Snapshot.SkillNameById.GetValueOrDefault(skillId, "Vocabulary"), + Questions = parsedQuestions, + }; + + AddCandidate(result, ImportEntityType.PracticeExercise, exRowKey, levelCode, topicExtId, exRowKey, + exTitle, existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, parsedQuestions.Count); + } + + foreach (var t in selectedTopics) + { + var topicCode = Str(t, "externalStableId") ?? ""; + if (!richData.ChapterAssessmentsById.TryGetValue(topicCode, out var assessJson)) continue; + var assessQuestions = ExtractPracticeQuestions(assessJson, topicCode, result.Issues); + if (assessQuestions.Count == 0) continue; + + var assessId = Str(assessJson, "assessmentId") ?? $"{topicCode}-ASSESS"; + var topicTitle = Truncate(Str(t, "titleVi") ?? topicCode, 300); + var exTitle = Truncate(Str(assessJson, "titleVi") ?? $"Kiểm tra cuối chương {topicCode}: {topicTitle}", 300); + var existingId = result.Snapshot.ExerciseIdByLevelTitle.TryGetValue((levelId, exTitle), out var peId) ? peId : (int?)null; + var grammarSkillId = ResolveSkillId(result.Snapshot, "Grammar"); + + var payload = new PracticeExerciseImportPayloadResponse + { + Title = exTitle, + Description = TruncateNullable($"Đánh giá tổng hợp chặng {topicCode} ({topicTitle}).", 1000), + SortOrder = (IntVal(t, "orderIndex") + 1) * 100, + Scope = PracticeExerciseScopes.GroupQuiz, + PassingScorePercent = Math.Max(50, IntVal(assessJson, "passingScorePercent", 75)), + LessonTitle = string.Empty, + TopicTitle = topicTitle, + CertificateLevelId = levelId, + CertificateLevelCode = levelCode, + LanguageSkillId = grammarSkillId, + LanguageSkillName = result.Snapshot.SkillNameById.GetValueOrDefault(grammarSkillId, "Grammar"), + Questions = assessQuestions, + }; + + AddCandidate(result, ImportEntityType.PracticeExercise, assessId, levelCode, topicCode, assessId, + exTitle, existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, assessQuestions.Count); + } + } + + // 4. SRS Card Templates + if (scope.IncludeSrsTemplates && srsNodes.Count > 0) + { + var matchGlobalIds = selectedVocabItems.Select(x => Str(x, "externalStableId") ?? "") + .Concat(selectedKanjiItems.Select(x => Str(x, "externalStableId") ?? "")) + .Concat(selectedGrammarItems.Select(x => Str(x, "externalStableId") ?? "")) + .Where(x => x.Length > 0) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + var matchFrontTexts = selectedVocabItems.Select(x => Str(x, "Word") ?? "") + .Concat(selectedKanjiItems.Select(x => Str(x, "Character") ?? "")) + .Concat(selectedGrammarItems.Select(x => Str(x, "Title") ?? "")) + .Where(x => x.Length > 0) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + var seenNormKeys = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var s in srsNodes) + { + if (!string.Equals(Str(s, "firstIntroducedLevel"), levelCode, StringComparison.OrdinalIgnoreCase)) continue; + var canonicalId = Str(s, "canonicalGlobalId") ?? ""; + var frontJa = Str(s, "frontTextJa") ?? ""; + if (scope.TopicCodes.Count > 0 && !matchGlobalIds.Contains(canonicalId) && !matchFrontTexts.Contains(frontJa)) + continue; + + var extId = Str(s, "externalStableId") ?? ""; + var rawType = (Str(s, "knowledgeType") ?? "VOCABULARY").ToUpperInvariant(); + var cardType = rawType switch + { + "KANJI" => "Kanji", + "GRAMMAR" => "Grammar", + _ => "Vocabulary", + }; + var front = Truncate(frontJa, 500); + var back = Truncate(Str(s, "backMeaningVi") ?? "", 1000); + if (front.Length == 0 || back.Length == 0) continue; + + var normKey = Truncate($"{levelCode}:{cardType}:{front}", 300); + if (!seenNormKeys.Add(normKey)) continue; + + var reading = cardType == "Kanji" + ? CleanPythonList(Str(s, "frontReadingKana")) + : Str(s, "frontReadingKana"); + + var payload = new SrsCardTemplateImportPayloadResponse + { + CardType = cardType, + FrontText = front, + BackText = back, + Reading = TruncateNullable(reading, 300), + Meaning = TruncateNullable(back, 500), + CertificateLevelId = levelId, + CertificateLevelCode = levelCode, + NormalizedContentKey = normKey, + ExternalStableId = extId, + }; + + var existingId = result.Snapshot.SrsIdByNormalizedKey.TryGetValue(normKey, out var sid) ? sid : (int?)null; + AddCandidate(result, ImportEntityType.SrsCardTemplate, extId, levelCode, null, extId, + $"{cardType}: {front}", existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0); + } + } + + // 5. Mock Tests (Server-side private answers combined securely; 4 JLPT skills split across active DB CertificateSections) + if (scope.IncludeMockTests) + { + var mocksPublic = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/mock_tests_public.json"); + var mocksPrivate = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/mock_tests_private_answers.json") + .GroupBy(m => Str(m, "mockExternalId") ?? "", StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + + foreach (var m in mocksPublic) + { + var extId = Str(m, "externalStableId") ?? ""; + if (scope.MockTestIds.Count > 0 && !scope.MockTestIds.Contains(extId)) + continue; + + mocksPrivate.TryGetValue(extId, out var privJson); + var candidate = await BuildMockTestCandidateAsync( + m, privJson, levelId, levelCode, csvAssets, ResolveMediaAsync, result.Snapshot, result.Issues); + if (candidate is not null) + result.Items.Add(candidate); + } + } + } + } + finally + { + foreach (var entry in resourceZips.Values) + entry.Zip.Dispose(); + } + + return result; + } + + private async Task BuildMockTestCandidateAsync( + JsonElement mockPublic, + JsonElement? mockPrivate, + int levelId, + string levelCode, + List csvAssets, + Func> resolveMediaAsync, + DbSnapshot snapshot, + List issues) + { + var extId = Str(mockPublic, "externalStableId") ?? ""; + var title = Truncate(Str(mockPublic, "titleVi") ?? extId, 300); + if (!mockPublic.TryGetProperty("publicLearnerPayload", out var pubPayload) || pubPayload.ValueKind != JsonValueKind.Object) + { + issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Error", + Code = "MOCK_PAYLOAD_MISSING", + Target = extId, + Message = "Đề thi thiếu publicLearnerPayload.", + }); + return null; + } + + // Answer key map: N5 uses "answers", N4-N2 uses "answerKeyAndExplanations". + var answerMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + var audioPlanByRefOrQ = new Dictionary(StringComparer.OrdinalIgnoreCase); + + if (mockPrivate is { ValueKind: JsonValueKind.Object } priv) + { + var ansArrayName = priv.TryGetProperty("answers", out _) ? "answers" : "answerKeyAndExplanations"; + if (priv.TryGetProperty(ansArrayName, out var ansArr) && ansArr.ValueKind == JsonValueKind.Array) + { + foreach (var a in ansArr.EnumerateArray()) + { + var qid = Str(a, "questionId"); + if (string.IsNullOrWhiteSpace(qid)) continue; + answerMap[qid] = (IntVal(a, "correctOptionIndex", 0), Str(a, "explanationVi")); + } + } + + if (priv.TryGetProperty("listeningScriptsAndAudioPlan", out var audioArr) && audioArr.ValueKind == JsonValueKind.Array) + { + foreach (var a in audioArr.EnumerateArray()) + { + var script = CombineScriptAndTranslation(Str(a, "scriptJa"), Str(a, "translationVi")); + var fileName = Str(a, "fileName"); + var refId = Str(a, "audioRefId") ?? Str(a, "audioId"); + var linkedQ = Str(a, "linkedQuestionId"); + if (!string.IsNullOrWhiteSpace(refId)) audioPlanByRefOrQ[refId] = (fileName, script, Str(a, "translationVi")); + if (!string.IsNullOrWhiteSpace(linkedQ)) audioPlanByRefOrQ[linkedQ] = (fileName, script, Str(a, "translationVi")); + } + } + } + + // Map assets from CSV linked to this mock (match e.g. N5-FULL-MOCK-01 inside N5-FULL-MOCK-01-COMPLETE). + var mockCsvAssets = csvAssets.Where(a => + a.Level.Equals(levelCode, StringComparison.OrdinalIgnoreCase) && + !string.IsNullOrWhiteSpace(a.LinkedChapterOrExam) && + (extId.StartsWith(a.LinkedChapterOrExam, StringComparison.OrdinalIgnoreCase) || + a.LinkedChapterOrExam.StartsWith(extId, StringComparison.OrdinalIgnoreCase))).ToList(); + + var assetByQuestionId = mockCsvAssets + .Where(a => !string.IsNullOrWhiteSpace(a.LinkedQuestionId)) + .GroupBy(a => a.LinkedQuestionId!, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + + var assetByExtId = mockCsvAssets + .Where(a => !string.IsNullOrWhiteSpace(a.AssetExternalId)) + .GroupBy(a => a.AssetExternalId!, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + + // Passages indexed by passageId. + var passagesById = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (pubPayload.TryGetProperty("passages", out var passagesArr) && passagesArr.ValueKind == JsonValueKind.Array) + { + var sortIdx = 0; + foreach (var psg in passagesArr.EnumerateArray()) + { + var pid = Str(psg, "passageId") ?? Str(psg, "code") ?? $"P-{++sortIdx}"; + var pText = Str(psg, "passageJa") ?? Str(psg, "passageText") ?? Str(psg, "contentJa") ?? string.Empty; + var pTitle = Truncate(Str(psg, "titleVi") ?? Str(psg, "titleJa") ?? pid, 300); + passagesById[pid] = new MockPassageImportPayloadResponse + { + PassageCode = Truncate(pid, 80), + Title = pTitle, + PassageText = pText, + SortOrder = ++sortIdx, + SourceReference = Truncate($"{SourceTypeTag}:{extId}", 300), + }; + } + } + + // Resolve DB sections for the 4 required JLPT study skills. + var certSections = snapshot.CertSectionsByLevelId.GetValueOrDefault(levelId) ?? []; + if (certSections.Count == 0) + { + issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Error", + Code = "MISSING_CERT_SECTION", + Target = extId, + Message = $"Cấp độ {levelCode} chưa có CertificateSection trong DB để gắn đề thi thử.", + }); + return null; + } + + var bucketVocab = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); + var bucketGrammar = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); + var bucketReading = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); + var bucketListening = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); + + var audioCount = 0; + var imageCount = 0; + var globalOrder = 0; + + if (pubPayload.TryGetProperty("questions", out var qArr) && qArr.ValueKind == JsonValueKind.Array) + { + foreach (var q in qArr.EnumerateArray()) + { + var qid = Str(q, "questionId") ?? $"Q{globalOrder + 1}"; + var prompt = SanitizeQuestionText(Str(q, "prompt") ?? Str(q, "promptJa") ?? Str(q, "questionText") ?? ""); + if (string.IsNullOrWhiteSpace(prompt)) continue; + + var rawOptions = new List(); + if (q.TryGetProperty("options", out var optEl) && optEl.ValueKind == JsonValueKind.Array) + foreach (var o in optEl.EnumerateArray()) + rawOptions.Add(SanitizeOptionText(o.GetString() ?? "")); + + if (rawOptions.Count < 2) continue; + + // Ensure option texts are unique & non-empty. + rawOptions = DeduplicateOptions(rawOptions); + var ansInfo = answerMap.GetValueOrDefault(qid); + var correctIdx = Math.Clamp(ansInfo.CorrectIndex, 0, rawOptions.Count - 1); + + var options = rawOptions.Select((optText, idx) => new ImportOptionPayloadResponse + { + SortOrder = idx + 1, + OptionText = optText, + IsCorrect = idx == correctIdx, + }).ToList(); + + var skillBucket = ClassifyMockQuestionSkill(q); + var audioRefId = Str(q, "audioRefId"); + var qAssetList = assetByQuestionId.GetValueOrDefault(qid) + ?? (!string.IsNullOrWhiteSpace(audioRefId) ? assetByExtId.GetValueOrDefault(audioRefId) : null) + ?? []; + + var wavLogical = qAssetList.FirstOrDefault(a => a.AssetType.Contains("WAV", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath + ?? Str(q, "linkedAudioFile") + ?? (audioPlanByRefOrQ.TryGetValue(qid, out var planByQ) ? planByQ.FileName : null) + ?? (!string.IsNullOrWhiteSpace(audioRefId) && audioPlanByRefOrQ.TryGetValue(audioRefId, out var planByRef) ? planByRef.FileName : null); + + var imgLogical = qAssetList.FirstOrDefault(a => a.AssetType.Contains("IMAGE", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath + ?? Str(q, "linkedIllustrationFile"); + + var (audioUrl, _) = skillBucket == JlptStudySkill.Listening + ? await resolveMediaAsync(wavLogical, true) + : (null, null); + var (imgUrl, _) = !string.IsNullOrWhiteSpace(imgLogical) + ? await resolveMediaAsync(imgLogical, false) + : (null, null); + + if (audioUrl is not null) audioCount++; + if (imgUrl is not null) imageCount++; + + if (skillBucket == JlptStudySkill.Listening && string.IsNullOrWhiteSpace(audioUrl) && wavLogical is null) + { + issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Warning", + Code = "MOCK_LISTENING_NO_AUDIO", + Target = $"{extId}/{qid}", + Message = "Câu nghe thiếu tệp WAV tương ứng trong asset_mapping.csv.", + }); + } + + string? transcript = null; + if (audioPlanByRefOrQ.TryGetValue(qid, out var p1)) transcript = p1.Script; + else if (!string.IsNullOrWhiteSpace(audioRefId) && audioPlanByRefOrQ.TryGetValue(audioRefId, out var p2)) transcript = p2.Script; + + var passageRef = Str(q, "passageRefId") ?? Str(q, "passageId"); + var qPayload = new MockQuestionPayloadResponse + { + SortOrder = ++globalOrder, + GroupSortOrder = globalOrder, + QuestionText = prompt, + QuestionType = imgUrl is not null && skillBucket == JlptStudySkill.Listening + ? JlptMockQuestionFormats.VisualMultipleChoice + : "SingleChoice", + AudioUrl = audioUrl, + AudioTranscript = transcript, + ImageUrl = imgUrl, + Explanation = ansInfo.Explanation, + PassageCode = passageRef is not null && passagesById.ContainsKey(passageRef) ? Truncate(passageRef, 80) : null, + Options = options, + }; + + switch (skillBucket) + { + case JlptStudySkill.Vocabulary: bucketVocab.Add((qPayload, qPayload.PassageCode)); break; + case JlptStudySkill.Grammar: bucketGrammar.Add((qPayload, qPayload.PassageCode)); break; + case JlptStudySkill.Reading: bucketReading.Add((qPayload, qPayload.PassageCode)); break; + case JlptStudySkill.Listening: bucketListening.Add((qPayload, qPayload.PassageCode)); break; + } + } + } + + // Guarantee ValidateMockTestCoverage passes if a mock omitted one of the 4 splits slightly or rebalances cleanly. + var sections = new List(); + void AddMockSection(string secTitle, JlptStudySkill skill, List<(MockQuestionPayloadResponse Q, string? PassageId)> items, int duration) + { + if (items.Count == 0) return; + var skillId = ResolveSkillId(snapshot, skill.ToString()); + var certSection = MatchCertificateSection(certSections, skill); + var passageCodesNeeded = items.Select(x => x.PassageId).Where(c => !string.IsNullOrWhiteSpace(c)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(c => passagesById[c!]) + .ToList(); + + sections.Add(new MockTestSectionPayloadResponse + { + Title = Truncate(secTitle, 200), + SortOrder = sections.Count + 1, + LanguageSkillId = skillId, + LanguageSkillName = snapshot.SkillNameById.GetValueOrDefault(skillId, skill.ToString()), + CertificateSectionCode = certSection.Code, + DurationMinutes = duration, + Passages = passageCodesNeeded, + Questions = items.Select(x => x.Q).ToList(), + }); + } + + AddMockSection($"Kiến thức ngôn ngữ — Từ vựng ({levelCode})", JlptStudySkill.Vocabulary, bucketVocab, 20); + AddMockSection($"Kiến thức ngôn ngữ — Ngữ pháp ({levelCode})", JlptStudySkill.Grammar, bucketGrammar, 25); + AddMockSection($"Đọc hiểu ({levelCode})", JlptStudySkill.Reading, bucketReading, 30); + AddMockSection($"Nghe hiểu ({levelCode})", JlptStudySkill.Listening, bucketListening, 30); + + if (sections.Count < 4) + { + issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Warning", + Code = "MOCK_INCOMPLETE_SECTIONS", + Target = extId, + Message = $"Đề thi chỉ phân tách được {sections.Count}/4 phần kỹ năng.", + }); + } + + var payload = new MockTestImportPayloadResponse + { + Title = title, + Description = TruncateNullable($"Đề thi thử JLPT {levelCode} nhập chuẩn từ gói giáo trình ({globalOrder} câu, đáp án bảo mật phía máy chủ).", 1000), + TimeLimitMinutes = Math.Max(30, sections.Sum(s => s.DurationMinutes ?? 20)), + IsPlacementAssessment = false, + CertificateLevelCode = levelCode, + CertificateLevelId = levelId, + Sections = sections, + }; + + var existingId = snapshot.MockIdBySourceOrTitle.TryGetValue(extId, out var m1) + ? m1 + : snapshot.MockIdByLevelTitle.TryGetValue((levelId, title), out var m2) ? m2 : (int?)null; + + var rowKey = extId; + var existsOpen = snapshot.OpenOrApprovedRowKeys.Contains((ImportEntityType.MockTest, rowKey)); + var action = (existingId.HasValue || existsOpen) ? ImportRowAction.Unchanged : ImportRowAction.New; + + return new StagedCandidate + { + EntityType = ImportEntityType.MockTest, + Action = action, + TargetEntityId = existingId, + PayloadJson = JsonSerializer.Serialize(payload, PascalJson), + CanStage = action != ImportRowAction.Unchanged, + Preview = new CurriculumPackagePreviewItemResponse + { + ExternalId = extId, + EntityType = nameof(ImportEntityType.MockTest), + LevelCode = levelCode, + RowKey = rowKey, + Title = title, + Action = existingId.HasValue ? "Existing" : existsOpen ? "Existing" : "New", + Status = "Draft", + PublishedReady = false, + AudioAsset = audioCount > 0 ? $"{audioCount} WAV" : null, + ImageAsset = imageCount > 0 ? $"{imageCount} Ảnh" : null, + ChildCount = globalOrder, + }, + }; + } + + private async Task UploadZipEntryAsync( + ZipArchiveEntry entry, + bool isAudio, + int actorUserId, + CancellationToken ct) + { + await using var entryStream = entry.Open(); + await using var ms = new MemoryStream(); + await entryStream.CopyToAsync(ms, ct); + ms.Position = 0; + + var fileName = Path.GetFileName(entry.FullName); + var ext = Path.GetExtension(fileName).ToLowerInvariant(); + if (isAudio) + { + var contentType = ListeningAudioFilePolicy.GetContentType(ext); + var storedAudio = await fileStorage.UploadAsync(ms, fileName, contentType, "jlpt-curriculum-audio", ct); + if (audioTranscriptions is not null && actorUserId > 0) + { + try { await audioTranscriptions.QueueAsync(storedAudio.Url, actorUserId, ct); } + catch (Exception ex) { logger.LogDebug(ex, "Queueing curriculum WAV transcription skipped for {Url}", storedAudio.Url); } + } + return storedAudio.Url; + } + + var imgMime = ext switch + { + ".png" => "image/png", + ".webp" => "image/webp", + ".gif" => "image/gif", + _ => "image/jpeg", + }; + var storedImg = await fileStorage.UploadAsync(ms, fileName, imgMime, "jlpt-curriculum-images", ct); + return storedImg.Url; + } + + private async Task SyncContentBankDraftsAsync( + List drafts, + int actorUserId, + Guid batchId, + CancellationToken ct) + { + var keys = drafts.Select(d => ComputeContentBankKey(d.EntityType, d.RowKey, d.PayloadJson)).Distinct().ToArray(); + var existing = await unitOfWork.ContentBankItems.Query() + .Where(x => !x.IsDeleted && x.OwnerUserId == actorUserId && keys.Contains(x.NaturalKey)) + .ToListAsync(ct); + + foreach (var draft in drafts) + { + var nk = ComputeContentBankKey(draft.EntityType, draft.RowKey, draft.PayloadJson); + var item = existing.FirstOrDefault(x => x.EntityType == draft.EntityType && x.NaturalKey == nk); + if (item is null) + { + item = new ContentBankItem + { + OwnerUserId = actorUserId, + EntityType = draft.EntityType, + NaturalKey = nk, + }; + await unitOfWork.ContentBankItems.AddAsync(item, ct); + existing.Add(item); + } + item.PayloadJson = draft.PayloadJson; + item.TargetEntityId = draft.TargetEntityId; + item.Status = ContentApprovalStatus.Draft; + item.LatestBatchId = batchId; + } + } + + private static string ComputeContentBankKey(ImportEntityType type, string rowKey, string payloadJson) + { + if (type != ImportEntityType.PracticeExercise) return Truncate(rowKey, 490); + try + { + using var doc = JsonDocument.Parse(payloadJson); + if (doc.RootElement.TryGetProperty("CertificateLevelId", out var lvl) && lvl.ValueKind == JsonValueKind.Number) + return $"{Truncate(rowKey, 460)} / level:{lvl.GetInt32()}"; + } + catch (JsonException) { } + return Truncate(rowKey, 490); + } + + private static void AddCandidate( + BuiltPackageResult result, + ImportEntityType entityType, + string externalId, + string levelCode, + string? topicCode, + string rowKey, + string title, + int? existingTargetId, + string payloadJson, + string? audioAsset, + string? imageAsset, + int childCount, + bool skipIfAlreadyLinkedToLesson = false) + { + var alreadyOpenOrApproved = result.Snapshot.OpenOrApprovedRowKeys.Contains((entityType, rowKey)); + var isLessonOrExerciseOrSrs = entityType is ImportEntityType.Lesson or ImportEntityType.PracticeExercise or ImportEntityType.SrsCardTemplate or ImportEntityType.MockTest; + + ImportRowAction action; + string previewAction; + if (alreadyOpenOrApproved || skipIfAlreadyLinkedToLesson || (isLessonOrExerciseOrSrs && existingTargetId.HasValue)) + { + action = ImportRowAction.Unchanged; + previewAction = "Existing"; + } + else if (existingTargetId.HasValue) + { + action = ImportRowAction.Modified; + previewAction = "Modified"; + } + else + { + action = ImportRowAction.New; + previewAction = "New"; + } + + result.Items.Add(new StagedCandidate + { + EntityType = entityType, + Action = action, + TargetEntityId = existingTargetId, + PayloadJson = payloadJson, + CanStage = action != ImportRowAction.Unchanged, + Preview = new CurriculumPackagePreviewItemResponse + { + ExternalId = externalId, + EntityType = entityType.ToString(), + LevelCode = levelCode, + TopicCode = topicCode, + RowKey = rowKey, + Title = title, + Action = previewAction, + Status = "Draft", + PublishedReady = false, + AudioAsset = audioAsset, + ImageAsset = imageAsset, + ChildCount = childCount, + }, + }); + } + + private async Task LoadDatabaseSnapshotAsync(CancellationToken ct) + { + var levels = await unitOfWork.CertificateLevels.Query() + .AsNoTracking() + .Where(l => !l.IsDeleted && !l.CertificateType.IsDeleted && l.CertificateType.Name == "JLPT") + .Select(l => new { l.Id, l.Code }) + .ToListAsync(ct); + + var skills = await unitOfWork.LanguageSkills.Query() + .AsNoTracking() + .Where(s => !s.IsDeleted) + .Select(s => new { s.Id, s.Name }) + .ToListAsync(ct); + + var certSections = await unitOfWork.CertificateSections.Query() + .AsNoTracking() + .Where(s => !s.IsDeleted) + .ToListAsync(ct); + + var lessons = await unitOfWork.Lessons.Query() + .AsNoTracking() + .Where(l => !l.IsDeleted) + .Select(l => new LessonSnap(l.Id, l.Title, l.CertificateLevelId, l.SourceProvenance)) + .ToListAsync(ct); + + var vocabs = await unitOfWork.Vocabularies.Query() + .AsNoTracking() + .Where(v => !v.IsDeleted) + .Select(v => new { v.Id, v.Word, v.Reading }) + .ToListAsync(ct); + + var kanjis = await unitOfWork.Kanjis.Query() + .AsNoTracking() + .Where(k => !k.IsDeleted) + .Select(k => new { k.Id, k.Character }) + .ToListAsync(ct); + + var grammars = await unitOfWork.GrammarPatterns.Query() + .AsNoTracking() + .Where(g => !g.IsDeleted) + .Select(g => new { g.Id, g.Title }) + .ToListAsync(ct); + + var exercises = await unitOfWork.PracticeExercises.Query() + .AsNoTracking() + .Where(e => !e.IsDeleted) + .Select(e => new { e.Id, e.Title, e.CertificateLevelId }) + .ToListAsync(ct); + + var mocks = await unitOfWork.MockTests.Query() + .AsNoTracking() + .Where(m => !m.IsDeleted && !m.IsArchivedVersion) + .Select(m => new { m.Id, m.Title, m.CertificateLevelId, m.SourceReference }) + .ToListAsync(ct); + + var srs = await unitOfWork.SrsCardTemplates.Query() + .AsNoTracking() + .Where(s => !s.IsDeleted) + .Select(s => new { s.Id, s.NormalizedContentKey }) + .ToListAsync(ct); + + var requests = await unitOfWork.ContentApprovalRequests.Query() + .AsNoTracking() + .Where(r => !r.IsDeleted && r.Status != ContentApprovalStatus.Rejected) + .Select(r => new { r.EntityType, r.RowKey, r.TargetEntityId, r.Status }) + .ToListAsync(ct); + + var lvLinks = await unitOfWork.LessonVocabularies.Query() + .AsNoTracking() + .Where(lv => !lv.Lesson.IsDeleted) + .Select(lv => new { lv.Lesson.Title, lv.Lesson.CertificateLevelId, lv.VocabularyId }) + .ToListAsync(ct); + + var lkLinks = await unitOfWork.LessonKanjis.Query() + .AsNoTracking() + .Where(lk => !lk.Lesson.IsDeleted) + .Select(lk => new { lk.Lesson.Title, lk.Lesson.CertificateLevelId, lk.KanjiId }) + .ToListAsync(ct); + + var lgLinks = await unitOfWork.LessonGrammars.Query() + .AsNoTracking() + .Where(lg => !lg.Lesson.IsDeleted) + .Select(lg => new { lg.Lesson.Title, lg.Lesson.CertificateLevelId, lg.GrammarPatternId }) + .ToListAsync(ct); + + return new DbSnapshot + { + LevelIdByCode = levels.ToDictionary(l => l.Code, l => l.Id, StringComparer.OrdinalIgnoreCase), + SkillIdByName = skills.ToDictionary(s => s.Name, s => s.Id, StringComparer.OrdinalIgnoreCase), + SkillNameById = skills.ToDictionary(s => s.Id, s => s.Name), + CertSectionsByLevelId = certSections.GroupBy(s => s.CertificateLevelId).ToDictionary(g => g.Key, g => g.ToList()), + Lessons = lessons, + VocabIdByWordReading = vocabs.GroupBy(v => $"{v.Word}\u001f{v.Reading}", StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), + KanjiIdByChar = kanjis.GroupBy(k => k.Character, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal), + GrammarIdByTitle = grammars.GroupBy(g => g.Title, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), + ExerciseIdByLevelTitle = exercises.Where(e => e.CertificateLevelId.HasValue) + .GroupBy(e => (e.CertificateLevelId!.Value, e.Title)) + .ToDictionary(g => g.Key, g => g.First().Id), + MockIdBySourceOrTitle = mocks.Where(m => !string.IsNullOrWhiteSpace(m.SourceReference)) + .GroupBy(m => m.SourceReference!, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), + MockIdByLevelTitle = mocks.GroupBy(m => (m.CertificateLevelId, m.Title)) + .ToDictionary(g => g.Key, g => g.First().Id), + SrsIdByNormalizedKey = srs.GroupBy(s => s.NormalizedContentKey, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), + OpenOrApprovedRowKeys = requests.Select(r => (r.EntityType, r.RowKey)).ToHashSet(), + OpenTargetIds = requests + .Where(r => r.TargetEntityId.HasValue && (r.Status == ContentApprovalStatus.Draft || r.Status == ContentApprovalStatus.PendingReview)) + .Select(r => (r.EntityType, r.TargetEntityId!.Value)) + .ToHashSet(), + LessonVocabPairs = lvLinks.Select(x => (x.Title, x.CertificateLevelId, x.VocabularyId)).ToHashSet(), + LessonKanjiPairs = lkLinks.Select(x => (x.Title, x.CertificateLevelId, x.KanjiId)).ToHashSet(), + LessonGrammarPairs = lgLinks.Select(x => (x.Title, x.CertificateLevelId, x.GrammarPatternId)).ToHashSet(), + }; + } + + private string? FindResourcesDirectory() + { + var configured = configuration["CurriculumPackage:RootPath"]; + if (!string.IsNullOrWhiteSpace(configured) && File.Exists(Path.Combine(configured, SystemZipName))) + return Path.GetFullPath(configured); + + foreach (var start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) + { + var dir = new DirectoryInfo(start); + for (var i = 0; i < 8 && dir is not null; i++) + { + var candidate = Path.Combine(dir.FullName, "resources"); + if (File.Exists(Path.Combine(candidate, SystemZipName))) + return candidate; + if (File.Exists(Path.Combine(dir.FullName, SystemZipName))) + return dir.FullName; + dir = dir.Parent; + } + } + return null; + } + + private static CurriculumPackageArchiveInfo InspectArchive(string fullPath, string fileName, string? levelCode) + { + var info = new CurriculumPackageArchiveInfo { FileName = fileName, LevelCode = levelCode }; + if (!File.Exists(fullPath)) return info; + + var fi = new FileInfo(fullPath); + info.Exists = true; + info.SizeBytes = fi.Length; + + try + { + using var zip = ZipFile.OpenRead(fullPath); + info.EntryCount = zip.Entries.Count; + info.UnsafeEntryCount = zip.Entries.Count(e => IsUnsafeZipEntry(e.FullName)); + using var sha = SHA256.Create(); + using var fs = File.OpenRead(fullPath); + info.Sha256Short = Convert.ToHexString(sha.ComputeHash(fs))[..12].ToLowerInvariant(); + } + catch (InvalidDataException) + { + info.UnsafeEntryCount = -1; + } + return info; + } + + private static bool IsUnsafeZipEntry(string entryName) => + string.IsNullOrEmpty(entryName) || + entryName.StartsWith('/') || + entryName.StartsWith('\\') || + entryName.Contains("..", StringComparison.Ordinal) || + entryName.Contains(':'); + + private static Dictionary IndexSafeEntries(ZipArchive zip) + { + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var entry in zip.Entries) + { + if (IsUnsafeZipEntry(entry.FullName)) continue; + var norm = entry.FullName.Replace('\\', '/').TrimStart('/'); + if (norm.EndsWith('/')) continue; + dict.TryAdd(norm, entry); + } + return dict; + } + + private static (ZipArchive Zip, Dictionary Entries, Dictionary ByFileName)? OpenLevelResourceZip( + string root, + string levelCode, + Dictionary Entries, Dictionary ByFileName)> cache) + { + if (cache.TryGetValue(levelCode, out var existing)) return existing; + var zipName = $"RIKIPATH_{levelCode.ToUpperInvariant()}_RESOURCES.zip"; + var full = Path.Combine(root, zipName); + if (!File.Exists(full)) return null; + + var zip = ZipFile.OpenRead(full); + var entries = IndexSafeEntries(zip); + var byFile = entries.Values + .GroupBy(e => Path.GetFileName(e.FullName), StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + var tuple = (zip, entries, byFile); + cache[levelCode] = tuple; + return tuple; + } + + private (ZipArchive? Zip, ZipArchiveEntry? Entry) LocateZipEntry( + string logicalPath, + string levelCode, + Dictionary resolver, + Dictionary Entries, Dictionary ByFileName)> resourceZips) + { + if (!resourceZips.TryGetValue(levelCode, out var res)) return (null, null); + + var target = resolver.TryGetValue(logicalPath, out var mapped) ? mapped : logicalPath; + if (target.Contains("::", StringComparison.Ordinal)) + { + var idx = target.IndexOf("::", StringComparison.Ordinal); + target = target[(idx + 2)..]; + } + target = target.Replace('\\', '/').TrimStart('/'); + + if (res.Entries.TryGetValue(target, out var exact)) + return (res.Zip, exact); + + var bySuffix = res.Entries.FirstOrDefault(kv => kv.Key.EndsWith("/" + target, StringComparison.OrdinalIgnoreCase)).Value; + if (bySuffix is not null) + return (res.Zip, bySuffix); + + var fileName = Path.GetFileName(target); + if (!string.IsNullOrEmpty(fileName) && res.ByFileName.TryGetValue(fileName, out var byName)) + return (res.Zip, byName); + + return (null, null); + } + + private static List ReadJsonArray(ZipArchive zip, Dictionary entries, string pathSuffix) + { + var entry = entries.TryGetValue(pathSuffix, out var e) + ? e + : entries.FirstOrDefault(kv => kv.Key.EndsWith("/" + pathSuffix, StringComparison.OrdinalIgnoreCase)).Value; + if (entry is null) return []; + + using var stream = entry.Open(); + using var doc = JsonDocument.Parse(stream); + if (doc.RootElement.ValueKind != JsonValueKind.Array) return []; + return doc.RootElement.EnumerateArray().Select(x => x.Clone()).ToList(); + } + + private static Dictionary ReadAssetMappingsResolver(ZipArchive zip, Dictionary entries) + { + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + var entry = entries.FirstOrDefault(kv => kv.Key.EndsWith("consolidated_path_resolver.json", StringComparison.OrdinalIgnoreCase)).Value; + if (entry is null) return dict; + + using var stream = entry.Open(); + using var doc = JsonDocument.Parse(stream); + if (doc.RootElement.TryGetProperty("assetMappings", out var am) && am.ValueKind == JsonValueKind.Object) + foreach (var p in am.EnumerateObject()) + if (p.Value.ValueKind == JsonValueKind.String && p.Value.GetString() is { } s) + dict[p.Name] = s; + if (doc.RootElement.TryGetProperty("fileMappings", out var fm) && fm.ValueKind == JsonValueKind.Object) + foreach (var p in fm.EnumerateObject()) + if (p.Value.ValueKind == JsonValueKind.String && p.Value.GetString() is { } s) + dict.TryAdd(p.Name, s); + return dict; + } + + private static List LoadAssetMappings(ZipArchive zip, Dictionary entries) + { + var rows = new List(); + var entry = entries.FirstOrDefault(kv => kv.Key.EndsWith("04_ASSET_REFERENCES/asset_mapping.csv", StringComparison.OrdinalIgnoreCase)).Value; + if (entry is null) return rows; + + using var reader = new StreamReader(entry.Open(), Encoding.UTF8); + var headerLine = reader.ReadLine(); + if (headerLine is null) return rows; + var headers = ParseCsvLine(headerLine); + var col = headers.Select((h, i) => (h, i)).ToDictionary(x => x.h.Trim(), x => x.i, StringComparer.OrdinalIgnoreCase); + + while (reader.ReadLine() is { } line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + var cols = ParseCsvLine(line); + string GetCol(string name) => col.TryGetValue(name, out var idx) && idx < cols.Count ? cols[idx].Trim() : ""; + rows.Add(new CsvAssetRow( + GetCol("assetType"), + GetCol("level"), + GetCol("assetExternalId"), + GetCol("linkedChapterOrExam"), + GetCol("linkedLessonId"), + GetCol("linkedQuestionId"), + GetCol("logicalAssetPath"))); + } + return rows; + } + + private static List ParseCsvLine(string line) + { + var result = new List(); + var sb = new StringBuilder(); + var inQuotes = false; + for (var i = 0; i < line.Length; i++) + { + var c = line[i]; + if (c == '"') + { + if (inQuotes && i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; } + else inQuotes = !inQuotes; + } + else if (c == ',' && !inQuotes) + { + result.Add(sb.ToString()); + sb.Clear(); + } + else sb.Append(c); + } + result.Add(sb.ToString()); + return result; + } + + private static Dictionary> LoadKaiwaByLesson(ZipArchive zip, Dictionary entries) + { + var dict = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var list = ReadJsonArray(zip, entries, "02_EXTENDED_LEARNING_DATA/KAIWA/n4_n2_kaiwa_dialogues.json"); + foreach (var item in list) + { + var lid = Str(item, "lessonExternalId"); + if (string.IsNullOrWhiteSpace(lid)) continue; + if (!dict.TryGetValue(lid, out var bucket)) dict[lid] = bucket = []; + bucket.Add(item); + } + return dict; + } + + private static RichCurriculumData ExtractRichCurriculumData( + string levelCode, + ZipArchive? resZip, + Dictionary? entries) + { + var data = new RichCurriculumData(); + if (resZip is null || entries is null) return data; + + foreach (var kv in entries) + { + if (!kv.Key.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) continue; + if (kv.Key.Contains("/Lessons/", StringComparison.OrdinalIgnoreCase)) + { + using var doc = JsonDocument.Parse(kv.Value.Open()); + if (doc.RootElement.ValueKind == JsonValueKind.Object) + { + var lid = Str(doc.RootElement, "lessonId") ?? Path.GetFileNameWithoutExtension(kv.Key); + data.LessonsById[lid] = doc.RootElement.Clone(); + } + } + else if (kv.Key.EndsWith("Chapter_Content.json", StringComparison.OrdinalIgnoreCase) || + Regex.IsMatch(Path.GetFileName(kv.Key), @"^N[2-4]_CH\d+_CONTENT\.json$", RegexOptions.IgnoreCase)) + { + using var doc = JsonDocument.Parse(kv.Value.Open()); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) continue; + var chId = Str(root, "chapterId"); + if (!string.IsNullOrWhiteSpace(chId) && root.TryGetProperty("chapterAssessment", out var ca) && ca.ValueKind == JsonValueKind.Object) + data.ChapterAssessmentsById[chId] = ca.Clone(); + if (root.TryGetProperty("lessons", out var arr) && arr.ValueKind == JsonValueKind.Array) + { + foreach (var l in arr.EnumerateArray()) + { + var lid = Str(l, "lessonId"); + if (!string.IsNullOrWhiteSpace(lid) && !data.LessonsById.ContainsKey(lid)) + data.LessonsById[lid] = l.Clone(); + } + } + } + } + return data; + } + + private List ExtractPracticeQuestions( + JsonElement container, + string sourceTag, + List issues) + { + var list = new List(); + var prop = container.TryGetProperty("practiceQuestions", out var pq) ? pq + : container.TryGetProperty("questions", out var qs) ? qs + : default; + if (prop.ValueKind != JsonValueKind.Array) return list; + + var order = 0; + foreach (var q in prop.EnumerateArray()) + { + var prompt = SanitizeQuestionText(Str(q, "prompt") ?? Str(q, "questionText") ?? ""); + if (string.IsNullOrWhiteSpace(prompt)) continue; + + var rawOpts = new List(); + if (q.TryGetProperty("options", out var optsEl) && optsEl.ValueKind == JsonValueKind.Array) + foreach (var o in optsEl.EnumerateArray()) + if (o.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(o.GetString())) + rawOpts.Add(SanitizeOptionText(o.GetString()!)); + + if (rawOpts.Count < 2) + { + issues.Add(new CurriculumPackageIssueResponse + { + Severity = "Warning", + Code = "PRACTICE_SKIPPED_FEW_OPTIONS", + Target = sourceTag, + Message = $"Bỏ qua câu luyện tập '{Truncate(prompt, 40)}' vì không có đủ 2 lựa chọn (dạng tự luận/không tương thích MCQ).", + }); + continue; + } + + rawOpts = DeduplicateOptions(rawOpts); + var correctIdx = Math.Clamp(IntVal(q, "correctOptionIndex", 0), 0, rawOpts.Count - 1); + + list.Add(new PracticeQuestionPayloadResponse + { + SortOrder = ++order, + QuestionText = prompt, + Explanation = Str(q, "explanationVi") ?? Str(q, "explanation"), + Options = rawOpts.Select((optText, i) => new ImportOptionPayloadResponse + { + SortOrder = i + 1, + OptionText = optText, + IsCorrect = i == correctIdx, + }).ToList(), + }); + } + return list; + } + + private static string BuildLessonMarkdown( + JsonElement indexLesson, + JsonElement? richLesson, + List kaiwaList, + Dictionary vocabByExtId) + { + _ = vocabByExtId; + var sb = new StringBuilder(); + var note = Str(indexLesson, "multiSkillNote"); + var focus = richLesson is { ValueKind: JsonValueKind.Object } rl ? Str(rl, "focus") : null; + if (!string.IsNullOrWhiteSpace(focus)) + sb.AppendLine($"**Trọng tâm bài học:** {focus}").AppendLine(); + else if (!string.IsNullOrWhiteSpace(note) && !note.Contains("Extended_Learning_Data", StringComparison.OrdinalIgnoreCase)) + sb.AppendLine(note).AppendLine(); + + if (richLesson is { ValueKind: JsonValueKind.Object } r) + { + if (r.TryGetProperty("contentSections", out var sections) && sections.ValueKind == JsonValueKind.Array) + { + foreach (var sec in sections.EnumerateArray()) + { + var h = Str(sec, "headingVi") ?? Str(sec, "title"); + var body = Str(sec, "bodyMarkdown") ?? Str(sec, "content"); + if (!string.IsNullOrWhiteSpace(h)) sb.AppendLine($"### {h}"); + if (!string.IsNullOrWhiteSpace(body)) sb.AppendLine(body); + sb.AppendLine(); + } + } + + if (r.TryGetProperty("grammarPoints", out var gp) && gp.ValueKind == JsonValueKind.Array && gp.GetArrayLength() > 0) + { + sb.AppendLine("### Điểm ngữ pháp trọng tâm"); + foreach (var g in gp.EnumerateArray()) + { + var pattern = Str(g, "pattern") ?? Str(g, "title") ?? ""; + var structure = Str(g, "structure") ?? ""; + var meaning = Str(g, "meaningVi") ?? Str(g, "explanationVi") ?? Str(g, "usageNotes") ?? ""; + if (!string.IsNullOrWhiteSpace(pattern)) sb.AppendLine($"- **{pattern}**: {meaning}"); + if (!string.IsNullOrWhiteSpace(structure)) sb.AppendLine($" - Cấu trúc: `{structure}`"); + if (g.TryGetProperty("examples", out var exs) && exs.ValueKind == JsonValueKind.Array) + { + foreach (var ex in exs.EnumerateArray().Take(3)) + { + var ja = Str(ex, "sentenceJa") ?? Str(ex, "japanese") ?? ""; + var vi = Str(ex, "meaningVi") ?? Str(ex, "vietnamese") ?? ""; + if (!string.IsNullOrWhiteSpace(ja)) sb.AppendLine($" - Ví dụ: {ja} — {vi}"); + } + } + } + sb.AppendLine(); + } + + if (r.TryGetProperty("grammarItems", out var gi) && gi.ValueKind == JsonValueKind.Array && gi.GetArrayLength() > 0) + { + sb.AppendLine("### Mẫu ngữ pháp trong bài"); + foreach (var g in gi.EnumerateArray()) + { + var title = Str(g, "title") ?? Str(g, "pattern") ?? ""; + var meaning = Str(g, "meaningVi") ?? Str(g, "explanationVi") ?? Str(g, "usageNotes") ?? ""; + if (!string.IsNullOrWhiteSpace(title)) sb.AppendLine($"- **{title}**: {meaning}"); + } + sb.AppendLine(); + } + + if (r.TryGetProperty("readingPassages", out var rp) && rp.ValueKind == JsonValueKind.Array && rp.GetArrayLength() > 0) + { + foreach (var p in rp.EnumerateArray()) + { + var t = Str(p, "titleVi") ?? Str(p, "titleJa") ?? "Bài đọc"; + var tJa = Str(p, "titleJa"); + var text = Str(p, "passageJa") ?? Str(p, "passageText") ?? ""; + var trans = Str(p, "translationVi"); + sb.AppendLine($"### Bài đọc: {t}" + (!string.IsNullOrWhiteSpace(tJa) && tJa != t ? $" ({tJa})" : "")); + if (!string.IsNullOrWhiteSpace(text)) sb.AppendLine(text); + if (!string.IsNullOrWhiteSpace(trans)) sb.AppendLine().AppendLine($"*Dịch tham khảo:* {trans}"); + sb.AppendLine(); + } + } + + if (r.TryGetProperty("listeningItems", out var li) && li.ValueKind == JsonValueKind.Array && li.GetArrayLength() > 0) + { + foreach (var item in li.EnumerateArray()) + { + var topic = Str(item, "topic") ?? Str(item, "title") ?? "Bài nghe"; + var ctx = Str(item, "context") ?? ""; + var script = Str(item, "scriptJa") ?? Str(item, "transcript") ?? ""; + var trans = Str(item, "translationVi") ?? ""; + sb.AppendLine($"### Nghe hiểu: {topic}"); + if (!string.IsNullOrWhiteSpace(ctx)) sb.AppendLine($"**Ngữ cảnh:** {ctx}"); + if (!string.IsNullOrWhiteSpace(script)) sb.AppendLine().AppendLine("**Lời thoại (Transcript):**").AppendLine(script); + if (!string.IsNullOrWhiteSpace(trans)) sb.AppendLine().AppendLine("**Bản dịch:**").AppendLine(trans); + sb.AppendLine(); + } + } + } + + if (kaiwaList.Count > 0) + { + sb.AppendLine("### Hội thoại thực hành (Kaiwa)"); + foreach (var kw in kaiwaList) + { + var ped = Str(kw, "pedagogicalNoteVi"); + if (!string.IsNullOrWhiteSpace(ped)) sb.AppendLine($"*{ped}*"); + if (kw.TryGetProperty("turns", out var turns) && turns.ValueKind == JsonValueKind.Array) + { + foreach (var turn in turns.EnumerateArray()) + { + var sp = Str(turn, "speaker") ?? ""; + var textJa = Str(turn, "textJa") ?? Str(turn, "lineJa") ?? ""; + var textVi = Str(turn, "translationVi") ?? Str(turn, "meaningVi") ?? ""; + if (!string.IsNullOrWhiteSpace(textJa)) + sb.AppendLine($"- **{sp}:** {textJa}" + (!string.IsNullOrWhiteSpace(textVi) ? $" ({textVi})" : "")); + } + } + sb.AppendLine(); + } + } + + var output = sb.ToString().Trim(); + return string.IsNullOrWhiteSpace(output) ? Str(indexLesson, "titleVi") ?? "Nội dung bài học JLPT." : output; + } + + private static string? BuildLearningObjectives(JsonElement? richLesson, JsonElement indexLesson) + { + if (richLesson is { ValueKind: JsonValueKind.Object } r && + r.TryGetProperty("learningObjectives", out var objEl) && + objEl.ValueKind == JsonValueKind.Array) + { + var items = objEl.EnumerateArray() + .Where(x => x.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(x.GetString())) + .Select(x => "• " + x.GetString()!.Trim()) + .ToList(); + if (items.Count > 0) return string.Join("\n", items); + } + return Str(indexLesson, "multiSkillNote"); + } + + private static string? ResolvePrerequisiteTitle(JsonElement? richLesson, Dictionary lessonTitleByExtId) + { + if (richLesson is not { ValueKind: JsonValueKind.Object } r) return null; + if (!r.TryGetProperty("prerequisites", out var pr) || pr.ValueKind != JsonValueKind.Array) return null; + foreach (var item in pr.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.String || item.GetString() is not { } id) continue; + if (lessonTitleByExtId.TryGetValue(id, out var title)) return title; + } + return null; + } + + private static string? FirstResolvedAudio(JsonElement? richLesson) + { + if (richLesson is not { ValueKind: JsonValueKind.Object } r) return null; + if (!r.TryGetProperty("resolvedAudioReferences", out var arr) || arr.ValueKind != JsonValueKind.Array) return null; + return arr.EnumerateArray() + .Select(x => x.ValueKind == JsonValueKind.String ? x.GetString() : null) + .FirstOrDefault(s => !string.IsNullOrWhiteSpace(s) && s!.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)); + } + + private static LessonSnap? FindExistingLesson(DbSnapshot snap, string provenance, string title, int levelId) => + snap.Lessons.FirstOrDefault(l => + (!string.IsNullOrWhiteSpace(l.SourceProvenance) && l.SourceProvenance.Equals(provenance, StringComparison.OrdinalIgnoreCase)) || + (l.CertificateLevelId == levelId && l.Title.Equals(title, StringComparison.OrdinalIgnoreCase))); + + private static Dictionary FirstLessonLookup( + List links, + string itemKeyName, + HashSet selectedLessonIds, + Dictionary lessonTitleByExtId) + { + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var row in links) + { + var lid = Str(row, "lessonExternalId") ?? ""; + var iid = Str(row, itemKeyName) ?? ""; + if (!selectedLessonIds.Contains(lid) || string.IsNullOrWhiteSpace(iid)) continue; + if (lessonTitleByExtId.TryGetValue(lid, out var title)) + dict.TryAdd(iid, title); + } + return dict; + } + + private static int ResolveSkillId(DbSnapshot snap, string? raw) + { + var s = (raw ?? string.Empty).Trim().ToUpperInvariant(); + var candidates = s switch + { + "GRAMMAR" => new[] { "Grammar", "Ngữ pháp" }, + "READING" => new[] { "Reading", "Đọc hiểu" }, + "LISTENING" => new[] { "Listening", "Nghe hiểu" }, + "KANJI" => new[] { "Kanji", "Vocabulary", "Từ vựng" }, + "KAIWA" => new[] { "Listening", "Speaking", "Kaiwa" }, + _ => new[] { "Vocabulary", "Từ vựng" }, + }; + foreach (var name in candidates) + { + var hit = snap.SkillIdByName.FirstOrDefault(kv => kv.Key.Contains(name, StringComparison.OrdinalIgnoreCase)); + if (hit.Value > 0) return hit.Value; + } + return snap.SkillIdByName.Values.FirstOrDefault(1); + } + + private static CertificateSection MatchCertificateSection(List sections, JlptStudySkill skill) + { + bool Has(CertificateSection s, params string[] words) => + words.Any(w => s.Code.Contains(w, StringComparison.OrdinalIgnoreCase) || s.Name.Contains(w, StringComparison.OrdinalIgnoreCase)); + + var exact = skill switch + { + JlptStudySkill.Vocabulary => sections.FirstOrDefault(s => Has(s, "vocab", "goi", "moji", "từ")), + JlptStudySkill.Grammar => sections.FirstOrDefault(s => Has(s, "grammar", "bunpo") && !Has(s, "read", "dokkai")) + ?? sections.FirstOrDefault(s => Has(s, "gram", "language", "ngữ")), + JlptStudySkill.Reading => sections.FirstOrDefault(s => Has(s, "read", "dokkai") && !Has(s, "gram", "bunpo")) + ?? sections.FirstOrDefault(s => Has(s, "read", "gram", "language", "đọc")), + JlptStudySkill.Listening => sections.FirstOrDefault(s => Has(s, "listen", "chok", "chouk", "nghe")), + _ => null, + }; + return exact ?? sections[0]; + } + + private static JlptStudySkill ClassifyMockQuestionSkill(JsonElement q) + { + var sec = Str(q, "sectionCode") ?? Str(q, "section") ?? Str(q, "session") ?? ""; + var mondai = Str(q, "jlptMondai") ?? Str(q, "mondai") ?? ""; + var qtype = Str(q, "questionType") ?? ""; + + if (sec.Contains("LISTEN", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Listen", StringComparison.OrdinalIgnoreCase) || + mondai.StartsWith("Mondai 1", StringComparison.OrdinalIgnoreCase) && sec.Contains("Session2", StringComparison.OrdinalIgnoreCase) || + qtype.StartsWith("LISTEN", StringComparison.OrdinalIgnoreCase)) + return JlptStudySkill.Listening; + + if (mondai.Contains("Reading", StringComparison.OrdinalIgnoreCase) || + Str(q, "passageRefId") is not null || + Str(q, "passageId") is not null) + return JlptStudySkill.Reading; + + if (sec.Equals("VOCAB", StringComparison.OrdinalIgnoreCase) || + sec.Contains("Vocab", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Vocab", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Kanji", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Orthography", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Paraphrase", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Context", StringComparison.OrdinalIgnoreCase)) + return JlptStudySkill.Vocabulary; + + if (sec.Contains("GRAM", StringComparison.OrdinalIgnoreCase) || + mondai.Contains("Grammar", StringComparison.OrdinalIgnoreCase) || + qtype.Contains("STAR", StringComparison.OrdinalIgnoreCase)) + return JlptStudySkill.Grammar; + + return JlptStudySkill.Vocabulary; + } + + private static string CleanPythonList(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return string.Empty; + var trimmed = raw.Trim(); + var m = PythonListRegex.Match(trimmed); + if (!m.Success) return trimmed; + var parts = m.Groups[1].Value + .Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select(p => p.Trim().Trim('\'', '"', ' ')) + .Where(p => p.Length > 0); + return string.Join("、", parts); + } + + private static string SanitizeQuestionText(string raw) => + raw.Replace("Câu hỏi mẫu #", "Câu hỏi #", StringComparison.OrdinalIgnoreCase) + .Replace("(Chính xác)", "", StringComparison.OrdinalIgnoreCase) + .Trim(); + + private static string SanitizeOptionText(string raw) => + raw.Replace("(Chính xác)", "", StringComparison.OrdinalIgnoreCase) + .Replace("(Correct)", "", StringComparison.OrdinalIgnoreCase) + .Trim(); + + private static List DeduplicateOptions(List options) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var result = new List(options.Count); + foreach (var opt in options) + { + var val = string.IsNullOrWhiteSpace(opt) ? "—" : opt; + var unique = val; + var suffix = 2; + while (!seen.Add(unique)) + unique = $"{val} ({suffix++})"; + result.Add(unique); + } + return result; + } + + private static string? CombineScriptAndTranslation(string? script, string? trans) + { + if (string.IsNullOrWhiteSpace(script) && string.IsNullOrWhiteSpace(trans)) return null; + if (string.IsNullOrWhiteSpace(trans)) return script?.Trim(); + if (string.IsNullOrWhiteSpace(script)) return trans.Trim(); + return $"{script.Trim()}\n\n[Dịch] {trans.Trim()}"; + } + + private static PackageScope NormalizeScope( + List? levels, + List? topicCodes, + List? mockTestIds, + bool includeLessons, + bool includeVocabKanjiGrammar, + bool includePracticeExercises, + bool includeSrsTemplates, + bool includeMockTests, + bool uploadAssets) + { + var cleanLevels = (levels ?? []) + .Select(x => x?.Trim().ToUpperInvariant() ?? "") + .Where(x => SupportedLevels.Contains(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + if (cleanLevels.Count == 0) cleanLevels = [.. SupportedLevels]; + + var cleanTopics = (topicCodes ?? []) + .Select(x => x?.Trim().ToUpperInvariant() ?? "") + .Where(x => x.Length > 0) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + var cleanMocks = (mockTestIds ?? []) + .Select(x => x?.Trim().ToUpperInvariant() ?? "") + .Where(x => x.Length > 0) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + return new PackageScope( + cleanLevels, cleanTopics, cleanMocks, + includeLessons, includeVocabKanjiGrammar, includePracticeExercises, + includeSrsTemplates, includeMockTests, uploadAssets); + } + + private static string? Str(JsonElement? el, string name) => + el is { ValueKind: JsonValueKind.Object } obj && obj.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String + ? v.GetString()?.Trim() + : null; + + private static int IntVal(JsonElement? el, string name, int fallback = 0) + { + if (el is not { ValueKind: JsonValueKind.Object } obj || !obj.TryGetProperty(name, out var v)) + return fallback; + if (v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var i)) return i; + if (v.ValueKind == JsonValueKind.String && int.TryParse(v.GetString(), out var parsed)) return parsed; + return fallback; + } + + private static string Truncate(string value, int maxLen) => + value.Length <= maxLen ? value : value[..maxLen]; + + private static string? TruncateNullable(string? value, int maxLen) => + string.IsNullOrWhiteSpace(value) ? null : (value.Trim().Length <= maxLen ? value.Trim() : value.Trim()[..maxLen]); + + private sealed record PackageScope( + List Levels, + HashSet TopicCodes, + HashSet MockTestIds, + bool IncludeLessons, + bool IncludeVocabKanjiGrammar, + bool IncludePracticeExercises, + bool IncludeSrsTemplates, + bool IncludeMockTests, + bool UploadAssets); + + private sealed record CsvAssetRow( + string AssetType, + string Level, + string AssetExternalId, + string LinkedChapterOrExam, + string LinkedLessonId, + string LinkedQuestionId, + string LogicalAssetPath); + + private sealed record LessonSnap(int Id, string Title, int CertificateLevelId, string? SourceProvenance); + + private sealed class RichCurriculumData + { + public Dictionary LessonsById { get; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary ChapterAssessmentsById { get; } = new(StringComparer.OrdinalIgnoreCase); + } + + private sealed class StagedCandidate + { + public ImportEntityType EntityType { get; init; } + public ImportRowAction Action { get; init; } + public int? TargetEntityId { get; init; } + public string? PayloadJson { get; init; } + public bool CanStage { get; init; } + public CurriculumPackagePreviewItemResponse Preview { get; init; } = new(); + } + + private sealed class BuiltPackageResult(DbSnapshot snapshot) + { + public DbSnapshot Snapshot { get; } = snapshot; + public List Items { get; } = []; + public List Issues { get; } = []; + public HashSet ReferencedAudioKeys { get; } = new(StringComparer.OrdinalIgnoreCase); + public HashSet ReferencedImageKeys { get; } = new(StringComparer.OrdinalIgnoreCase); + public int UploadedAudioCount { get; set; } + public int UploadedImageCount { get; set; } + } + + private sealed class DbSnapshot + { + public Dictionary LevelIdByCode { get; init; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary SkillIdByName { get; init; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary SkillNameById { get; init; } = []; + public Dictionary> CertSectionsByLevelId { get; init; } = []; + public List Lessons { get; init; } = []; + public Dictionary VocabIdByWordReading { get; init; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary KanjiIdByChar { get; init; } = new(StringComparer.Ordinal); + public Dictionary GrammarIdByTitle { get; init; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary<(int LevelId, string Title), int> ExerciseIdByLevelTitle { get; init; } = []; + public Dictionary MockIdBySourceOrTitle { get; init; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary<(int LevelId, string Title), int> MockIdByLevelTitle { get; init; } = []; + public Dictionary SrsIdByNormalizedKey { get; init; } = new(StringComparer.OrdinalIgnoreCase); + public HashSet<(ImportEntityType, string)> OpenOrApprovedRowKeys { get; init; } = []; + public HashSet<(ImportEntityType, int)> OpenTargetIds { get; init; } = []; + public HashSet<(string LessonTitle, int LevelId, int VocabId)> LessonVocabPairs { get; init; } = []; + public HashSet<(string LessonTitle, int LevelId, int KanjiId)> LessonKanjiPairs { get; init; } = []; + public HashSet<(string LessonTitle, int LevelId, int GrammarId)> LessonGrammarPairs { get; init; } = []; + } +} diff --git a/RikiPath.Infrastructure/Services/MentorGroupPolicyService.cs b/RikiPath.Infrastructure/Services/MentorGroupPolicyService.cs index 5ea3fba..1ce0afb 100644 --- a/RikiPath.Infrastructure/Services/MentorGroupPolicyService.cs +++ b/RikiPath.Infrastructure/Services/MentorGroupPolicyService.cs @@ -218,6 +218,8 @@ public async Task> UpdateVersionAsync( PlacementAttemptLimit = request.PlacementAttemptLimit, RemediationCompletionThresholdPercent = request.RemediationCompletionThresholdPercent, RemediationThresholdComparison = request.RemediationThresholdComparison, + RetakeSupportEnabled = request.RetakeSupportEnabled ?? target.RetakeSupportEnabled, + RemediationAttendanceThresholdPercent = request.RemediationAttendanceThresholdPercent ?? target.RemediationAttendanceThresholdPercent, RequireOfficialExamEvidence = target.RequireOfficialExamEvidence, RequireAdminRemediationReview = target.RequireAdminRemediationReview, KpiReportingPeriodDays = request.KpiReportingPeriodDays, @@ -240,9 +242,18 @@ public async Task> UpdateSectionAsync( return ApiResponse.Fail("Phiên bản chính sách không hợp lệ.", HttpStatusCode.BadRequest); var normalizedSection = (sectionKey ?? string.Empty).Trim().ToLowerInvariant(); - if (normalizedSection is not ("structure" or "schedule" or "admission" or "coordination" or "training")) + if (normalizedSection is not ("structure" or "tuition" or "schedule" or "operations" or "admission" or "coordination" or "training" or "retake")) return ApiResponse.Fail("Nhóm cấu hình không hợp lệ.", HttpStatusCode.BadRequest); + // Card → fields: "tuition" and "operations" group the existing fields without new storage. + var structureSection = normalizedSection == "structure"; + var tuitionSection = normalizedSection is "structure" or "tuition"; + var scheduleSection = normalizedSection is "schedule" or "operations"; + var coordinationSection = normalizedSection is "coordination" or "operations"; + var admissionSection = normalizedSection == "admission"; + var trainingSection = normalizedSection == "training"; + var retakeSection = normalizedSection == "retake"; + return await SaveUpdatedPolicyAsync( policyId, adminId, @@ -251,67 +262,71 @@ public async Task> UpdateSectionAsync( target => new CreateMentorGroupPolicyRequest { ExpectedCurrentVersion = target.Version, - MaxLearners = normalizedSection == "structure" + MaxLearners = structureSection ? (request.MaxLearners ?? target.MaxLearners) : target.MaxLearners, - SessionMinutes = normalizedSection == "structure" + SessionMinutes = structureSection ? (request.SessionMinutes ?? target.SessionMinutes) : target.SessionMinutes, - TuitionPerSessionN5 = normalizedSection == "structure" + TuitionPerSessionN5 = tuitionSection ? (request.TuitionPerSessionN5 ?? target.TuitionPerSessionN5) : target.TuitionPerSessionN5, - TuitionPerSessionN4 = normalizedSection == "structure" + TuitionPerSessionN4 = tuitionSection ? (request.TuitionPerSessionN4 ?? target.TuitionPerSessionN4) : target.TuitionPerSessionN4, - TuitionPerSessionN3 = normalizedSection == "structure" + TuitionPerSessionN3 = tuitionSection ? (request.TuitionPerSessionN3 ?? target.TuitionPerSessionN3) : target.TuitionPerSessionN3, - TuitionPerSessionN2 = normalizedSection == "structure" + TuitionPerSessionN2 = tuitionSection ? (request.TuitionPerSessionN2 ?? target.TuitionPerSessionN2) : target.TuitionPerSessionN2, - RestMinutes = normalizedSection == "schedule" + RestMinutes = scheduleSection ? (request.RestMinutes ?? target.RestMinutes) : target.RestMinutes, - MinimumPreparationDays = normalizedSection == "schedule" + MinimumPreparationDays = scheduleSection ? (request.MinimumPreparationDays ?? target.MinimumPreparationDays) : target.MinimumPreparationDays, - MinimumPublishedEnrollmentDays = normalizedSection == "admission" + MinimumPublishedEnrollmentDays = admissionSection ? (request.MinimumPublishedEnrollmentDays ?? target.MinimumPublishedEnrollmentDays) : target.MinimumPublishedEnrollmentDays, - CheckoutHoldMinutes = normalizedSection == "admission" + CheckoutHoldMinutes = admissionSection ? (request.CheckoutHoldMinutes ?? target.CheckoutHoldMinutes) : target.CheckoutHoldMinutes, - CancellationLeadHours = normalizedSection == "coordination" + CancellationLeadHours = coordinationSection ? (request.CancellationLeadHours ?? target.CancellationLeadHours) : target.CancellationLeadHours, - ReschedulingLeadHours = normalizedSection == "coordination" + ReschedulingLeadHours = coordinationSection ? (request.ReschedulingLeadHours ?? target.ReschedulingLeadHours) : target.ReschedulingLeadHours, - MentorReplacementLeadHours = normalizedSection == "coordination" + MentorReplacementLeadHours = coordinationSection ? (request.MentorReplacementLeadHours ?? target.MentorReplacementLeadHours) : target.MentorReplacementLeadHours, - LearnerTransferEnabled = normalizedSection == "coordination" + LearnerTransferEnabled = coordinationSection ? (request.LearnerTransferEnabled ?? target.LearnerTransferEnabled) : target.LearnerTransferEnabled, TransferAllowedAfterSourceStart = false, - MentorReplacementEnabled = normalizedSection == "coordination" + MentorReplacementEnabled = coordinationSection ? (request.MentorReplacementEnabled ?? target.MentorReplacementEnabled) : target.MentorReplacementEnabled, - HomeworkDeadlineDays = normalizedSection == "training" + HomeworkDeadlineDays = trainingSection ? (request.HomeworkDeadlineDays ?? target.HomeworkDeadlineDays) : target.HomeworkDeadlineDays, - PlacementAttemptLimit = normalizedSection == "training" + PlacementAttemptLimit = trainingSection ? (request.PlacementAttemptLimit ?? target.PlacementAttemptLimit) : target.PlacementAttemptLimit, - RemediationCompletionThresholdPercent = normalizedSection == "training" + RemediationCompletionThresholdPercent = retakeSection || trainingSection ? (request.RemediationCompletionThresholdPercent ?? target.RemediationCompletionThresholdPercent) : target.RemediationCompletionThresholdPercent, - RemediationThresholdComparison = normalizedSection == "training" - ? (request.RemediationThresholdComparison ?? target.RemediationThresholdComparison) - : target.RemediationThresholdComparison, + RemediationThresholdComparison = CourseRetakePolicy.Comparison, + RetakeSupportEnabled = retakeSection + ? (request.RetakeSupportEnabled ?? target.RetakeSupportEnabled) + : target.RetakeSupportEnabled, + RemediationAttendanceThresholdPercent = retakeSection + ? (request.RemediationAttendanceThresholdPercent ?? target.RemediationAttendanceThresholdPercent) + : target.RemediationAttendanceThresholdPercent, RequireOfficialExamEvidence = target.RequireOfficialExamEvidence, RequireAdminRemediationReview = target.RequireAdminRemediationReview, - KpiReportingPeriodDays = normalizedSection == "training" + KpiReportingPeriodDays = trainingSection ? (request.KpiReportingPeriodDays ?? target.KpiReportingPeriodDays) : target.KpiReportingPeriodDays, }, @@ -699,7 +714,10 @@ private static void ApplyPolicyFields( policy.HomeworkDeadlineDays = request.HomeworkDeadlineDays; policy.PlacementAttemptLimit = request.PlacementAttemptLimit; policy.RemediationCompletionThresholdPercent = request.RemediationCompletionThresholdPercent; - policy.RemediationThresholdComparison = request.RemediationThresholdComparison; + // Retake support is always evaluated with ">="; the stored operator only documents that for new versions. + policy.RemediationThresholdComparison = CourseRetakePolicy.Comparison; + policy.RetakeSupportEnabled = request.RetakeSupportEnabled; + policy.RemediationAttendanceThresholdPercent = request.RemediationAttendanceThresholdPercent; policy.RequireOfficialExamEvidence = request.RequireOfficialExamEvidence; policy.RequireAdminRemediationReview = request.RequireAdminRemediationReview; policy.KpiReportingPeriodDays = request.KpiReportingPeriodDays; @@ -741,6 +759,8 @@ private Task LoadDetailedByIdAsync(int policyId, Cancellation policy.PlacementAttemptLimit, policy.RemediationCompletionThresholdPercent, policy.RemediationThresholdComparison, + policy.RetakeSupportEnabled, + policy.RemediationAttendanceThresholdPercent, policy.KpiReportingPeriodDays, policy.TuitionPerSessionN5, policy.TuitionPerSessionN4, @@ -778,9 +798,11 @@ private Task LoadDetailedByIdAsync(int policyId, Cancellation if (request.PlacementAttemptLimit is < 1 or > 20) return "Giới hạn lượt đánh giá năng lực phải từ 1 đến 20 lượt."; if (request.RemediationCompletionThresholdPercent is <= 0 or > 100) - return "Ngưỡng hoàn thành bài tập phải lớn hơn 0% và không vượt quá 100%."; + return "Tỷ lệ hoàn thành bài tập tối thiểu phải lớn hơn 0% và không vượt quá 100%."; if (request.RemediationThresholdComparison is not (">" or ">=")) return "Cách so sánh ngưỡng hoàn thành bài tập không hợp lệ."; + if (request.RemediationAttendanceThresholdPercent is <= 0 or > 100) + return "Tỷ lệ chuyên cần tối thiểu phải lớn hơn 0% và không vượt quá 100%."; if (!request.RequireOfficialExamEvidence || !request.RequireAdminRemediationReview) return "Yêu cầu học lại luôn cần minh chứng JLPT chính thức và quản trị viên xét duyệt."; if (request.KpiReportingPeriodDays is < 1 or > 365) diff --git a/RikiPath.Infrastructure/Services/MentorKpiDashboardService.cs b/RikiPath.Infrastructure/Services/MentorKpiDashboardService.cs new file mode 100644 index 0000000..55fc277 --- /dev/null +++ b/RikiPath.Infrastructure/Services/MentorKpiDashboardService.cs @@ -0,0 +1,620 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using RikiPath.Application.Helpers; +using RikiPath.Application.IServices; +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.MentorKpi; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Infrastructure.Services; + +/// +/// Chấm công & KPI Giáo viên — một bộ tính duy nhất cho Mentor, Admin (chi tiết) và tổng quan trung tâm. +/// Mọi tỷ lệ được xét trên tử số/mẫu số nguyên (không dùng phần trăm đã làm tròn); dữ liệu thiếu không bao giờ thành 0%/100%. +/// Không ghi hay sửa dữ liệu học tập; đối soát chỉ thêm lịch sử chấm công. +/// +public sealed class MentorKpiDashboardService(AppDbContext context, IClaimService claims) : IMentorKpiDashboardService +{ + private const int ReviewListLimit = 50; + + // ------------------------------------------------------------------ public API + + public async Task> GetMyDashboardAsync(string? month, string? level, int? cohortId, CancellationToken ct = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Mentor) + return ApiResponse.Fail("Chỉ Giáo viên mới xem được Chấm công & KPI cá nhân.", HttpStatusCode.Forbidden); + return await BuildMentorDashboardAsync(actor.Id, month, level, cohortId, adminView: false, ct); + } + + public async Task> GetMentorDashboardAsync(int mentorId, string? month, string? level, int? cohortId, CancellationToken ct = default) + { + if (claims.GetUserClaim().Role != Role.Admin) + return ApiResponse.Fail("Chỉ Quản trị viên được xem KPI của Giáo viên khác.", HttpStatusCode.Forbidden); + return await BuildMentorDashboardAsync(mentorId, month, level, cohortId, adminView: true, ct); + } + + public async Task> GetOverviewAsync(string? month, string? level, CancellationToken ct = default) + { + if (claims.GetUserClaim().Role != Role.Admin) + return ApiResponse.Fail("Chỉ Quản trị viên được xem KPI toàn trung tâm.", HttpStatusCode.Forbidden); + if (!KpiPeriod.TryParseMonth(month, out var period)) + return ApiResponse.Fail("Tháng thống kê không hợp lệ.", HttpStatusCode.BadRequest); + + var mentors = await context.Users.AsNoTracking() + .Where(u => u.Role == Role.Mentor && !u.IsDeleted) + .Select(u => new MentorInfo(u.Id, (u.FirstName + " " + u.LastName).Trim(), u.AvatarUrl)) + .ToListAsync(ct); + var data = await LoadAsync(mentors.Select(m => m.Id).ToList(), period, ct); + if (data.PeriodPolicy is null) + return ApiResponse.Fail("Chưa có chính sách chấm công & KPI có hiệu lực cho tháng này.", HttpStatusCode.ServiceUnavailable); + var normalizedLevel = NormalizeLevel(level); + + var results = mentors.Select(m => (Mentor: m, Calc: Compute(data, m.Id, normalizedLevel, null))).ToList(); + var total = Accumulator.Sum(results.Select(r => r.Calc.Acc)); + var metrics = BuildMetrics(total, data.PeriodPolicy, data.PeriodEnded); + + var rows = results.Select(r => new KpiMentorRowResponse( + r.Mentor.Id, string.IsNullOrWhiteSpace(r.Mentor.Name) ? $"#{r.Mentor.Id}" : r.Mentor.Name, r.Mentor.AvatarUrl, + r.Calc.ActiveLevels, r.Calc.Acc.Required, r.Calc.Acc.Taught, r.Calc.Acc.Pending, r.Calc.Acc.ConfirmedMinutes, + r.Calc.Acc.ReviewCount, r.Calc.Acc.AverageRating, + MetricFor(r.Calc.Acc, data.PeriodPolicy, data.PeriodEnded, "grading"), + MetricFor(r.Calc.Acc, data.PeriodPolicy, data.PeriodEnded, "onTime"), + MetricFor(r.Calc.Acc, data.PeriodPolicy, data.PeriodEnded, "homework"), + r.Calc.Acc.HasActivity)) + .OrderBy(r => r.MentorName, StringComparer.CurrentCultureIgnoreCase) + .ToList(); + + return ApiResponse.Success(new KpiOverviewResponse( + Month(period), data.PeriodEnded, data.NowUtc, normalizedLevel, + KpiPeriod.Snapshot(data.PeriodPolicy, period == KpiPeriod.CurrentMonth(data.NowUtc), false), + data.AllLevels, metrics, + results.Count(r => r.Calc.Acc.HasActivity), total.Taught, total.ConfirmedMinutes, total.ReviewCount, total.AverageRating, + rows)); + } + + public async Task> ReconcileAsync(int mentorId, int sessionId, ReconcileTimesheetRequest request, CancellationToken ct = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Admin) + return ApiResponse.Fail("Chỉ Quản trị viên được đối soát chấm công.", HttpStatusCode.Forbidden); + var reason = request.Reason?.Trim() ?? string.Empty; + if (reason.Length is 0 or > 1000) + return ApiResponse.Fail("Cần nhập lý do đối soát (tối đa 1000 ký tự).", HttpStatusCode.BadRequest); + if (request.Status is not (MentorTimesheetAdjustment.StatusTaught or MentorTimesheetAdjustment.StatusAbsent)) + return ApiResponse.Fail("Kết quả đối soát không hợp lệ.", HttpStatusCode.BadRequest); + if (request.Evidence is { Length: > 1000 }) + return ApiResponse.Fail("Căn cứ xác nhận tối đa 1000 ký tự.", HttpStatusCode.BadRequest); + + var strategy = context.Database.CreateExecutionStrategy(); + return await strategy.ExecuteAsync(async () => + { + await using var tx = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable, ct); + var cohortId = await context.Set().Where(s => s.Id == sessionId).Select(s => (int?)s.CohortId).FirstOrDefaultAsync(ct); + if (cohortId is null) return ApiResponse.NotFound("Không tìm thấy buổi học."); + var month = await context.Set().Where(s => s.Id == sessionId).Select(s => s.Availability.StartTime).FirstAsync(ct); + var data = await LoadAsync([mentorId], KpiPeriod.MonthOf(month), ct); + var calc = Compute(data, mentorId, null, null); + var row = calc.Timesheet.FirstOrDefault(r => r.SessionId == sessionId); + if (row is null) return ApiResponse.NotFound("Buổi học không thuộc Giáo viên này."); + if (row.Status != TimesheetStatus.Pending) + return ApiResponse.Fail("Chỉ đối soát buổi đang Chờ xác nhận.", HttpStatusCode.Conflict); + + int newMinutes; + if (request.Status == MentorTimesheetAdjustment.StatusTaught) + { + if (data.Sessions.Single(s => s.Id == sessionId).Status != "Completed") + return ApiResponse.Fail("Chỉ xác nhận giảng dạy cho buổi đã hoàn thành theo lifecycle.", HttpStatusCode.Conflict); + newMinutes = request.ConfirmedMinutes ?? -1; + if (newMinutes <= 0 || newMinutes > row.ScheduledMinutes) + return ApiResponse.Fail($"Thời lượng xác nhận phải lớn hơn 0 và không vượt quá {row.ScheduledMinutes} phút theo lịch.", HttpStatusCode.BadRequest); + } + else newMinutes = 0; + + var now = DateTime.UtcNow; + var adjustment = new MentorTimesheetAdjustment + { + CohortSessionId = sessionId, MentorId = mentorId, + PreviousStatus = row.Status, NewStatus = request.Status, + PreviousConfirmedMinutes = row.ConfirmedMinutes, NewConfirmedMinutes = newMinutes, + Reason = reason, Evidence = string.IsNullOrWhiteSpace(request.Evidence) ? null : request.Evidence.Trim(), + AdminId = actor.Id, CreatedAtUtc = now, + }; + context.MentorTimesheetAdjustments.Add(adjustment); + context.AdminAuditLogs.Add(new AdminAuditLog + { + ActorUserId = actor.Id, EntityType = "MentorTimesheet", EntityId = sessionId, Action = "Reconciled", Reason = reason, + BeforeJson = JsonSerializer.Serialize(new { mentorId, sessionId, row.Status, row.ConfirmedMinutes, row.PresenceMinutes, row.ScheduledMinutes, row.ReasonCode }), + AfterJson = JsonSerializer.Serialize(new { mentorId, sessionId, Status = request.Status, ConfirmedMinutes = newMinutes, adjustment.Evidence }), + CreatedAtUtc = now, + }); + await context.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + + var after = Compute(await LoadAsync([mentorId], KpiPeriod.MonthOf(month), ct), mentorId, null, null) + .Timesheet.First(r => r.SessionId == sessionId); + return ApiResponse.Success(after); + }); + } + + // ------------------------------------------------------------------ dashboard + + private async Task> BuildMentorDashboardAsync( + int mentorId, string? month, string? level, int? cohortId, bool adminView, CancellationToken ct) + { + if (!KpiPeriod.TryParseMonth(month, out var period)) + return ApiResponse.Fail("Tháng thống kê không hợp lệ.", HttpStatusCode.BadRequest); + var mentor = await context.Users.AsNoTracking() + .Where(u => u.Id == mentorId && u.Role == Role.Mentor && !u.IsDeleted) + .Select(u => new MentorInfo(u.Id, (u.FirstName + " " + u.LastName).Trim(), u.AvatarUrl)) + .FirstOrDefaultAsync(ct); + if (mentor is null) return ApiResponse.NotFound("Không tìm thấy Giáo viên."); + + var data = await LoadAsync([mentorId], period, ct); + if (data.PeriodPolicy is null) + return ApiResponse.Fail("Chưa có chính sách chấm công & KPI có hiệu lực cho tháng này.", HttpStatusCode.ServiceUnavailable); + + var normalizedLevel = NormalizeLevel(level); + var mentorCohorts = data.Cohorts.Values.Where(c => data.Sessions.Any(s => s.CohortId == c.Id && s.Availability.MentorId == mentorId) + || data.Homework.Any(h => h.CohortId == c.Id && h.MentorId == mentorId)) + .ToList(); + // Ownership: a Mentor (or an Admin URL) can only scope to a class this Mentor actually teaches. + if (cohortId.HasValue && mentorCohorts.All(c => c.Id != cohortId.Value)) + return ApiResponse.Fail("Lớp học không thuộc Giáo viên này.", HttpStatusCode.Forbidden); + + var calc = Compute(data, mentorId, normalizedLevel, cohortId, adminView); + var levelOptions = mentorCohorts.Select(LevelOf).Where(l => l is not null).Distinct().OrderBy(LevelOrder).Cast().ToList(); + var classOptions = mentorCohorts + .Where(c => normalizedLevel is null || LevelOf(c) == normalizedLevel) + .OrderByDescending(c => c.StartsAt) + .Select(c => new KpiFilterOptionResponse(c.Id, c.Name, LevelOf(c))) + .ToList(); + + return ApiResponse.Success(new MentorKpiDashboardResponse( + mentor.Id, string.IsNullOrWhiteSpace(mentor.Name) ? $"#{mentor.Id}" : mentor.Name, mentor.AvatarUrl, + Month(period), KpiPeriod.StartUtc(period), KpiPeriod.StartUtc(period.AddMonths(1)), data.PeriodEnded, data.NowUtc, + normalizedLevel, cohortId, + KpiPeriod.Snapshot(data.PeriodPolicy, period == KpiPeriod.CurrentMonth(data.NowUtc), false), + levelOptions, classOptions, calc.ActiveLevels, + new TeachingSummaryResponse(calc.Acc.Required, calc.Acc.Taught, calc.Acc.Pending, calc.Acc.Absent, calc.Acc.Cancelled, + calc.Acc.Upcoming, calc.Acc.InProgress, calc.Acc.ConfirmedMinutes, calc.Acc.ScheduledMinutesOfTaught), + new HomeworkSummaryResponse(calc.Acc.AssignedHomework, calc.Acc.RequiredHomework, calc.Acc.RecognizedHomework, + calc.Acc.ClassesWithTarget, calc.Acc.ClassesMeetingTarget, calc.Acc.Received, calc.Acc.Graded, + calc.Acc.Received - calc.Acc.Graded, calc.Acc.OverduePending, calc.Acc.GradedActivity, calc.Acc.Backlog, calc.Acc.Quizzes), + new ResponseSummaryResponse(calc.Acc.AverageResponseMinutes, calc.Acc.ResponseSamples, calc.Acc.SlaEligible, calc.Acc.SlaOnTime, + calc.Acc.SlaLate, calc.Acc.SlaOverdueUnanswered, calc.Acc.SlaOpen, calc.Acc.SlaHoursInUse.OrderBy(x => x).ToList(), calc.Weekly), + new RatingSummaryResponse(calc.Acc.ReviewCount, calc.Acc.AverageRating, calc.Acc.PositiveReviews, + Enumerable.Range(1, 5).ToDictionary(s => s, s => calc.Acc.RatingDistribution[s]), calc.Reviews), + BuildMetrics(calc.Acc, data.PeriodPolicy, data.PeriodEnded), + cohortId.HasValue ? [] : calc.Classes, + calc.Timesheet)); + } + + // ------------------------------------------------------------------ loading (bulk, no N+1) + + private sealed record MentorInfo(int Id, string Name, string? AvatarUrl); + + private sealed class Dataset + { + public DateOnly Period { get; init; } + public DateTime StartUtc { get; init; } + public DateTime EndUtc { get; init; } + public DateTime NowUtc { get; init; } + public bool PeriodEnded => NowUtc >= EndUtc; + public List Policies { get; init; } = []; + public MentorKpiPolicy? PeriodPolicy { get; init; } + public List Sessions { get; init; } = []; + public Dictionary Cohorts { get; init; } = []; + public Dictionary> RoomRecords { get; init; } = []; + public Dictionary> Adjustments { get; init; } = []; + public Dictionary AdminNames { get; init; } = []; + public List Homework { get; init; } = []; + public List Quizzes { get; init; } = []; + public List Reviews { get; init; } = []; + public List AllLevels { get; init; } = []; + } + + private async Task LoadAsync(IReadOnlyCollection mentorIds, DateOnly period, CancellationToken ct) + { + var startUtc = KpiPeriod.StartUtc(period); + var endUtc = KpiPeriod.StartUtc(period.AddMonths(1)); + var policies = await context.MentorKpiPolicies.AsNoTracking().Include(p => p.CreatedByAdmin) + .Where(p => !p.IsDeleted).ToListAsync(ct); + + // Sessions up to the end of the period (earlier months are needed for cumulative homework targets). + var sessions = await context.Set().AsNoTracking() + .Include(s => s.Availability) + .Where(s => mentorIds.Contains(s.Availability.MentorId) && !s.Availability.IsDeleted + && s.Availability.StartTime < endUtc + && s.Cohort.Status != "Draft" && s.Cohort.Status != "Cancelled" && s.Cohort.EnrollmentClosedAtUtc != null) + .ToListAsync(ct); + + var homework = await context.HomeworkAssignments.AsNoTracking() + .Include(h => h.Submission) + .Where(h => mentorIds.Contains(h.MentorId) && !h.IsDeleted && h.CohortId != null && h.CreatedDate < endUtc) + .ToListAsync(ct); + + var cohortIds = sessions.Select(s => s.CohortId).Concat(homework.Select(h => h.CohortId!.Value)).Distinct().ToList(); + var cohorts = await context.StudyCohorts.AsNoTracking() + .Include(c => c.Plan).ThenInclude(p => p.CertificateLevel) + .Where(c => cohortIds.Contains(c.Id) && c.Status != "Cancelled") + .ToDictionaryAsync(c => c.Id, ct); + sessions = sessions.Where(s => cohorts.ContainsKey(s.CohortId)).ToList(); + homework = homework.Where(h => cohorts.ContainsKey(h.CohortId!.Value)).ToList(); + + var allRooms = sessions.Select(s => s.Availability.RoomId).Distinct().ToList(); + var records = allRooms.Count == 0 ? [] : await context.MentorAttendanceRecords.AsNoTracking() + .Where(r => allRooms.Contains(r.RoomId)).ToListAsync(ct); + + var sessionIds = sessions.Select(s => s.Id).ToList(); + var adjustments = sessionIds.Count == 0 ? [] : await context.MentorTimesheetAdjustments.AsNoTracking() + .Where(a => sessionIds.Contains(a.CohortSessionId)).ToListAsync(ct); + var adminIds = adjustments.Select(a => a.AdminId).Distinct().ToList(); + var adminNames = adminIds.Count == 0 ? new Dictionary() : await context.Users.AsNoTracking() + .Where(u => adminIds.Contains(u.Id)).ToDictionaryAsync(u => u.Id, u => (u.FirstName + " " + u.LastName).Trim(), ct); + + var quizzes = await context.ClassQuizzes.AsNoTracking() + .Where(q => mentorIds.Contains(q.MentorId) && !q.IsDeleted && q.Status == "Published" + && q.PublishedAtUtc >= startUtc && q.PublishedAtUtc < endUtc) + .ToListAsync(ct); + + var reviews = await CohortReviewRatingQuery.Valid(context.CohortMentorReviews.AsNoTracking()) + .Where(r => mentorIds.Contains(r.MentorId) && !r.IsHidden && r.CreatedAtUtc >= startUtc && r.CreatedAtUtc < endUtc) + .ToListAsync(ct); + var reviewCohortIds = reviews.Where(r => r.CohortId.HasValue && !cohorts.ContainsKey(r.CohortId.Value)).Select(r => r.CohortId!.Value).Distinct().ToList(); + if (reviewCohortIds.Count > 0) + foreach (var c in await context.StudyCohorts.AsNoTracking().Include(c => c.Plan).ThenInclude(p => p.CertificateLevel) + .Where(c => reviewCohortIds.Contains(c.Id)).ToListAsync(ct)) + cohorts[c.Id] = c; + + var allLevels = await context.CertificateLevels.AsNoTracking() + .Where(l => !l.IsDeleted && l.Code != null) + .OrderBy(l => l.SortOrder).Select(l => l.Code!).ToListAsync(ct); + + var nowUtc = DateTime.UtcNow; + return new Dataset + { + Period = period, StartUtc = startUtc, EndUtc = endUtc, NowUtc = nowUtc, + Policies = policies, PeriodPolicy = KpiPeriod.PolicyFor(policies, period), + Sessions = sessions, Cohorts = cohorts, + RoomRecords = records.GroupBy(r => r.RoomId).ToDictionary(g => g.Key, g => g.ToList()), + Adjustments = adjustments.GroupBy(a => a.CohortSessionId).ToDictionary(g => g.Key, g => g.OrderBy(a => a.CreatedAtUtc).ThenBy(a => a.Id).ToList()), + AdminNames = adminNames, + Homework = homework, Quizzes = quizzes, Reviews = reviews, + AllLevels = allLevels.Select(l => l.Trim().ToUpperInvariant()).Distinct().ToList(), + }; + } + + // ------------------------------------------------------------------ calculation + + private sealed class Accumulator + { + public int Required, Taught, Pending, Absent, Cancelled, Upcoming, InProgress, ConfirmedMinutes, ScheduledMinutesOfTaught; + public int AssignedHomework, RequiredHomework, RecognizedHomework, ClassesWithTarget, ClassesMeetingTarget; + public bool HomeworkTargetDisabled; + public int Received, Graded, OverduePending, GradedActivity, Backlog, Quizzes; + public int SlaEligible, SlaOnTime, SlaLate, SlaOverdueUnanswered, SlaOpen; + public double ResponseMinutesSum; + public int ResponseSamples; + public HashSet SlaHoursInUse = []; + public int ReviewCount, ReviewSum, PositiveReviews; + public Dictionary RatingDistribution = Enumerable.Range(1, 5).ToDictionary(s => s, _ => 0); + + public double? AverageResponseMinutes => ResponseSamples > 0 ? ResponseMinutesSum / ResponseSamples : null; + public decimal? AverageRating => ReviewCount > 0 ? (decimal)ReviewSum / ReviewCount : null; + public bool HasActivity => Required + Upcoming + InProgress + Cancelled + AssignedHomework + Received + Quizzes + ReviewCount > 0; + + public static Accumulator Sum(IEnumerable items) + { + var t = new Accumulator(); + foreach (var a in items) + { + t.Required += a.Required; t.Taught += a.Taught; t.Pending += a.Pending; t.Absent += a.Absent; t.Cancelled += a.Cancelled; + t.Upcoming += a.Upcoming; t.InProgress += a.InProgress; t.ConfirmedMinutes += a.ConfirmedMinutes; + t.ScheduledMinutesOfTaught += a.ScheduledMinutesOfTaught; + t.AssignedHomework += a.AssignedHomework; t.RequiredHomework += a.RequiredHomework; t.RecognizedHomework += a.RecognizedHomework; + t.ClassesWithTarget += a.ClassesWithTarget; t.ClassesMeetingTarget += a.ClassesMeetingTarget; + t.HomeworkTargetDisabled |= a.HomeworkTargetDisabled; + t.Received += a.Received; t.Graded += a.Graded; t.OverduePending += a.OverduePending; t.GradedActivity += a.GradedActivity; + t.Backlog += a.Backlog; t.Quizzes += a.Quizzes; + t.SlaEligible += a.SlaEligible; t.SlaOnTime += a.SlaOnTime; t.SlaLate += a.SlaLate; + t.SlaOverdueUnanswered += a.SlaOverdueUnanswered; t.SlaOpen += a.SlaOpen; + t.ResponseMinutesSum += a.ResponseMinutesSum; t.ResponseSamples += a.ResponseSamples; + t.SlaHoursInUse.UnionWith(a.SlaHoursInUse); + t.ReviewCount += a.ReviewCount; t.ReviewSum += a.ReviewSum; t.PositiveReviews += a.PositiveReviews; + foreach (var kv in a.RatingDistribution) t.RatingDistribution[kv.Key] += kv.Value; + } + return t; + } + } + + private sealed record Calculation( + Accumulator Acc, + List ActiveLevels, + List Timesheet, + List Classes, + List Weekly, + List Reviews); + + private sealed record SessionEval(TimesheetRowResponse Row, DateOnly Month); + + private Calculation Compute(Dataset d, int mentorId, string? level, int? cohortId, bool adminView = false) + { + bool InScope(int cid) => d.Cohorts.TryGetValue(cid, out var c) + && (cohortId is null || cid == cohortId) && (level is null || LevelOf(c) == level); + + var acc = new Accumulator(); + var evals = d.Sessions + .Where(s => s.Availability.MentorId == mentorId && InScope(s.CohortId)) + .Select(s => Evaluate(d, s, adminView)) + .ToList(); + + // ---- Teaching (month of the scheduled date, business time zone) + var periodRows = evals.Where(e => e.Month == d.Period).Select(e => e.Row).ToList(); + foreach (var r in periodRows) + { + switch (r.Status) + { + case TimesheetStatus.Taught: acc.Taught++; acc.ConfirmedMinutes += r.ConfirmedMinutes; acc.ScheduledMinutesOfTaught += r.ScheduledMinutes; break; + case TimesheetStatus.Pending: acc.Pending++; break; + case TimesheetStatus.Absent: acc.Absent++; break; + case TimesheetStatus.Cancelled: acc.Cancelled++; break; + case TimesheetStatus.InProgress: acc.InProgress++; break; + default: acc.Upcoming++; break; + } + } + acc.Required = acc.Taught + acc.Pending + acc.Absent; + + // ---- Homework (one "giao bài" per class = one assignment group; per-learner rows are not counted twice) + var policy = d.PeriodPolicy!; + acc.HomeworkTargetDisabled = policy.HomeworkMinimumCount == 0; + var mentorHomework = d.Homework.Where(h => h.MentorId == mentorId && InScope(h.CohortId!.Value)).ToList(); + var units = mentorHomework + .GroupBy(h => (Cohort: h.CohortId!.Value, Key: h.CohortAssignmentGroupKey?.ToString() ?? $"id:{h.Id}")) + .Select(g => (g.Key.Cohort, AssignedAt: g.Min(h => h.CreatedDate ?? DateTime.MaxValue))) + .ToList(); + acc.AssignedHomework = units.Count(u => u.AssignedAt >= d.StartUtc && u.AssignedAt < d.EndUtc); + + var classRows = new List(); + var taughtByCohort = evals.Where(e => e.Row.Status == TimesheetStatus.Taught).GroupBy(e => e.Row.CohortId) + .ToDictionary(g => g.Key, g => g.Select(e => e.Row.ScheduledStartUtc).ToList()); + foreach (var cid in evals.Select(e => e.Row.CohortId).Concat(units.Select(u => u.Cohort)).Distinct()) + { + var taughtStarts = taughtByCohort.GetValueOrDefault(cid) ?? []; + int TaughtBefore(DateTime t) => taughtStarts.Count(x => x < t); + int Req(DateTime t) => acc.HomeworkTargetDisabled ? 0 + : (int)Math.Ceiling(TaughtBefore(t) * (decimal)policy.HomeworkMinimumCount / policy.HomeworkPerSessionCount); + int AssignedBefore(DateTime t) => units.Count(u => u.Cohort == cid && u.AssignedAt < t); + var reqStart = Req(d.StartUtc); + var reqEnd = Req(d.EndUtc); + var satisfiedStart = Math.Min(AssignedBefore(d.StartUtc), reqStart); + var satisfiedEnd = Math.Min(AssignedBefore(d.EndUtc), reqEnd); + var requiredInPeriod = reqEnd - reqStart; + // Earlier extra homework of the SAME class may cover this period; a deficit made up later is capped so no + // class compensates another and no assignment is counted in two periods. + var recognized = Math.Clamp(satisfiedEnd - satisfiedStart, 0, requiredInPeriod); + if (requiredInPeriod > 0) + { + acc.RequiredHomework += requiredInPeriod; + acc.RecognizedHomework += recognized; + acc.ClassesWithTarget++; + if (recognized >= requiredInPeriod) acc.ClassesMeetingTarget++; + } + var classPeriodRows = periodRows.Where(r => r.CohortId == cid).ToList(); + var cohort = d.Cohorts[cid]; + classRows.Add(new KpiClassRowResponse(cid, cohort.Name, LevelOf(cohort), + classPeriodRows.Count(r => r.Status is TimesheetStatus.Taught or TimesheetStatus.Pending or TimesheetStatus.Absent), + classPeriodRows.Count(r => r.Status == TimesheetStatus.Taught), + classPeriodRows.Where(r => r.Status == TimesheetStatus.Taught).Sum(r => r.ConfirmedMinutes), + units.Count(u => u.Cohort == cid && u.AssignedAt >= d.StartUtc && u.AssignedAt < d.EndUtc), + requiredInPeriod, recognized)); + } + + // ---- Grading, SLA, response time (submissions = per learner work) + var weekly = new Dictionary Sla)>(); + foreach (var h in mentorHomework) + { + var sub = h.Submission is { IsDeleted: false } s ? s : null; + if (sub is null) continue; + var submitted = Utc(sub.SubmittedAt); + DateTime? published = h.PublishedFeedbackAtUtc.HasValue ? Utc(h.PublishedFeedbackAtUtc.Value) : null; + var subPolicy = KpiPeriod.PolicyFor(d.Policies, KpiPeriod.MonthOf(submitted)) ?? policy; + var deadline = submitted.AddHours(subPolicy.ResponseSlaHours); + var inPeriod = submitted >= d.StartUtc && submitted < d.EndUtc; + + if (inPeriod) + { + acc.Received++; + if (published.HasValue) acc.Graded++; + else if (deadline < d.NowUtc) acc.OverduePending++; + } + if (published.HasValue && published >= d.StartUtc && published < d.EndUtc) acc.GradedActivity++; + if (submitted < d.StartUtc && (!published.HasValue || published >= d.StartUtc)) acc.Backlog++; + + // SLA cohort = submissions whose response deadline falls in this period. + if (deadline >= d.StartUtc && deadline < d.EndUtc) + { + if (published.HasValue && published >= submitted) + { + acc.SlaEligible++; + var onTime = published <= deadline; + if (onTime) acc.SlaOnTime++; else acc.SlaLate++; + acc.SlaHoursInUse.Add(subPolicy.ResponseSlaHours); + var minutes = (published.Value - submitted).TotalMinutes; + acc.ResponseMinutesSum += minutes; + acc.ResponseSamples++; + var week = WeekStart(KpiPeriod.LocalDate(published.Value)); + var w = weekly.TryGetValue(week, out var existing) ? existing : (Sum: 0d, N: 0, OnTime: 0, Sla: new HashSet()); + w.Sum += minutes; w.N++; if (onTime) w.OnTime++; w.Sla.Add(subPolicy.ResponseSlaHours); + weekly[week] = w; + } + else if (!published.HasValue) + { + if (deadline <= d.NowUtc) { acc.SlaEligible++; acc.SlaOverdueUnanswered++; acc.SlaHoursInUse.Add(subPolicy.ResponseSlaHours); } + else acc.SlaOpen++; + } + } + } + var monthStart = d.Period; + var monthEnd = d.Period.AddMonths(1).AddDays(-1); + var weeklyPoints = weekly.OrderBy(kv => kv.Key).Select(kv => new ResponseTimePointResponse( + kv.Key < monthStart ? monthStart : kv.Key, + kv.Key.AddDays(6) > monthEnd ? monthEnd : kv.Key.AddDays(6), + kv.Value.N > 0 ? kv.Value.Sum / kv.Value.N : null, kv.Value.N, kv.Value.OnTime, + kv.Value.Sla.Count == 1 ? kv.Value.Sla.First() : kv.Value.Sla.DefaultIfEmpty(0).Max())) + .ToList(); + + // ---- Quizzes (statistics only; auto-graded, never part of grading KPI) + acc.Quizzes = d.Quizzes.Count(q => q.MentorId == mentorId && InScope(q.CohortId)); + + // ---- Reviews + var reviewItems = new List(); + foreach (var r in d.Reviews.Where(r => r.MentorId == mentorId + && (r.CohortId is null ? cohortId is null && level is null : InScope(r.CohortId.Value))) + .OrderByDescending(r => r.CreatedAtUtc)) + { + var star = Math.Clamp(r.Rating, 1, 5); + acc.ReviewCount++; acc.ReviewSum += star; acc.RatingDistribution[star]++; + if (star >= MentorKpiPolicy.PositiveRatingMinimum) acc.PositiveReviews++; + if (reviewItems.Count < ReviewListLimit) + reviewItems.Add(new ReviewItemResponse(r.Id, star, r.Comment, + r.CohortId.HasValue && d.Cohorts.TryGetValue(r.CohortId.Value, out var rc) ? rc.Name : null, r.CreatedAtUtc)); + } + + var activeLevels = periodRows.Where(r => r.Status is TimesheetStatus.Taught or TimesheetStatus.Pending or TimesheetStatus.Absent or TimesheetStatus.InProgress) + .Select(r => r.LevelCode).Where(l => l is not null).Cast().Distinct().OrderBy(LevelOrder).ToList(); + + return new Calculation(acc, activeLevels, + periodRows.OrderByDescending(r => r.ScheduledStartUtc).ToList(), + classRows.Where(c => c.RequiredSessions + c.AssignedHomework + c.RequiredHomework > 0 + || periodRows.Any(r => r.CohortId == c.CohortId)) + .OrderBy(c => c.CohortName, StringComparer.CurrentCultureIgnoreCase).ToList(), + weeklyPoints, reviewItems); + } + + /// + /// Timesheet rule (approved): latest Admin reconciliation wins → otherwise a session completed through the lifecycle + /// with the Mentor AND at least one learner having joined the room is credited its scheduled minutes (covers the + /// Time Skip demo flow; no meeting logs are created) → otherwise Mentor presence ≥ policy minimum gives + /// min(presence, scheduled) → otherwise "Chờ xác nhận". Missing data is never turned into an absence. + /// + private SessionEval Evaluate(Dataset d, StudyCohortSession s, bool adminView) + { + var start = Utc(s.Availability.StartTime); + var end = Utc(s.Availability.EndTime); + var scheduled = Math.Max(0, (int)Math.Round((end - start).TotalMinutes)); + var month = KpiPeriod.MonthOf(start); + var monthPolicy = KpiPeriod.PolicyFor(d.Policies, month) ?? d.PeriodPolicy!; + var cohort = d.Cohorts[s.CohortId]; + var records = d.RoomRecords.GetValueOrDefault(s.Availability.RoomId) ?? []; + var mentorRecord = records.Where(r => r.UserId == s.Availability.MentorId && r.Role == "Mentor").ToList(); + int? presenceMinutes = mentorRecord.Count == 0 ? null : (int)Math.Floor(mentorRecord.Sum(r => r.TotalDurationSeconds) / 60d); + var mentorJoined = mentorRecord.Any(r => r.FirstJoinedAtUtc != null) || s.ActualStartedAtUtc != null; + var learnerJoined = records.Any(r => r.Role == "Learner" && r.FirstJoinedAtUtc != null); + var adjustments = d.Adjustments.GetValueOrDefault(s.Id) ?? []; + + string status; string? source = null; string? reason = null; var confirmed = 0; + var latest = adjustments.LastOrDefault(); + if (s.Status is "Cancelled" or "Rescheduled") + { + status = TimesheetStatus.Cancelled; reason = s.Status; + } + else if (latest is not null) + { + status = latest.NewStatus == MentorTimesheetAdjustment.StatusTaught ? TimesheetStatus.Taught : TimesheetStatus.Absent; + confirmed = latest.NewConfirmedMinutes; source = TimesheetSource.AdminAdjustment; + } + else if (s.Status == "Completed") + { + if (mentorJoined && learnerJoined) + { + status = TimesheetStatus.Taught; confirmed = scheduled; source = TimesheetSource.CompletionFlow; + } + else if (presenceMinutes is int p && scheduled > 0 && (decimal)p * 100m >= scheduled * monthPolicy.MinimumPresencePercent) + { + status = TimesheetStatus.Taught; confirmed = Math.Min(p, scheduled); source = TimesheetSource.Presence; + } + else + { + status = TimesheetStatus.Pending; + reason = presenceMinutes is null ? "NoPresenceData" : !learnerJoined ? "NoLearnerJoined" : "PresenceBelowMinimum"; + } + } + else if (s.Status == "InProgress") + { + status = TimesheetStatus.InProgress; + } + else if (end <= d.NowUtc) + { + status = TimesheetStatus.Pending; reason = "NotCompleted"; + } + else status = TimesheetStatus.Upcoming; + + var row = new TimesheetRowResponse( + s.Id, cohort.Id, cohort.Name, LevelOf(cohort), s.Number, start, end, scheduled, presenceMinutes, confirmed, + status, source, reason, + s.ActualStartedAtUtc.HasValue ? Utc(s.ActualStartedAtUtc.Value) : null, + s.ActualEndedAtUtc.HasValue ? Utc(s.ActualEndedAtUtc.Value) : null, + learnerJoined, + adminView && status == TimesheetStatus.Pending, + adjustments.Select(a => new TimesheetAdjustmentResponse(a.Id, a.PreviousStatus, a.NewStatus, a.PreviousConfirmedMinutes, + a.NewConfirmedMinutes, a.Reason, a.Evidence, d.AdminNames.GetValueOrDefault(a.AdminId), a.CreatedAtUtc)).ToList()); + return new SessionEval(row, month); + } + + // ------------------------------------------------------------------ metrics + + private static readonly string[] MetricKeys = ["teaching", "homework", "grading", "onTime", "averageRating", "positive"]; + + private static List BuildMetrics(Accumulator a, MentorKpiPolicy p, bool periodEnded) + => MetricKeys.Select(k => MetricFor(a, p, periodEnded, k)).ToList(); + + private static KpiMetricResponse MetricFor(Accumulator a, MentorKpiPolicy p, bool periodEnded, string key) + { + var provisional = !periodEnded; + static decimal Pct(int n, int dd) => dd == 0 ? 0 : (decimal)n * 100m / dd; + static bool AtLeast(int n, int dd, decimal target) => (decimal)n * 100m >= dd * target; + switch (key) + { + case "teaching": + if (a.Required == 0) return new(key, null, p.TeachingCompletionTargetPercent, 0, 0, KpiStatus.NoData, provisional); + return new(key, Pct(a.Taught, a.Required), p.TeachingCompletionTargetPercent, a.Taught, a.Required, + AtLeast(a.Taught, a.Required, p.TeachingCompletionTargetPercent) ? KpiStatus.Met + : a.Pending > 0 ? KpiStatus.PendingConfirmation : KpiStatus.NotMet, provisional); + case "homework": + if (a.HomeworkTargetDisabled) return new(key, null, null, a.AssignedHomework, null, KpiStatus.NotApplicable, provisional); + if (a.RequiredHomework == 0) return new(key, null, 100, a.RecognizedHomework, 0, KpiStatus.NoData, provisional); + return new(key, Pct(a.RecognizedHomework, a.RequiredHomework), 100, a.RecognizedHomework, a.RequiredHomework, + a.RecognizedHomework >= a.RequiredHomework ? KpiStatus.Met : KpiStatus.NotMet, provisional); + case "grading": + if (a.Received == 0) return new(key, null, p.GradingCompletionTargetPercent, 0, 0, KpiStatus.NoData, provisional); + var openWithin = a.Received - a.Graded - a.OverduePending; + return new(key, Pct(a.Graded, a.Received), p.GradingCompletionTargetPercent, a.Graded, a.Received, + AtLeast(a.Graded, a.Received, p.GradingCompletionTargetPercent) ? KpiStatus.Met + : openWithin > 0 ? KpiStatus.PendingConfirmation : KpiStatus.NotMet, provisional); + case "onTime": + if (a.SlaEligible == 0) return new(key, null, p.OnTimeResponseTargetPercent, 0, 0, KpiStatus.NoData, provisional); + return new(key, Pct(a.SlaOnTime, a.SlaEligible), p.OnTimeResponseTargetPercent, a.SlaOnTime, a.SlaEligible, + AtLeast(a.SlaOnTime, a.SlaEligible, p.OnTimeResponseTargetPercent) ? KpiStatus.Met : KpiStatus.NotMet, provisional); + case "averageRating": + if (a.ReviewCount == 0) return new(key, null, p.AverageRatingTarget, 0, 0, KpiStatus.NoData, provisional); + return new(key, a.AverageRating, p.AverageRatingTarget, a.ReviewSum, a.ReviewCount, + a.ReviewSum >= a.ReviewCount * p.AverageRatingTarget ? KpiStatus.Met : KpiStatus.NotMet, provisional); + default: // positive + if (a.ReviewCount == 0) return new("positive", null, p.PositiveReviewTargetPercent, 0, 0, KpiStatus.NoData, provisional); + return new("positive", Pct(a.PositiveReviews, a.ReviewCount), p.PositiveReviewTargetPercent, a.PositiveReviews, a.ReviewCount, + AtLeast(a.PositiveReviews, a.ReviewCount, p.PositiveReviewTargetPercent) ? KpiStatus.Met : KpiStatus.NotMet, provisional); + } + } + + // ------------------------------------------------------------------ helpers + + private static DateTime Utc(DateTime value) => value.Kind == DateTimeKind.Utc ? value : DateTime.SpecifyKind(value, DateTimeKind.Utc); + private static string Month(DateOnly m) => $"{m.Year:D4}-{m.Month:D2}"; + private static DateOnly WeekStart(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7)); + private static string? LevelOf(StudyCohort c) => c.Plan?.CertificateLevel?.Code?.Trim().ToUpperInvariant(); + private static int LevelOrder(string? code) => code is { Length: > 1 } && int.TryParse(code[1..], out var n) ? -n : 0; + private static string? NormalizeLevel(string? level) => string.IsNullOrWhiteSpace(level) ? null : level.Trim().ToUpperInvariant(); +} diff --git a/RikiPath.Infrastructure/Services/MentorKpiPolicyService.cs b/RikiPath.Infrastructure/Services/MentorKpiPolicyService.cs new file mode 100644 index 0000000..9fdfe93 --- /dev/null +++ b/RikiPath.Infrastructure/Services/MentorKpiPolicyService.cs @@ -0,0 +1,184 @@ +using System.Data; +using System.Globalization; +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using RikiPath.Application.IServices; +using RikiPath.Application.Responses; +using RikiPath.Application.Responses.MentorKpi; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Infrastructure.Services; + +/// +/// Chính sách chấm công & KPI: phiên bản đã ban hành không bị sửa; phiên bản mới chỉ có hiệu lực từ đầu một tháng +/// sau tháng hiện tại, nên báo cáo các tháng đã qua/đang diễn ra không bị thay đổi hồi tố. +/// +public sealed class MentorKpiPolicyService(AppDbContext context, IClaimService claims) : IMentorKpiPolicyService +{ + public async Task> GetCurrentAsync(CancellationToken ct = default) + { + if (claims.GetUserClaim().Role is not (Role.Admin or Role.Mentor)) + return ApiResponse.Fail("Bạn không có quyền xem chính sách này.", HttpStatusCode.Forbidden); + var month = KpiPeriod.CurrentMonth(); + var policy = await KpiPeriod.PolicyForMonthAsync(context, month, ct); + if (policy is null) + return ApiResponse.Fail("Chưa có chính sách chấm công & KPI có hiệu lực.", HttpStatusCode.ServiceUnavailable); + return ApiResponse.Success(KpiPeriod.Snapshot(policy, isCurrent: true, canDelete: false)); + } + + public async Task>> GetHistoryAsync(CancellationToken ct = default) + { + if (claims.GetUserClaim().Role != Role.Admin) + return ApiResponse>.Fail("Chỉ Quản trị viên được xem lịch sử chính sách.", HttpStatusCode.Forbidden); + var month = KpiPeriod.CurrentMonth(); + var rows = await context.MentorKpiPolicies.AsNoTracking().Include(p => p.CreatedByAdmin) + .Where(p => !p.IsDeleted).OrderByDescending(p => p.Version).ToListAsync(ct); + var current = rows.Where(p => p.EffectiveFromMonth <= month).OrderByDescending(p => p.EffectiveFromMonth).FirstOrDefault(); + return ApiResponse>.Success(rows + .Select(p => KpiPeriod.Snapshot(p, p.Id == current?.Id, canDelete: p.EffectiveFromMonth > month)) + .ToList()); + } + + public async Task> PublishAsync(PublishMentorKpiPolicyRequest r, CancellationToken ct = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Admin) + return ApiResponse.Fail("Chỉ Quản trị viên được ban hành chính sách.", HttpStatusCode.Forbidden); + var error = Validate(r, out var effectiveMonth); + if (error is not null) + return ApiResponse.Fail(error, HttpStatusCode.BadRequest); + + var strategy = context.Database.CreateExecutionStrategy(); + return await strategy.ExecuteAsync(async () => + { + await using var tx = await context.Database.BeginTransactionAsync(IsolationLevel.Serializable, ct); + var latest = await context.MentorKpiPolicies.Where(p => !p.IsDeleted).MaxAsync(p => (int?)p.Version, ct) ?? 0; + if (latest != r.ExpectedLatestVersion) + return ApiResponse.Fail("Chính sách vừa được cập nhật. Vui lòng tải lại trước khi ban hành.", HttpStatusCode.Conflict); + if (await context.MentorKpiPolicies.AnyAsync(p => !p.IsDeleted && p.EffectiveFromMonth == effectiveMonth, ct)) + return ApiResponse.Fail("Đã có phiên bản có hiệu lực từ tháng này. Xóa phiên bản đó trước khi ban hành lại.", HttpStatusCode.Conflict); + var nextVersion = (await context.MentorKpiPolicies.MaxAsync(p => (int?)p.Version, ct) ?? 0) + 1; + var policy = new MentorKpiPolicy + { + Version = nextVersion, + EffectiveFromMonth = effectiveMonth, + MinimumPresencePercent = r.MinimumPresencePercent, + TeachingCompletionTargetPercent = r.TeachingCompletionTargetPercent, + HomeworkMinimumCount = r.HomeworkMinimumCount, + HomeworkPerSessionCount = r.HomeworkPerSessionCount, + GradingCompletionTargetPercent = r.GradingCompletionTargetPercent, + ResponseSlaHours = r.ResponseSlaHours, + OnTimeResponseTargetPercent = r.OnTimeResponseTargetPercent, + AverageRatingTarget = r.AverageRatingTarget, + PositiveReviewTargetPercent = r.PositiveReviewTargetPercent, + Note = string.IsNullOrWhiteSpace(r.Note) ? null : r.Note.Trim(), + CreatedByAdminId = actor.Id, + CreatedAtUtc = DateTime.UtcNow, + }; + context.MentorKpiPolicies.Add(policy); + await context.SaveChangesAsync(ct); + context.AdminAuditLogs.Add(new AdminAuditLog + { + ActorUserId = actor.Id, + EntityType = "MentorKpiPolicy", + EntityId = policy.Version, + Action = "Published", + AfterJson = JsonSerializer.Serialize(KpiPeriod.Snapshot(policy, false, true)), + CreatedAtUtc = policy.CreatedAtUtc, + }); + await context.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return ApiResponse.Created(KpiPeriod.Snapshot(policy, false, true)); + }); + } + + public async Task> DeleteAsync(int id, CancellationToken ct = default) + { + var actor = claims.GetUserClaim(); + if (actor.Role != Role.Admin) + return ApiResponse.Fail("Chỉ Quản trị viên được xóa phiên bản chính sách.", HttpStatusCode.Forbidden); + var policy = await context.MentorKpiPolicies.FirstOrDefaultAsync(p => p.Id == id && !p.IsDeleted, ct); + if (policy is null) return ApiResponse.NotFound("Không tìm thấy phiên bản chính sách."); + // Phiên bản đã/đang có hiệu lực là căn cứ của báo cáo — không được xóa. + if (policy.EffectiveFromMonth <= KpiPeriod.CurrentMonth()) + return ApiResponse.Fail("Không thể xóa phiên bản đã có hiệu lực vì đang là căn cứ của báo cáo.", HttpStatusCode.Conflict); + policy.IsDeleted = true; + policy.DeletedAtUtc = DateTime.UtcNow; + policy.DeletedByAdminId = actor.Id; + context.AdminAuditLogs.Add(new AdminAuditLog + { + ActorUserId = actor.Id, EntityType = "MentorKpiPolicy", EntityId = policy.Version, Action = "Deleted", + BeforeJson = JsonSerializer.Serialize(KpiPeriod.Snapshot(policy, false, true)), CreatedAtUtc = DateTime.UtcNow, + }); + await context.SaveChangesAsync(ct); + return ApiResponse.Success(new { policy.Id, policy.Version }); + } + + private static string? Validate(PublishMentorKpiPolicyRequest r, out DateOnly month) + { + month = default; + if (!DateOnly.TryParseExact((r.EffectiveFromMonth ?? string.Empty) + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out month)) + return "Tháng hiệu lực không hợp lệ."; + if (month <= KpiPeriod.CurrentMonth()) + return "Phiên bản mới chỉ có hiệu lực từ tháng tiếp theo trở đi."; + static bool Pct(decimal v) => v > 0m && v <= 100m; + if (!Pct(r.MinimumPresencePercent)) return "Tỷ lệ hiện diện tối thiểu phải lớn hơn 0% và không quá 100%."; + if (!Pct(r.TeachingCompletionTargetPercent)) return "Tỷ lệ hoàn thành giảng dạy phải lớn hơn 0% và không quá 100%."; + if (r.HomeworkMinimumCount is < 0 or > 20) return "Số bài tập tối thiểu phải từ 0 đến 20."; + if (r.HomeworkPerSessionCount is < 1 or > 50) return "Số buổi giảng dạy tương ứng phải từ 1 đến 50."; + if (!Pct(r.GradingCompletionTargetPercent)) return "Tỷ lệ hoàn thành chấm bài phải lớn hơn 0% và không quá 100%."; + if (r.ResponseSlaHours is < 1 or > 720) return "Thời hạn phản hồi phải từ 1 đến 720 giờ."; + if (!Pct(r.OnTimeResponseTargetPercent)) return "Tỷ lệ phản hồi đúng hạn phải lớn hơn 0% và không quá 100%."; + if (r.AverageRatingTarget is < 1m or > 5m) return "Điểm đánh giá trung bình mục tiêu phải từ 1 đến 5."; + if (!Pct(r.PositiveReviewTargetPercent)) return "Tỷ lệ đánh giá tích cực phải lớn hơn 0% và không quá 100%."; + if (r.Note is { Length: > 500 }) return "Ghi chú tối đa 500 ký tự."; + return null; + } +} + +/// Kỳ báo cáo theo tháng dương lịch, giờ nghiệp vụ Việt Nam (Asia/Ho_Chi_Minh, UTC+7, không có giờ mùa hè). +public static class KpiPeriod +{ + public static readonly TimeSpan BusinessOffset = TimeSpan.FromHours(7); + + public static DateOnly CurrentMonth(DateTime? nowUtc = null) + { + var local = (nowUtc ?? DateTime.UtcNow).Add(BusinessOffset); + return new DateOnly(local.Year, local.Month, 1); + } + + public static DateOnly MonthOf(DateTime utc) + { + var local = utc.Add(BusinessOffset); + return new DateOnly(local.Year, local.Month, 1); + } + + public static DateOnly LocalDate(DateTime utc) => DateOnly.FromDateTime(utc.Add(BusinessOffset)); + + public static DateTime StartUtc(DateOnly month) + => DateTime.SpecifyKind(month.ToDateTime(TimeOnly.MinValue) - BusinessOffset, DateTimeKind.Utc); + + public static bool TryParseMonth(string? raw, out DateOnly month) + { + if (string.IsNullOrWhiteSpace(raw)) { month = CurrentMonth(); return true; } + return DateOnly.TryParseExact(raw.Trim() + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out month); + } + + public static async Task PolicyForMonthAsync(AppDbContext context, DateOnly month, CancellationToken ct) + => await context.MentorKpiPolicies.AsNoTracking().Include(p => p.CreatedByAdmin) + .Where(p => !p.IsDeleted && p.EffectiveFromMonth <= month) + .OrderByDescending(p => p.EffectiveFromMonth).FirstOrDefaultAsync(ct); + + public static MentorKpiPolicy? PolicyFor(IReadOnlyList policies, DateOnly month) + => policies.Where(p => p.EffectiveFromMonth <= month).OrderByDescending(p => p.EffectiveFromMonth).FirstOrDefault(); + + public static KpiPolicySnapshotResponse Snapshot(MentorKpiPolicy p, bool isCurrent, bool canDelete) => new( + p.Id, p.Version, p.EffectiveFromMonth, p.MinimumPresencePercent, p.TeachingCompletionTargetPercent, + p.HomeworkMinimumCount, p.HomeworkPerSessionCount, p.GradingCompletionTargetPercent, p.ResponseSlaHours, + p.OnTimeResponseTargetPercent, p.AverageRatingTarget, p.PositiveReviewTargetPercent, MentorKpiPolicy.PositiveRatingMinimum, + p.Note, p.CreatedAtUtc, + p.CreatedByAdmin is null ? null : $"{p.CreatedByAdmin.FirstName} {p.CreatedByAdmin.LastName}".Trim(), + isCurrent, canDelete); +} diff --git a/RikiPath.Infrastructure/Services/MentorOutboxDispatcherService.cs b/RikiPath.Infrastructure/Services/MentorOutboxDispatcherService.cs index a48ec43..7416d9e 100644 --- a/RikiPath.Infrastructure/Services/MentorOutboxDispatcherService.cs +++ b/RikiPath.Infrastructure/Services/MentorOutboxDispatcherService.cs @@ -344,7 +344,7 @@ await DispatchNotificationAsync( case "CohortLearningNotification": { - // Chuyển lớp / thay cố vấn chính: payload liệt kê sẵn người nhận; gửi sau commit, lỗi sẽ được thử lại. + // Outbox payloads can list recipients explicitly; dispatch after commit and retry failures. foreach (var item in root.GetProperty("Notifications").EnumerateArray()) { var linkUrl = item.TryGetProperty("LinkUrl", out var link) && link.ValueKind == JsonValueKind.String ? link.GetString() : null; diff --git a/RikiPath.Infrastructure/Services/StudyCohortLifecycleWorker.cs b/RikiPath.Infrastructure/Services/StudyCohortLifecycleWorker.cs index b768066..d592f48 100644 --- a/RikiPath.Infrastructure/Services/StudyCohortLifecycleWorker.cs +++ b/RikiPath.Infrastructure/Services/StudyCohortLifecycleWorker.cs @@ -102,7 +102,7 @@ private async Task ExpireStaleSeatHoldsAsync(IServiceProvider sp, AppDbContext d { CourseId = course.Id, Action = "PaidEnrollmentUnresolved", - Detail = "Phát hiện thanh toán từ PayOS sau khi giữ chỗ hết hạn; chuyển Quản trị viên xem xét hoàn tiền hoặc chuyển lớp.", + Detail = "Phát hiện thanh toán từ PayOS sau khi giữ chỗ hết hạn; chuyển Quản trị viên xem xét hoàn tiền hoặc hỗ trợ học viên.", At = nowUtc, }); diff --git a/RikiPath.Infrastructure/UnitOfWork.cs b/RikiPath.Infrastructure/UnitOfWork.cs index ff38ac4..9752a43 100644 --- a/RikiPath.Infrastructure/UnitOfWork.cs +++ b/RikiPath.Infrastructure/UnitOfWork.cs @@ -13,6 +13,8 @@ public class UnitOfWork : IUnitOfWork public IStudyCourseRepository StudyCourses { get; } public IGenericRepository StudyCoursePlans { get; } public IGenericRepository StudyCohorts { get; } + public IGenericRepository ClassQuizzes { get; } + public IGenericRepository ClassQuizAssignments { get; } public IGenericRepository CohortEnrollmentEntitlements { get; } public IGenericRepository CourseScheduleRequests { get; } public IGenericRepository CohortTransferRequests { get; } @@ -121,6 +123,8 @@ public UnitOfWork(AppDbContext context) StudyCourses = new StudyCourseRepository(_context); StudyCoursePlans = new GenericRepository(_context); StudyCohorts = new GenericRepository(_context); + ClassQuizzes = new GenericRepository(_context); + ClassQuizAssignments = new GenericRepository(_context); CohortEnrollmentEntitlements = new GenericRepository(_context); CourseScheduleRequests = new GenericRepository(_context); CohortTransferRequests = new GenericRepository(_context); diff --git a/RikiPath.WebApi/Controllers/ClassQuizzesController.cs b/RikiPath.WebApi/Controllers/ClassQuizzesController.cs new file mode 100644 index 0000000..357e441 --- /dev/null +++ b/RikiPath.WebApi/Controllers/ClassQuizzesController.cs @@ -0,0 +1,87 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using RikiPath.WebApi.Infrastructure; +using RikiPath.Application.IServices; +using RikiPath.Application.Responses.ClassQuizzes; + +namespace RikiPath.WebApi.Controllers; + +/// In-class skill quizzes — Mentor side (Admin read-only). +[ApiController] +[Authorize(Roles = "Mentor,Admin")] +[Route("api/mentor/class-quizzes")] +public sealed class MentorClassQuizzesController(IClassQuizService quizzes) : ControllerBase +{ + /// Danh sách bài kiểm tra của Giáo viên (lọc theo lớp nếu có). + [HttpGet] + public async Task List([FromQuery] int? cohortId, CancellationToken ct) + { + var r = await quizzes.GetMentorQuizzesAsync(cohortId, ct); + return StatusCode(r.StatusCode, r); + } + + /// Chi tiết bài kiểm tra: cấu trúc đề (kèm đáp án), học viên được giao và kết quả. + [HttpGet("{quizId:int}")] + public async Task Detail(int quizId, CancellationToken ct) + { + var r = await quizzes.GetMentorQuizDetailAsync(quizId, ct); + return StatusCode(r.StatusCode, r); + } + + /// Kho câu hỏi được phép dùng cho lớp (đúng cấp độ lớp, không gồm bộ đề đánh giá được bảo vệ). + [HttpGet("bank")] + public async Task Bank([FromQuery] int cohortId, CancellationToken ct) + { + var r = await quizzes.GetBankAsync(cohortId, ct); + return StatusCode(r.StatusCode, r); + } + + /// Tạo và giao bài kiểm tra cho lớp (đề được chốt phiên bản khi giao). + [HttpPost] + [Authorize(Roles = "Mentor")] + public async Task Create([FromQuery] int cohortId, [FromBody] CreateClassQuizRequest request, CancellationToken ct) + { + var r = await quizzes.CreateAsync(cohortId, request, ct); + return StatusCode(r.StatusCode, r); + } + + /// Kết quả và bài làm của một học viên. + [HttpGet("assignments/{assignmentId:int}/result")] + public async Task LearnerResult(int assignmentId, CancellationToken ct) + { + var r = await quizzes.GetMentorLearnerResultAsync(assignmentId, ct); + return StatusCode(r.StatusCode, r); + } +} + +/// In-class skill quizzes — Learner side. Answers/submit reuse /api/PlacementTest/attempts/{attemptId}. +[ApiController] +[Authorize(Roles = "Learner")] +[Route("api/class-quizzes")] +public sealed class LearnerClassQuizzesController(IClassQuizService quizzes, IPracticeTestService engine) : ControllerBase +{ + /// Bài kiểm tra được giao cho học viên (lọc theo lớp nếu có). + [HttpGet] + public async Task List([FromQuery] int? cohortId, CancellationToken ct) + { + var r = await quizzes.GetLearnerQuizzesAsync(cohortId, ct); + return StatusCode(r.StatusCode, r); + } + + /// Bắt đầu hoặc tiếp tục bài kiểm tra (không cho bắt đầu sau hạn, một lượt làm). + [ClassRecordWrite(ClassRecordSource.QuizAssignment, "assignmentId")] + [HttpPost("assignments/{assignmentId:int}/start")] + public async Task Start(int assignmentId, CancellationToken ct) + { + var r = await engine.StartClassQuizAsync(assignmentId, ct); + return StatusCode((int)r.StatusCode, r); + } + + /// Kết quả bài kiểm tra; đáp án chỉ công bố khi cả lớp đã làm xong hoặc đã hết hạn. + [HttpGet("assignments/{assignmentId:int}/result")] + public async Task Result(int assignmentId, CancellationToken ct) + { + var r = await quizzes.GetLearnerResultAsync(assignmentId, ct); + return StatusCode(r.StatusCode, r); + } +} diff --git a/RikiPath.WebApi/Controllers/ContentImportController.cs b/RikiPath.WebApi/Controllers/ContentImportController.cs index 3560532..81405a1 100644 --- a/RikiPath.WebApi/Controllers/ContentImportController.cs +++ b/RikiPath.WebApi/Controllers/ContentImportController.cs @@ -17,6 +17,7 @@ namespace RikiPath.Api.Controllers [Route("api/content-import")] [Authorize(Roles = "ContentAuthor,Admin")] public class ContentImportController(IExcelContentImportService importService, IFileStorageService fileStorage, + ICurriculumPackageImportService? curriculumImport = null, IContentAudioTranscriptionService? transcriptions = null, ILogger? logger = null, IAwsAudioFileStorageService? awsAudio = null) : ControllerBase @@ -31,15 +32,16 @@ public class ContentImportController(IExcelContentImportService importService, I [RequestFormLimits(MultipartBodyLengthLimit = ListeningAudioFilePolicy.MaxBytes + 4L * 1024 * 1024)] public async Task UploadListeningAudio(IFormFile? file, CancellationToken cancellationToken) { - if (file is null || file.Length < 4 || !string.Equals(Path.GetExtension(file.FileName), ".mp3", StringComparison.OrdinalIgnoreCase)) - return BadRequest(ApiResponse.Fail("Vui lòng chọn file nghe .mp3.")); + var extension = file is null ? null : Path.GetExtension(file.FileName); + if (file is null || file.Length < 12 || !ListeningAudioFilePolicy.IsSupportedExtension(extension)) + return BadRequest(ApiResponse.Fail("Vui lòng chọn file nghe .mp3 hoặc .wav.")); await using var stream = file.OpenReadStream(); - if (!await HasMp3HeaderAsync(stream, cancellationToken)) - return BadRequest(ApiResponse.Fail("File nghe không có định dạng MP3 hợp lệ.")); + if (!await ListeningAudioFilePolicy.HasSupportedAudioHeaderAsync(stream, file.FileName, cancellationToken)) + return BadRequest(ApiResponse.Fail("File nghe không có định dạng MP3 hoặc WAV hợp lệ.")); if (file.Length > ListeningAudioFilePolicy.MaxBytes) - return BadRequest(ApiResponse.Fail("File MP3 không được vượt quá 500 MB.")); + return BadRequest(ApiResponse.Fail("File âm thanh không được vượt quá 500 MB.")); await using var audio = file.OpenReadStream(); if (transcriptions is not null) @@ -72,7 +74,8 @@ public async Task UploadListeningAudio(IFormFile? file, Cancellat return StatusCode(failure.StatusCode, failure); } } - var uploaded = await fileStorage.UploadAsync(audio, file.FileName, "audio/mpeg", "jlpt-listening", cancellationToken); + var contentType = ListeningAudioFilePolicy.GetContentType(extension); + var uploaded = await fileStorage.UploadAsync(audio, file.FileName, contentType, "jlpt-listening", cancellationToken); uploaded = uploaded with { Url = NormalizeLocalMediaUrl(uploaded.Url) }; return Ok(ApiResponse.Success(uploaded)); } @@ -238,10 +241,10 @@ private async Task UploadLocalMediaAsync(string path, bool isAudio, Canc throw new InvalidDataException("Đường dẫn file phải nằm trong thư mục import được phép."); var extension = Path.GetExtension(fullPath).ToLowerInvariant(); var contentType = isAudio - ? (extension == ".mp3" ? "audio/mpeg" : null) + ? (ListeningAudioFilePolicy.IsSupportedExtension(extension) ? ListeningAudioFilePolicy.GetContentType(extension) : null) : extension switch { ".jpg" or ".jpeg" => "image/jpeg", ".png" => "image/png", ".webp" => "image/webp", ".gif" => "image/gif", _ => null }; if (contentType is null) - throw new InvalidDataException(isAudio ? "Đường dẫn audio phải trỏ tới file .mp3." : "Ảnh phải là JPG, PNG, WebP hoặc GIF."); + throw new InvalidDataException(isAudio ? "Đường dẫn audio phải trỏ tới file .mp3 hoặc .wav." : "Ảnh phải là JPG, PNG, WebP hoặc GIF."); for (string? entry = fullPath; entry is not null; entry = Path.GetDirectoryName(entry)) { @@ -251,9 +254,9 @@ private async Task UploadLocalMediaAsync(string path, bool isAudio, Canc await using var audio = System.IO.File.OpenRead(fullPath); if (audio.Length > (isAudio ? 25 * 1024 * 1024 : ImportImageFiles.MaxImageBytes)) - throw new InvalidDataException(isAudio ? "MP3 tối đa 25 MB." : "Ảnh tối đa 10 MB."); - if (isAudio && !await HasMp3HeaderAsync(audio, cancellationToken)) - throw new InvalidDataException("File nghe không có định dạng MP3 hợp lệ."); + throw new InvalidDataException(isAudio ? "File âm thanh tối đa 25 MB." : "Ảnh tối đa 10 MB."); + if (isAudio && !await ListeningAudioFilePolicy.HasSupportedAudioHeaderAsync(audio, fullPath, cancellationToken)) + throw new InvalidDataException("File nghe không có định dạng MP3 hoặc WAV hợp lệ."); audio.Position = 0; if (!isAudio) { @@ -290,18 +293,6 @@ private async Task UploadLocalMediaAsync(string path, bool isAudio, Canc } } - private static async Task HasMp3HeaderAsync(Stream audio, CancellationToken cancellationToken) - { - var header = new byte[4]; - if (await audio.ReadAtLeastAsync(header, header.Length, false, cancellationToken) < header.Length) - return false; - - var hasId3 = header[0] == 'I' && header[1] == 'D' && header[2] == '3' && header[3] is >= 2 and <= 4; - var hasMp3Frame = header[0] == 0xff && (header[1] & 0xe6) == 0xe2 && - (header[1] & 0x18) != 0x08 && (header[2] & 0xf0) != 0xf0 && (header[2] & 0x0c) != 0x0c; - return hasId3 || hasMp3Frame; - } - /// /// Lưu các dòng hợp lệ từ bản xem trước thành bản nháp của tác giả. /// @@ -331,6 +322,52 @@ public async Task Confirm( return Ok(result); } + [HttpGet("curriculum-package/inventory")] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] + public async Task GetCurriculumPackageInventory(CancellationToken cancellationToken) + { + if (curriculumImport is null) + return StatusCode(503, ApiResponse.Fail("Dịch vụ nhập gói giáo trình chưa được kích hoạt.")); + + var result = await curriculumImport.GetInventoryAsync(cancellationToken); + return result.IsSuccess ? Ok(result) : BadRequest(result); + } + + [HttpPost("curriculum-package/preview")] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status400BadRequest)] + public async Task PreviewCurriculumPackage( + [FromBody] CurriculumPackagePreviewRequest request, + CancellationToken cancellationToken) + { + if (curriculumImport is null) + return StatusCode(503, ApiResponse.Fail("Dịch vụ nhập gói giáo trình chưa được kích hoạt.")); + + var result = await curriculumImport.PreviewAsync(request ?? new CurriculumPackagePreviewRequest(), cancellationToken); + return result.IsSuccess ? Ok(result) : BadRequest(result); + } + + [HttpPost("curriculum-package/confirm")] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status400BadRequest)] + public async Task ConfirmCurriculumPackage( + [FromBody] CurriculumPackageConfirmRequest request, + CancellationToken cancellationToken) + { + if (curriculumImport is null) + return StatusCode(503, ApiResponse.Fail("Dịch vụ nhập gói giáo trình chưa được kích hoạt.")); + + var actorUserId = GetCurrentUserId(); + if (actorUserId is null) + return Unauthorized(ApiResponse.Fail("Không xác định được thông tin người dùng.")); + + var result = await curriculumImport.ConfirmAsync( + request ?? new CurriculumPackageConfirmRequest(), + actorUserId.Value, + cancellationToken); + return result.IsSuccess ? Ok(result) : BadRequest(result); + } + /// /// Trích xuất UserId của người dùng hiện tại từ Claims/Token JWT /// diff --git a/RikiPath.WebApi/Controllers/FileStorageController.cs b/RikiPath.WebApi/Controllers/FileStorageController.cs index 40555d3..06ff8aa 100644 --- a/RikiPath.WebApi/Controllers/FileStorageController.cs +++ b/RikiPath.WebApi/Controllers/FileStorageController.cs @@ -62,7 +62,7 @@ public async Task Upload(IFormFile file, [FromQuery] string folde if (transcriptions is not null && claims is not null && fileStorageService is not LocalDevMediaStorageService && (User.IsInRole("ContentAuthor") || User.IsInRole("Admin")) && - ext.Equals(".mp3", StringComparison.OrdinalIgnoreCase)) + RikiPath.Application.Services.ListeningAudioFilePolicy.IsSupportedExtension(ext)) { try { diff --git a/RikiPath.WebApi/Controllers/HomeworkController.cs b/RikiPath.WebApi/Controllers/HomeworkController.cs index 9e80bd7..3e174af 100644 --- a/RikiPath.WebApi/Controllers/HomeworkController.cs +++ b/RikiPath.WebApi/Controllers/HomeworkController.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using RikiPath.WebApi.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; using RikiPath.Application.IServices; using RikiPath.Application.Requests.Homework; @@ -26,12 +27,14 @@ public async Task List([FromQuery] int? learnerId, [FromQuery] in return Ok(ApiResponse.Success(await homework.GetAssignmentsAsync(learnerId, ct, cohortId))); } + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/scan"), Authorize(Roles = "Learner"), RequestSizeLimit(11000000)] [Consumes("multipart/form-data")] public async Task SubmitScan(int assignmentId, IFormFile? file, [FromForm] string? textContent, CancellationToken ct) => Send(await homework.SubmitScanAsync(assignmentId, file, ct, textContent)); // Alias Task 02: form "scan" + "textContent". + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/submit-scan"), Authorize(Roles = "Learner"), RequestSizeLimit(11000000)] [Consumes("multipart/form-data")] public async Task SubmitScanLegacy(int assignmentId, [FromForm] string? textContent, IFormFile? scan, @@ -39,6 +42,7 @@ public async Task SubmitScanLegacy(int assignmentId, [FromForm] s => Send(await homework.SubmitWithScanAsync(assignmentId, textContent, scan, ct)); // Multi-file submission (ảnh/PDF, tối đa 5 tệp × 10 MB). keepFileKeys = files from the previous version to keep. + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/submit-files"), Authorize(Roles = "Learner"), RequestSizeLimit(105_000_000)] [Consumes("multipart/form-data")] public async Task SubmitFiles(int assignmentId, [FromForm] List? files, @@ -55,12 +59,14 @@ public async Task SubmissionFile(int assignmentId, Guid fileKey, } // Mentor attachments (đề bài = Prompt, đáp án nội bộ = AnswerKey) applied to every recipient of the giao bài. + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/attachments"), Authorize(Roles = "Mentor"), RequestSizeLimit(105_000_000)] [Consumes("multipart/form-data")] public async Task AddAttachments(int assignmentId, [FromForm] List? files, [FromForm] string? kind, CancellationToken ct) => Send(await homework.AddAttachmentsAsync(assignmentId, files, kind, ct)); + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpDelete("{assignmentId:int}/attachments/{fileKey:guid}"), Authorize(Roles = "Mentor")] public async Task RemoveAttachment(int assignmentId, Guid fileKey, CancellationToken ct) => Send(await homework.RemoveAttachmentAsync(assignmentId, fileKey, ct)); @@ -92,6 +98,7 @@ public async Task Scan(int assignmentId, [FromQuery] bool downloa public async Task BatchDraft(HomeworkAiBatchDraftRequest request, CancellationToken ct) => Send(await homework.CreateDraftsAsync(request, ct)); + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/audio"), Authorize(Roles = "Learner"), RequestSizeLimit(5500000)] [Consumes("multipart/form-data")] public async Task SubmitAudio(int assignmentId, IFormFile? file, CancellationToken ct) @@ -106,11 +113,13 @@ public async Task Audio(int assignmentId, CancellationToken ct) return audio is null ? NotFound() : File(audio.Content, audio.ContentType); } + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPut("{assignmentId:int}/grade"), Authorize(Roles = "Mentor")] public async Task Grade(int assignmentId, PublishHomeworkGradeRequest request, CancellationToken ct) => Send(await homework.PublishGradeAsync(assignmentId, request, ct)); // Alias Task 02: GradeHomeworkAssignmentRequest (Passed/Score/Feedback/PublishAiDraft) → PublishGradeAsync. + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/grade"), Authorize(Roles = "Mentor")] public async Task GradeAndPublish(int assignmentId, GradeHomeworkAssignmentRequest request, CancellationToken ct) => Send(await homework.GradeAndPublishAsync(assignmentId, request, ct)); @@ -131,12 +140,14 @@ public async Task Catalog([FromQuery] string? level, [FromQuery] public async Task Create(CreateHomeworkRequest request, CancellationToken ct) => Send(await homework.CreateAsync(request, ct)); + [ClassRecordWrite(ClassRecordSource.Cohort, "cohortId")] [HttpPost("cohorts/{cohortId:int}")] [Authorize(Roles = "Mentor")] public async Task CreateForCohort(int cohortId, CreateHomeworkRequest request, CancellationToken ct) => Send(await homework.CreateCohortAssignmentsAsync(cohortId, request, ct)); // Giao bài: content + deadline + recipients + đề bài files + private đáp án (text and/or files) in one request. + [ClassRecordWrite(ClassRecordSource.Cohort, "cohortId")] [HttpPost("cohorts/{cohortId:int}/with-files"), Authorize(Roles = "Mentor"), RequestSizeLimit(210_000_000), RequestFormLimits(MultipartBodyLengthLimit = 210_000_000)] [Consumes("multipart/form-data")] public async Task CreateForCohortWithFiles(int cohortId, @@ -156,17 +167,20 @@ public async Task CreateForCohortWithFiles(int cohortId, public async Task Lesson(int assignmentId, int lessonId, CancellationToken ct) => Send(await homework.GetAssignedLessonAsync(assignmentId, lessonId, ct)); + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/exercises/{exerciseId:int}/start")] [Authorize(Roles = "Learner")] public async Task StartExercise(int assignmentId, int exerciseId, CancellationToken ct) => Send(await practice.StartHomeworkAttemptAsync(assignmentId, exerciseId, ct)); + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/exercise-attempts/{attemptId:int}/submit")] [Authorize(Roles = "Learner")] public async Task SubmitExercise(int assignmentId, int attemptId, SubmitPracticeExerciseAttemptRequest request, CancellationToken ct) => Send(await practice.SubmitHomeworkAttemptAsync(assignmentId, attemptId, request, ct)); + [ClassRecordWrite(ClassRecordSource.HomeworkAssignment, "assignmentId")] [HttpPost("{assignmentId:int}/submit")] [HttpPut("{assignmentId:int}/submit")] [Authorize(Roles = "Learner")] diff --git a/RikiPath.WebApi/Controllers/LearnerCourseCompetencyController.cs b/RikiPath.WebApi/Controllers/LearnerCourseCompetencyController.cs new file mode 100644 index 0000000..825de61 --- /dev/null +++ b/RikiPath.WebApi/Controllers/LearnerCourseCompetencyController.cs @@ -0,0 +1,42 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using RikiPath.Application.IServices; + +namespace RikiPath.WebApi.Controllers; + +/// +/// Learner view of the class competency profile and the end-of-course assessment (Stage 5). +/// enrollmentId is the learner's own class enrollment (the id in /my-courses/{id}). +/// Answers, submit and result of a started attempt reuse /api/PlacementTest/attempts/{attemptId}. +/// +[ApiController] +[Authorize(Roles = "Learner")] +[Route("api/my-courses/{enrollmentId:int}")] +public sealed class LearnerCourseCompetencyController( + IMentorLearnerSkillProfileService skillProfiles, + IPracticeTestService assessments) : ControllerBase +{ + /// Hồ sơ năng lực của chính học viên trong lớp: đầu vào, quá trình học và mức tiến bộ. + [HttpGet("competency")] + public async Task GetCompetency(int enrollmentId, CancellationToken cancellationToken) + { + var result = await skillProfiles.GetLearnerCourseCompetencyAsync(enrollmentId, cancellationToken); + return StatusCode(result.StatusCode, result); + } + + /// Trạng thái bài đánh giá cuối khóa của lớp (chưa mở, có thể làm, đang làm, đã hoàn thành). + [HttpGet("final-assessment")] + public async Task GetFinalAssessment(int enrollmentId, CancellationToken cancellationToken) + { + var result = await assessments.GetCourseFinalAssessmentAsync(enrollmentId, cancellationToken); + return StatusCode((int)result.StatusCode, result); + } + + /// Bắt đầu hoặc tiếp tục bài đánh giá cuối khóa; chỉ mở sau khi lớp học hoàn thành. + [HttpPost("final-assessment/start")] + public async Task StartFinalAssessment(int enrollmentId, CancellationToken cancellationToken) + { + var result = await assessments.StartCourseFinalAssessmentAsync(enrollmentId, cancellationToken); + return StatusCode((int)result.StatusCode, result); + } +} diff --git a/RikiPath.WebApi/Controllers/MentorKpiDashboardController.cs b/RikiPath.WebApi/Controllers/MentorKpiDashboardController.cs new file mode 100644 index 0000000..e3dd04d --- /dev/null +++ b/RikiPath.WebApi/Controllers/MentorKpiDashboardController.cs @@ -0,0 +1,72 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using RikiPath.Application.IServices; + +namespace RikiPath.WebApi.Controllers; + +/// +/// Chấm công & KPI Giáo viên theo tháng (Mentor cá nhân, Admin toàn trung tâm/từng Giáo viên) và Chính sách chấm công & KPI. +/// Mọi kiểm tra quyền được thực thi lại trong service (không dựa vào việc ẩn nút ở giao diện). +/// +[ApiController] +[Authorize] +public sealed class MentorKpiDashboardController( + IMentorKpiDashboardService dashboards, + IMentorKpiPolicyService policies) : ControllerBase +{ + [HttpGet("api/mentor/kpi/dashboard"), Authorize(Roles = "Mentor")] + public async Task MyDashboard([FromQuery] string? month, [FromQuery] string? level, [FromQuery] int? cohortId, CancellationToken ct) + { + var r = await dashboards.GetMyDashboardAsync(month, level, cohortId, ct); + return StatusCode(r.StatusCode, r); + } + + [HttpGet("api/admin/mentor-kpi/overview"), Authorize(Roles = "Admin")] + public async Task Overview([FromQuery] string? month, [FromQuery] string? level, CancellationToken ct) + { + var r = await dashboards.GetOverviewAsync(month, level, ct); + return StatusCode(r.StatusCode, r); + } + + [HttpGet("api/admin/mentor-kpi/mentors/{mentorId:int}/dashboard"), Authorize(Roles = "Admin")] + public async Task MentorDashboard(int mentorId, [FromQuery] string? month, [FromQuery] string? level, [FromQuery] int? cohortId, CancellationToken ct) + { + var r = await dashboards.GetMentorDashboardAsync(mentorId, month, level, cohortId, ct); + return StatusCode(r.StatusCode, r); + } + + [HttpPost("api/admin/mentor-kpi/mentors/{mentorId:int}/sessions/{sessionId:int}/reconcile"), Authorize(Roles = "Admin")] + public async Task Reconcile(int mentorId, int sessionId, [FromBody] ReconcileTimesheetRequest request, CancellationToken ct) + { + var r = await dashboards.ReconcileAsync(mentorId, sessionId, request, ct); + return StatusCode(r.StatusCode, r); + } + + [HttpGet("api/mentor-kpi-policies/current"), Authorize(Roles = "Admin,Mentor")] + public async Task CurrentPolicy(CancellationToken ct) + { + var r = await policies.GetCurrentAsync(ct); + return StatusCode(r.StatusCode, r); + } + + [HttpGet("api/admin/mentor-kpi-policies"), Authorize(Roles = "Admin")] + public async Task PolicyHistory(CancellationToken ct) + { + var r = await policies.GetHistoryAsync(ct); + return StatusCode(r.StatusCode, r); + } + + [HttpPost("api/admin/mentor-kpi-policies"), Authorize(Roles = "Admin")] + public async Task PublishPolicy([FromBody] PublishMentorKpiPolicyRequest request, CancellationToken ct) + { + var r = await policies.PublishAsync(request, ct); + return StatusCode(r.StatusCode, r); + } + + [HttpDelete("api/admin/mentor-kpi-policies/{id:int}"), Authorize(Roles = "Admin")] + public async Task DeletePolicy(int id, CancellationToken ct) + { + var r = await policies.DeleteAsync(id, ct); + return StatusCode(r.StatusCode, r); + } +} diff --git a/RikiPath.WebApi/Controllers/StudyCoursesController.cs b/RikiPath.WebApi/Controllers/StudyCoursesController.cs index d278982..35de18b 100644 --- a/RikiPath.WebApi/Controllers/StudyCoursesController.cs +++ b/RikiPath.WebApi/Controllers/StudyCoursesController.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using RikiPath.WebApi.Infrastructure; using Microsoft.AspNetCore.SignalR; using RikiPath.Application.IServices; using RikiPath.Application.Requests.StudyCourses; @@ -22,6 +23,7 @@ public sealed class StudyCoursesController( public async Task CloseEnrollment(int cohortId, CancellationToken ct) => Result(await classLifecycle.CloseEnrollmentAsync(cohortId, ct)); + [ClassRecordWrite(ClassRecordSource.Cohort, "cohortId")] [HttpPost("cohorts/{cohortId:int}/sessions/{sessionId:int}/end"), Authorize(Roles = "Mentor")] public async Task EndSession(int cohortId, int sessionId, CancellationToken ct) { @@ -50,6 +52,7 @@ public async Task EndSession(int cohortId, int sessionId, Cancell /// Lưu điểm danh (một phần hoặc toàn bộ) cho buổi học của lớp. Buổi đang diễn ra: lưu/cập nhật nhiều lần; /// buổi đã hoàn thành: chỉ bổ sung học viên chưa có kết quả và khóa ngay. + [ClassRecordWrite(ClassRecordSource.Cohort, "cohortId")] [HttpPost("cohorts/{cohortId:int}/sessions/{sessionId:int}/attendance"), Authorize(Roles = "Mentor")] public async Task SaveSessionAttendance(int cohortId, int sessionId, SaveClassAttendance r, CancellationToken ct) => Result(await classLifecycle.SaveAttendanceAsync(cohortId, sessionId, r, ct)); @@ -106,6 +109,7 @@ private static bool TryParseLocalTime(string? value, out TimeOnly? time) [HttpPost("cohorts/schedule-preview"), Authorize(Roles = "Admin")] public async Task CohortSchedulePreview(CohortSchedulePreviewRequest r, CancellationToken ct) => Result(await service.CohortSchedulePreviewAsync(r, ct)); + [ClassRecordWrite(ClassRecordSource.Cohort, "id")] [HttpPut("cohorts/{id:int}"), Authorize(Roles = "Admin")] public async Task UpdateCohort(int id, SaveStudyCohort r, CancellationToken ct) => Result(await service.SaveCohortAsync(id, r, ct)); [HttpGet("catalog")] @@ -151,6 +155,7 @@ public async Task ReconcilePayment(int id, CancellationToken ct) [HttpPost("{id:int}/cancel-enrollment"), Authorize(Roles = "Learner,Admin")] public async Task CancelCohortEnrollment(int id, CancelCohortEnrollmentRequest? r, CancellationToken ct) => Result(await service.CancelCohortEnrollmentAsync(id, r, ct)); + [ClassRecordWrite(ClassRecordSource.Enrollment, "id")] [HttpPost("{id:int}/sessions/{sessionId:int}/attendance"), Authorize(Roles = "Admin,Mentor")] public async Task Attendance(int id, int sessionId, ConfirmCourseAttendance r, CancellationToken ct) => Result(await service.AttendanceAsync(id, sessionId, r, ct)); [HttpPost("{id:int}/complete"), Authorize(Roles = "Admin")] @@ -167,31 +172,6 @@ public async Task Review(int id, int requestId, ReviewCourseRetak [HttpPost("{id:int}/retake/{requestId:int}/support-plan"), Authorize(Roles = "Mentor")] public async Task SaveRetakeSupportPlan(int id, int requestId, SaveRetakeSupportPlan r, CancellationToken ct) => Result(await service.SaveRetakeSupportPlanAsync(id, requestId, r, ct)); - /// Học viên gửi yêu cầu chuyển lớp cho ghi danh lớp nhóm của mình (Admin duyệt; không tự đổi lớp). - [HttpPost("{id:int}/transfer-requests"), Authorize(Roles = "Learner"), RequestSizeLimit(11000000)] - [Consumes("multipart/form-data")] - public async Task RequestTransfer(int id, [FromForm] Guid idempotencyKey, [FromForm] string? reason, - [FromForm] int? targetCohortId, IFormFile? evidence, CancellationToken ct) - => Result(await service.RequestTransferAsync(id, targetCohortId, reason, idempotencyKey, evidence, ct)); - /// Danh sách yêu cầu chuyển lớp (Admin: toàn bộ; Học viên: của mình). - [HttpGet("transfer-requests"), Authorize(Roles = "Admin,Learner")] - public async Task TransferRequests([FromQuery] string? status, CancellationToken ct) => Result(await service.TransferRequestsAsync(status, ct)); - /// Chi tiết yêu cầu chuyển lớp kèm lịch sử, tiến độ học và lớp đích phù hợp (Admin). - [HttpGet("transfer-requests/{requestId:int}"), Authorize(Roles = "Admin,Learner")] - public async Task TransferRequestDetail(int requestId, CancellationToken ct) => Result(await service.TransferRequestDetailAsync(requestId, ct)); - /// Xem trước điều kiện chuyển sang một lớp đích (sức chứa, lịch, cấp độ, chính sách). - [HttpGet("transfer-requests/{requestId:int}/eligibility"), Authorize(Roles = "Admin")] - public async Task TransferEligibility(int requestId, [FromQuery] int targetCohortId, CancellationToken ct) - => Result(await service.TransferEligibilityAsync(requestId, targetCohortId, ct)); - /// Admin duyệt chuyển lớp; kiểm tra lại điều kiện và cập nhật ghi danh trong một giao dịch. - [HttpPost("transfer-requests/{requestId:int}/approve"), Authorize(Roles = "Admin")] - public async Task ApproveTransfer(int requestId, ApproveCohortTransfer r, CancellationToken ct) => Result(await service.ApproveTransferAsync(requestId, r, ct)); - /// Admin từ chối yêu cầu chuyển lớp (bắt buộc nhập lý do). - [HttpPost("transfer-requests/{requestId:int}/reject"), Authorize(Roles = "Admin")] - public async Task RejectTransfer(int requestId, RejectCohortTransfer r, CancellationToken ct) => Result(await service.RejectTransferAsync(requestId, r, ct)); - /// Học viên rút yêu cầu chuyển lớp đang chờ. - [HttpPost("transfer-requests/{requestId:int}/withdraw"), Authorize(Roles = "Learner")] - public async Task WithdrawTransfer(int requestId, CancellationToken ct) => Result(await service.WithdrawTransferAsync(requestId, ct)); /// Tải hoặc xem tài liệu giới thiệu / đề cương gắn với lớp nhóm (đã kiểm tra quyền theo vai trò). [HttpGet("cohorts/{cohortId:int}/attachments/{index:int}"), Authorize(Roles = "Admin,Learner,Mentor")] public async Task CohortAttachment( @@ -227,22 +207,6 @@ public async Task CohortAttachmentPreview( this, fileStorageService, httpClientFactory, meta.Result, ct); } - /// Tải minh chứng riêng tư của yêu cầu chuyển lớp. - [HttpGet("transfer-requests/{requestId:int}/evidence"), Authorize(Roles = "Admin,Learner")] - public async Task TransferEvidence(int requestId, [FromQuery] bool download = false, CancellationToken ct = default) - { - var file = await service.TransferEvidenceAsync(requestId, ct); - return ProposalAttachmentStreamHelper.StreamPrivateVerificationResult( - this, file, $"minh-chung-chuyen-lop-{requestId}", download); - } - /// Xem trước tác động khi thay cố vấn chính cho các buổi còn lại của lớp. - [HttpGet("cohorts/{cohortId:int}/mentor-replacement/preview"), Authorize(Roles = "Admin")] - public async Task PreviewMentorReplacement(int cohortId, [FromQuery] int mentorId, [FromQuery] int? fromSessionNumber, CancellationToken ct) - => Result(await service.PreviewMentorReplacementAsync(cohortId, mentorId, fromSessionNumber, ct)); - /// Admin xác nhận thay cố vấn chính; buổi đã diễn ra giữ cố vấn thực dạy. - [HttpPost("cohorts/{cohortId:int}/mentor-replacement"), Authorize(Roles = "Admin")] - public async Task ReplaceCohortMentor(int cohortId, ReplaceCohortMentorRequest r, CancellationToken ct) - => Result(await service.ReplaceCohortMentorAsync(cohortId, r, ct)); /// Lịch sử phân công cố vấn chính của lớp. [HttpGet("cohorts/{cohortId:int}/mentor-assignments"), Authorize(Roles = "Admin,Mentor")] public async Task MentorAssignments(int cohortId, CancellationToken ct) => Result(await service.MentorAssignmentsAsync(cohortId, ct)); @@ -250,6 +214,7 @@ public async Task ReplaceCohortMentor(int cohortId, ReplaceCohort /// Mentor chính của lớp (hoặc Admin) gửi yêu cầu dời toàn bộ lịch lớp chưa có học viên thêm N tuần (giữ nguyên thứ/giờ và số buổi) /// hoặc hủy lớp trống. Gửi lại cùng mã chống trùng trả về đúng yêu cầu cũ; mỗi lớp chỉ có một yêu cầu đang chờ. /// + [ClassRecordWrite(ClassRecordSource.Cohort, "cohortId")] [HttpPost("cohorts/{cohortId:int}/schedule-requests"), Authorize(Roles = "Admin,Mentor")] public async Task CreateCohortScheduleRequest(int cohortId, CreateCohortScheduleRequest r, CancellationToken ct) => Result(await service.CreateCohortScheduleRequestAsync(cohortId, r, ct)); @@ -300,6 +265,10 @@ public async Task CreateCohortMentorReview(int courseId, CreateCo public async Task UpdateCohortMentorReview(int courseId, int reviewId, UpdateCohortMentorReviewRequest r, CancellationToken ct) => Result(await service.UpdateCohortMentorReviewAsync(courseId, reviewId, r, ct)); /// Danh sách đánh giá cố vấn của một khóa học (Học viên sở hữu, Admin hoặc Cố vấn tham gia giảng dạy). + /// Lớp đã hoàn thành mà Học viên còn có thể đánh giá Giáo viên (CTA tùy chọn ở "Lớp của tôi"). + [HttpGet("mentor-review-prompts"), Authorize(Roles = "Learner")] + public async Task MentorReviewPrompts(CancellationToken ct) + => Result(await service.MentorReviewPromptsAsync(ct)); [HttpGet("{courseId:int}/mentor-reviews"), Authorize(Roles = "Admin,Learner,Mentor")] public async Task CohortMentorReviews(int courseId, CancellationToken ct) => Result(await service.CohortMentorReviewsAsync(courseId, ct)); diff --git a/RikiPath.WebApi/Infrastructure/ClassRecordWriteAttribute.cs b/RikiPath.WebApi/Infrastructure/ClassRecordWriteAttribute.cs new file mode 100644 index 0000000..2b61746 --- /dev/null +++ b/RikiPath.WebApi/Infrastructure/ClassRecordWriteAttribute.cs @@ -0,0 +1,50 @@ +using System.Net; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using RikiPath.Application; +using RikiPath.Application.Responses; +using RikiPath.Application.Services; + +namespace RikiPath.WebApi.Infrastructure; + +/// Which route value identifies the class whose learning records an action writes. +public enum ClassRecordSource +{ + Cohort, + HomeworkAssignment, + Enrollment, + QuizAssignment, +} + +/// +/// Refuses learning-record writes (homework, quiz, attendance, schedule) for a completed class, for every role, +/// whatever client sent the request. Critical write paths also re-check under the class lock in their transaction. +/// +[AttributeUsage(AttributeTargets.Method)] +public sealed class ClassRecordWriteAttribute(ClassRecordSource source, string routeKey) : Attribute, IAsyncActionFilter +{ + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + if (context.RouteData.Values.TryGetValue(routeKey, out var raw) && int.TryParse(raw?.ToString(), out var id)) + { + var uow = context.HttpContext.RequestServices.GetRequiredService(); + var ct = context.HttpContext.RequestAborted; + var cohortId = source switch + { + ClassRecordSource.Cohort => id, + ClassRecordSource.HomeworkAssignment => await ClassRecordLock.CohortOfHomeworkAsync(uow, id, ct), + ClassRecordSource.Enrollment => await ClassRecordLock.CohortOfEnrollmentAsync(uow, id, ct), + ClassRecordSource.QuizAssignment => await ClassRecordLock.CohortOfQuizAssignmentAsync(uow, id, ct), + _ => null, + }; + if (await ClassRecordLock.IsCompletedAsync(uow, cohortId, ct)) + { + context.Result = new ObjectResult(ApiResponse.Fail( + ClassRecordLock.Message, HttpStatusCode.Conflict, errorCode: ClassRecordLock.ErrorCode, retryable: false)) + { StatusCode = StatusCodes.Status409Conflict }; + return; + } + } + await next(); + } +} diff --git a/RikiPath.WebApi/Services/ImportAudioFiles.cs b/RikiPath.WebApi/Services/ImportAudioFiles.cs index 13d9692..ff5eb3d 100644 --- a/RikiPath.WebApi/Services/ImportAudioFiles.cs +++ b/RikiPath.WebApi/Services/ImportAudioFiles.cs @@ -16,11 +16,11 @@ public ImportAudioFiles(IEnumerable? files, IAwsAudioFileStorageServi IContentAudioTranscriptionService? transcripts, int authorId, Func> readServerFile) { - selected = (files ?? []).Where(file => file.FileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)).ToList(); + selected = (files ?? []).Where(file => ListeningAudioFilePolicy.IsSupportedExtension(Path.GetExtension(file.FileName))).ToList(); if (selected.Count > 1) - throw new InvalidDataException("Mỗi lần chỉ được tải lên một file MP3."); - if (selected.Any(file => file.Length < 4 || file.Length > ListeningAudioFilePolicy.MaxBytes)) - throw new InvalidDataException("File MP3 phải có dữ liệu và không vượt quá 500 MB."); + throw new InvalidDataException("Mỗi lần chỉ được tải lên một file âm thanh (MP3/WAV)."); + if (selected.Any(file => file.Length < 12 || file.Length > ListeningAudioFilePolicy.MaxBytes)) + throw new InvalidDataException("File âm thanh phải có dữ liệu và không vượt quá 500 MB."); this.aws = aws; this.transcripts = transcripts; this.authorId = authorId; @@ -39,7 +39,7 @@ public async Task ResolveAsync(string source, CancellationToken ct) } var previous = transcripts is null ? null : await transcripts.QueueAsync(source, authorId, ct); if (previous is not null) return previous.AudioUrl; - throw new InvalidDataException("AudioUrl phải là MP3 trong bucket S3 đã cấu hình hoặc audio đã lưu trên hệ thống."); + throw new InvalidDataException("AudioUrl phải là file MP3/WAV trong bucket S3 đã cấu hình hoặc audio đã lưu trên hệ thống."); } var path = Normalize(source); var matches = selected.Where(file => path.Equals(Normalize(file.FileName), StringComparison.OrdinalIgnoreCase) || @@ -52,7 +52,7 @@ public async Task ResolveAsync(string source, CancellationToken ct) .Equals(name, StringComparison.OrdinalIgnoreCase)).ToList(); } if (matches.Count > 1) - throw new InvalidDataException("Có nhiều MP3 trùng tên. Điền đường dẫn thư mục tương đối đầy đủ trong Excel."); + throw new InvalidDataException("Có nhiều file âm thanh trùng tên. Điền đường dẫn thư mục tương đối đầy đủ trong Excel."); if (matches.Count == 1) { if (uploaded.TryGetValue(matches[0], out var existing)) return existing; diff --git a/seed-data/dev-stage5-class-quiz-demo-cleanup.sql b/seed-data/dev-stage5-class-quiz-demo-cleanup.sql new file mode 100644 index 0000000..259648d --- /dev/null +++ b/seed-data/dev-stage5-class-quiz-demo-cleanup.sql @@ -0,0 +1,17 @@ +-- RikiPath Stage 5 — remove ONLY the demo in-class quizzes of the Stage 5 demo class (DEVELOPMENT / LOCAL ONLY). +DO $cleanup$ +DECLARE v_cohort int; v_attempts int[]; +BEGIN + IF current_database() <> 'rikipath_local' THEN RAISE EXCEPTION 'Cleanup runs only on rikipath_local (found %)', current_database(); END IF; + SELECT "Id" INTO v_cohort FROM "StudyCohorts" WHERE "Name" = '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành'; + IF v_cohort IS NULL THEN RETURN; END IF; + SELECT array_agg(a."AttemptId") INTO v_attempts FROM "ClassQuizAssignments" a JOIN "ClassQuizzes" q ON q."Id" = a."QuizId" + WHERE q."CohortId" = v_cohort AND q."Title" LIKE 'Kiểm tra kiến thức lần %' AND a."AttemptId" IS NOT NULL; + DELETE FROM "ClassQuizAssignments" WHERE "QuizId" IN (SELECT "Id" FROM "ClassQuizzes" WHERE "CohortId" = v_cohort AND "Title" LIKE 'Kiểm tra kiến thức lần %'); + DELETE FROM "ClassQuizzes" WHERE "CohortId" = v_cohort AND "Title" LIKE 'Kiểm tra kiến thức lần %'; + DELETE FROM "MockTestSectionResults" WHERE "MockTestAttemptId" = ANY(coalesce(v_attempts, ARRAY[]::int[])); + DELETE FROM "MockTestAnswers" WHERE "PracticeTestAttemptId" = ANY(coalesce(v_attempts, ARRAY[]::int[])); + DELETE FROM "MockTestAttempts" WHERE "Id" = ANY(coalesce(v_attempts, ARRAY[]::int[])) AND "UserId" = 900009 AND "AttemptKind" = 2; + RAISE NOTICE 'Demo quizzes removed for cohort %', v_cohort; +END +$cleanup$; diff --git a/seed-data/dev-stage5-class-quiz-demo.sql b/seed-data/dev-stage5-class-quiz-demo.sql new file mode 100644 index 0000000..dd448e1 --- /dev/null +++ b/seed-data/dev-stage5-class-quiz-demo.sql @@ -0,0 +1,123 @@ +-- RikiPath Stage 5 — in-class quiz demo seed (DEVELOPMENT / LOCAL ONLY). Generated, do not edit by hand. +-- Requires dev-stage5-competency-demo.sql (demo class + enrollment of Hoang Pham, UserId 900009). +-- Adds 4 completed N5 quizzes of one comparison series (30 questions: 10 Từ vựng, 10 Ngữ pháp, 10 Đọc hiểu; approved bank + Mentor-authored only), +-- assignments, attempts, chosen answers and engine results. Idempotent; removed by dev-stage5-competency-demo-cleanup.sql. +DO $seed$ +DECLARE v_cohort int; v_course int; v_quiz int; v_assign int; v_attempt int; +BEGIN + IF current_database() <> 'rikipath_local' THEN RAISE EXCEPTION 'Quiz demo seed runs only on rikipath_local (found %)', current_database(); END IF; + SELECT "Id" INTO v_cohort FROM "StudyCohorts" WHERE "Name" = '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành'; + SELECT "Id" INTO v_course FROM "StudyCourses" WHERE "LearnerId" = 900009 AND "PurchaseKey" = '5e5d0005-de30-4000-8000-000000900009'::uuid; + IF v_cohort IS NULL OR v_course IS NULL THEN RAISE EXCEPTION 'Run dev-stage5-competency-demo.sql first'; END IF; + IF EXISTS (SELECT 1 FROM "ClassQuizzes" WHERE "CohortId" = v_cohort AND "Title" LIKE 'Kiểm tra kiến thức lần %') THEN RAISE NOTICE 'Quiz demo already seeded for cohort %', v_cohort; RETURN; END IF; + -- Kiểm tra kiến thức lần 1: 9/30 = 30.0% + INSERT INTO "ClassQuizzes" ("CohortId","MentorId","CertificateLevelId","Title","TimeLimitMinutes","DueAtUtc","SkillCodes","QuestionCount","QuestionSnapshotJson","StructureKey","Status","PublishedAtUtc","CreatedAtUtc","IsDeleted","Revision") + VALUES (v_cohort, 900002, 1, 'Kiểm tra kiến thức lần 1', 30, '2026-10-08 16:59:00+00'::timestamptz, 'vocabulary,grammar,reading', 30, + replace($json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"0001-01-01T00:00:00Z","expiresAt":"0001-01-01T00:00:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":null,"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":null,"quizId":null,"quizAssignmentId":null}$json$, '"__COHORT_ID__"', v_cohort::text), + 's:stage5demoseries01|grammar:10,reading:10,vocabulary:10', 'Published', '2026-10-06 02:45:00+00'::timestamptz, '2026-10-06 02:45:00+00'::timestamptz, false, 1) RETURNING "Id" INTO v_quiz; + INSERT INTO "MockTestAttempts" ("UserId","AttemptKind","StartedAt","ExpiresAt","SubmittedAt","IsCompleted","TotalScore","IsPlacementAssessment","QuestionSnapshotJson","CreatedDate","IsDeleted","CreatedBy") + VALUES (900009, 2, '2026-10-07 12:00:00'::timestamp, '2026-10-07 12:30:00'::timestamp, '2026-10-07 12:22:00'::timestamp, true, 30.0, false, $json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"2026-10-07T12:00:00Z","expiresAt":"2026-10-07T12:30:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":1,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":5,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":9,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":13,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":18,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":1800000012,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":1800000022,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":1800000032,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":1800000042,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":1800000052,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":21,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":25,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":29,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":34,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":38,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":1800000062,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":1800000072,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":1800000082,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":1800000092,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":1800000102,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":41,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":45,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":50,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":54,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":58,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":1800000112,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":1800000122,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":1800000132,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":1800000142,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":1800000152,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":{"attemptId":0,"attemptType":"courseFinal","status":"completed","startedAt":"2026-10-07T12:00:00Z","durationSeconds":1320,"submittedAt":"2026-10-07T12:22:00Z","assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"totalScore":30.0,"correctCount":9,"notStudiedCount":0,"totalQuestions":30,"assessedJlptLevelId":1,"assessedJlptLevelName":"N5","recommendedTargetJlptLevelId":1,"recommendedTargetJlptLevelName":"N5","wrongQuestionIds":[5,9,10,13,14,15,1900000001,1900000002,1900000003,1900000004,1900000005,1900000006,1900000007,1900000008,1900000009,1900000010,1900000011,1900000012,1900000013,1900000014,1900000015],"levelBreakdowns":[{"jlptLevelId":1,"jlptLevelName":"N5","correctCount":9,"totalCount":30,"scorePercent":30.0}],"sections":[{"mockTestSectionId":0,"sectionTitle":"Từ vựng","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":4,"totalCount":5,"score":80.0,"scorePercent":80.0},{"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":2,"sectionTitle":"N5 Grammar","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":3,"totalCount":5,"score":60.0,"scorePercent":60.0},{"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":3,"sectionTitle":"N5 Reading","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":2,"totalCount":5,"score":40.0,"scorePercent":40.0}]},"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":"__ENROLLMENT_ID__","quizId":"__QUIZ_ID__","quizAssignmentId":"__ASSIGNMENT_ID__"}$json$, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_attempt; + INSERT INTO "ClassQuizAssignments" ("QuizId","LearnerId","EnrollmentId","AttemptId","AssignedAtUtc","CompletedAtUtc") VALUES (v_quiz, 900009, v_course, v_attempt, '2026-10-06 02:45:00+00'::timestamptz, '2026-10-07 12:22:00+00'::timestamptz) RETURNING "Id" INTO v_assign; + UPDATE "MockTestAttempts" SET "QuestionSnapshotJson" = replace(replace(replace(replace("QuestionSnapshotJson", '"__COHORT_ID__"', v_cohort::text), '"__ENROLLMENT_ID__"', v_course::text), '"__QUIZ_ID__"', v_quiz::text), '"__ASSIGNMENT_ID__"', v_assign::text) WHERE "Id" = v_attempt; + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 1, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 5, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 9, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 4, 13, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 5, 18, false, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 6, 21, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 7, 25, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 8, 29, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 9, 34, false, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 10, 38, false, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 11, 41, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 12, 45, true, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 13, 50, false, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 14, 54, false, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 15, 58, false, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 4, 5, 80.0, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 3, 5, 60.0, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 2, 5, 40.0, '2026-10-07 12:22:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + -- Kiểm tra kiến thức lần 2: 13/30 = 43.33% + INSERT INTO "ClassQuizzes" ("CohortId","MentorId","CertificateLevelId","Title","TimeLimitMinutes","DueAtUtc","SkillCodes","QuestionCount","QuestionSnapshotJson","StructureKey","Status","PublishedAtUtc","CreatedAtUtc","IsDeleted","Revision") + VALUES (v_cohort, 900002, 1, 'Kiểm tra kiến thức lần 2', 30, '2026-10-12 16:59:00+00'::timestamptz, 'vocabulary,grammar,reading', 30, + replace($json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"0001-01-01T00:00:00Z","expiresAt":"0001-01-01T00:00:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":null,"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":null,"quizId":null,"quizAssignmentId":null}$json$, '"__COHORT_ID__"', v_cohort::text), + 's:stage5demoseries01|grammar:10,reading:10,vocabulary:10', 'Published', '2026-10-08 02:45:00+00'::timestamptz, '2026-10-08 02:45:00+00'::timestamptz, false, 1) RETURNING "Id" INTO v_quiz; + INSERT INTO "MockTestAttempts" ("UserId","AttemptKind","StartedAt","ExpiresAt","SubmittedAt","IsCompleted","TotalScore","IsPlacementAssessment","QuestionSnapshotJson","CreatedDate","IsDeleted","CreatedBy") + VALUES (900009, 2, '2026-10-09 12:00:00'::timestamp, '2026-10-09 12:30:00'::timestamp, '2026-10-09 12:23:00'::timestamp, true, 43.33, false, $json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"2026-10-09T12:00:00Z","expiresAt":"2026-10-09T12:30:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":1,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":5,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":9,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":13,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":17,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":1800000011,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":1800000022,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":1800000032,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":1800000042,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":1800000052,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":21,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":25,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":29,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":33,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":38,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":1800000062,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":1800000072,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":1800000082,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":1800000092,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":1800000102,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":41,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":45,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":49,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":54,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":58,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":1800000112,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":1800000122,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":1800000132,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":1800000142,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":1800000152,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":{"attemptId":0,"attemptType":"courseFinal","status":"completed","startedAt":"2026-10-09T12:00:00Z","durationSeconds":1380,"submittedAt":"2026-10-09T12:23:00Z","assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"totalScore":43.33,"correctCount":13,"notStudiedCount":0,"totalQuestions":30,"assessedJlptLevelId":1,"assessedJlptLevelName":"N5","recommendedTargetJlptLevelId":1,"recommendedTargetJlptLevelName":"N5","wrongQuestionIds":[10,14,15,1900000002,1900000003,1900000004,1900000005,1900000006,1900000007,1900000008,1900000009,1900000010,1900000011,1900000012,1900000013,1900000014,1900000015],"levelBreakdowns":[{"jlptLevelId":1,"jlptLevelName":"N5","correctCount":13,"totalCount":30,"scorePercent":43.33}],"sections":[{"mockTestSectionId":0,"sectionTitle":"Từ vựng","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":1,"totalCount":5,"score":20.0,"scorePercent":20.0},{"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":5,"totalCount":5,"score":100.0,"scorePercent":100.0},{"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":2,"sectionTitle":"N5 Grammar","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":4,"totalCount":5,"score":80.0,"scorePercent":80.0},{"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":3,"sectionTitle":"N5 Reading","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":3,"totalCount":5,"score":60.0,"scorePercent":60.0}]},"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":"__ENROLLMENT_ID__","quizId":"__QUIZ_ID__","quizAssignmentId":"__ASSIGNMENT_ID__"}$json$, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_attempt; + INSERT INTO "ClassQuizAssignments" ("QuizId","LearnerId","EnrollmentId","AttemptId","AssignedAtUtc","CompletedAtUtc") VALUES (v_quiz, 900009, v_course, v_attempt, '2026-10-08 02:45:00+00'::timestamptz, '2026-10-09 12:23:00+00'::timestamptz) RETURNING "Id" INTO v_assign; + UPDATE "MockTestAttempts" SET "QuestionSnapshotJson" = replace(replace(replace(replace("QuestionSnapshotJson", '"__COHORT_ID__"', v_cohort::text), '"__ENROLLMENT_ID__"', v_course::text), '"__QUIZ_ID__"', v_quiz::text), '"__ASSIGNMENT_ID__"', v_assign::text) WHERE "Id" = v_attempt; + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 1, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 5, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 9, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 4, 13, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 5, 17, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 6, 21, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 7, 25, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 8, 29, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 9, 33, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 10, 38, false, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 11, 41, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 12, 45, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 13, 49, true, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 14, 54, false, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 15, 58, false, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 5, 5, 100.0, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 4, 5, 80.0, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 3, 5, 60.0, '2026-10-09 12:23:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + -- Kiểm tra kiến thức lần 3: 17/30 = 56.67% + INSERT INTO "ClassQuizzes" ("CohortId","MentorId","CertificateLevelId","Title","TimeLimitMinutes","DueAtUtc","SkillCodes","QuestionCount","QuestionSnapshotJson","StructureKey","Status","PublishedAtUtc","CreatedAtUtc","IsDeleted","Revision") + VALUES (v_cohort, 900002, 1, 'Kiểm tra kiến thức lần 3', 30, '2026-10-15 00:59:00+00'::timestamptz, 'vocabulary,grammar,reading', 30, + replace($json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"0001-01-01T00:00:00Z","expiresAt":"0001-01-01T00:00:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":null,"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":null,"quizId":null,"quizAssignmentId":null}$json$, '"__COHORT_ID__"', v_cohort::text), + 's:stage5demoseries01|grammar:10,reading:10,vocabulary:10', 'Published', '2026-10-13 02:45:00+00'::timestamptz, '2026-10-13 02:45:00+00'::timestamptz, false, 1) RETURNING "Id" INTO v_quiz; + INSERT INTO "MockTestAttempts" ("UserId","AttemptKind","StartedAt","ExpiresAt","SubmittedAt","IsCompleted","TotalScore","IsPlacementAssessment","QuestionSnapshotJson","CreatedDate","IsDeleted","CreatedBy") + VALUES (900009, 2, '2026-10-14 12:00:00'::timestamp, '2026-10-14 12:30:00'::timestamp, '2026-10-14 12:24:00'::timestamp, true, 56.67, false, $json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"2026-10-14T12:00:00Z","expiresAt":"2026-10-14T12:30:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":1,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":5,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":9,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":13,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":17,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":1800000011,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":1800000021,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":1800000032,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":1800000042,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":1800000052,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":21,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":25,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":29,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":33,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":37,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":1800000061,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":1800000072,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":1800000082,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":1800000092,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":1800000102,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":41,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":45,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":49,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":53,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":58,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":1800000112,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":1800000122,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":1800000132,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":1800000142,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":1800000152,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":{"attemptId":0,"attemptType":"courseFinal","status":"completed","startedAt":"2026-10-14T12:00:00Z","durationSeconds":1440,"submittedAt":"2026-10-14T12:24:00Z","assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"totalScore":56.67,"correctCount":17,"notStudiedCount":0,"totalQuestions":30,"assessedJlptLevelId":1,"assessedJlptLevelName":"N5","recommendedTargetJlptLevelId":1,"recommendedTargetJlptLevelName":"N5","wrongQuestionIds":[15,1900000003,1900000004,1900000005,1900000007,1900000008,1900000009,1900000010,1900000011,1900000012,1900000013,1900000014,1900000015],"levelBreakdowns":[{"jlptLevelId":1,"jlptLevelName":"N5","correctCount":17,"totalCount":30,"scorePercent":56.67}],"sections":[{"mockTestSectionId":0,"sectionTitle":"Từ vựng","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":2,"totalCount":5,"score":40.0,"scorePercent":40.0},{"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":5,"totalCount":5,"score":100.0,"scorePercent":100.0},{"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":1,"totalCount":5,"score":20.0,"scorePercent":20.0},{"mockTestSectionId":2,"sectionTitle":"N5 Grammar","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":5,"totalCount":5,"score":100.0,"scorePercent":100.0},{"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":3,"sectionTitle":"N5 Reading","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":4,"totalCount":5,"score":80.0,"scorePercent":80.0}]},"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":"__ENROLLMENT_ID__","quizId":"__QUIZ_ID__","quizAssignmentId":"__ASSIGNMENT_ID__"}$json$, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_attempt; + INSERT INTO "ClassQuizAssignments" ("QuizId","LearnerId","EnrollmentId","AttemptId","AssignedAtUtc","CompletedAtUtc") VALUES (v_quiz, 900009, v_course, v_attempt, '2026-10-13 02:45:00+00'::timestamptz, '2026-10-14 12:24:00+00'::timestamptz) RETURNING "Id" INTO v_assign; + UPDATE "MockTestAttempts" SET "QuestionSnapshotJson" = replace(replace(replace(replace("QuestionSnapshotJson", '"__COHORT_ID__"', v_cohort::text), '"__ENROLLMENT_ID__"', v_course::text), '"__QUIZ_ID__"', v_quiz::text), '"__ASSIGNMENT_ID__"', v_assign::text) WHERE "Id" = v_attempt; + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 1, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 5, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 9, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 4, 13, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 5, 17, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 6, 21, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 7, 25, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 8, 29, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 9, 33, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 10, 37, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 11, 41, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 12, 45, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 13, 49, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 14, 53, true, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 15, 58, false, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 5, 5, 100.0, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 5, 5, 100.0, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 4, 5, 80.0, '2026-10-14 12:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + -- Kiểm tra kiến thức lần 4: 20/30 = 66.67% + INSERT INTO "ClassQuizzes" ("CohortId","MentorId","CertificateLevelId","Title","TimeLimitMinutes","DueAtUtc","SkillCodes","QuestionCount","QuestionSnapshotJson","StructureKey","Status","PublishedAtUtc","CreatedAtUtc","IsDeleted","Revision") + VALUES (v_cohort, 900002, 1, 'Kiểm tra kiến thức lần 4', 30, '2026-10-16 00:59:00+00'::timestamptz, 'vocabulary,grammar,reading', 30, + replace($json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"0001-01-01T00:00:00Z","expiresAt":"0001-01-01T00:00:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":null,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":null,"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":null,"quizId":null,"quizAssignmentId":null}$json$, '"__COHORT_ID__"', v_cohort::text), + 's:stage5demoseries01|grammar:10,reading:10,vocabulary:10', 'Published', '2026-10-15 02:45:00+00'::timestamptz, '2026-10-15 02:45:00+00'::timestamptz, false, 1) RETURNING "Id" INTO v_quiz; + INSERT INTO "MockTestAttempts" ("UserId","AttemptKind","StartedAt","ExpiresAt","SubmittedAt","IsCompleted","TotalScore","IsPlacementAssessment","QuestionSnapshotJson","CreatedDate","IsDeleted","CreatedBy") + VALUES (900009, 2, '2026-10-15 12:00:00'::timestamp, '2026-10-15 12:30:00'::timestamp, '2026-10-15 12:25:00'::timestamp, true, 66.67, false, $json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"2026-10-15T12:00:00Z","expiresAt":"2026-10-15T12:30:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":1,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":1,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":3,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":4,"content":"Đáp án D","order":4,"isCorrect":false}],"order":1,"selectedOptionId":1,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":2,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":5,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":5,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":6,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":7,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":8,"content":"Đáp án D","order":4,"isCorrect":false}],"order":2,"selectedOptionId":5,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":3,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":9,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":9,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":10,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":11,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":12,"content":"Đáp án D","order":4,"isCorrect":false}],"order":3,"selectedOptionId":9,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":4,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":13,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":13,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":14,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":15,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":16,"content":"Đáp án D","order":4,"isCorrect":false}],"order":4,"selectedOptionId":13,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":5,"mockTestId":1,"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Vocabulary] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":17,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":17,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":18,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":19,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":20,"content":"Đáp án D","order":4,"isCorrect":false}],"order":5,"selectedOptionId":17,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000001,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「たべもの」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000011,"explanation":"「たべもの」 là đồ ăn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000011,"content":"Đồ ăn","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000012,"content":"Đồ uống","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000013,"content":"Quần áo","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000014,"content":"Nhà cửa","order":4,"isCorrect":false}],"order":6,"selectedOptionId":1800000011,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000002,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「やすみ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000021,"explanation":"「やすみ」 là ngày nghỉ, nghỉ ngơi.","topic":null,"options":[{"imageUrl":null,"optionId":1800000021,"content":"Nghỉ ngơi","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000022,"content":"Làm việc","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000023,"content":"Học tập","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000024,"content":"Đi chơi","order":4,"isCorrect":false}],"order":7,"selectedOptionId":1800000021,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000003,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「まいあさ」の いみは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000031,"explanation":"「まい」 = mỗi, 「あさ」 = buổi sáng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000031,"content":"Mỗi sáng","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000032,"content":"Mỗi tối","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000033,"content":"Hôm qua","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000034,"content":"Ngày mai","order":4,"isCorrect":false}],"order":8,"selectedOptionId":1800000031,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000004,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「あたらしい」の はんたいの ことばは どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000041,"explanation":"Trái nghĩa của 「あたらしい」(mới) là 「ふるい」(cũ).","topic":null,"options":[{"imageUrl":null,"optionId":1800000041,"content":"ふるい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000042,"content":"たかい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000043,"content":"ひろい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000044,"content":"おおきい","order":4,"isCorrect":false}],"order":9,"selectedOptionId":1800000042,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000005,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Từ vựng","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","content":"「でんしゃ」は どれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000051,"explanation":"「でんしゃ」(電車) là tàu điện.","topic":null,"options":[{"imageUrl":null,"optionId":1800000051,"content":"Tàu điện","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000052,"content":"Xe buýt","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000053,"content":"Xe đạp","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000054,"content":"Máy bay","order":4,"isCorrect":false}],"order":10,"selectedOptionId":1800000052,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":6,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":21,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":21,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":22,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":23,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":24,"content":"Đáp án D","order":4,"isCorrect":false}],"order":11,"selectedOptionId":21,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":7,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":25,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":25,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":26,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":27,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":28,"content":"Đáp án D","order":4,"isCorrect":false}],"order":12,"selectedOptionId":25,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":8,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":29,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":29,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":30,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":31,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":32,"content":"Đáp án D","order":4,"isCorrect":false}],"order":13,"selectedOptionId":29,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":9,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":33,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":33,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":34,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":35,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":36,"content":"Đáp án D","order":4,"isCorrect":false}],"order":14,"selectedOptionId":33,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":10,"mockTestId":1,"mockTestSectionId":2,"sectionTitle":"N5 Grammar","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Grammar] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":37,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":37,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":38,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":39,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":40,"content":"Đáp án D","order":4,"isCorrect":false}],"order":15,"selectedOptionId":37,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000006,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"わたし( )がくせいです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000061,"explanation":"Trợ từ 「は」 đánh dấu chủ đề của câu.","topic":null,"options":[{"imageUrl":null,"optionId":1800000061,"content":"は","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000062,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000063,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000064,"content":"で","order":4,"isCorrect":false}],"order":16,"selectedOptionId":1800000061,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000007,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"まいにち 7じ( )おきます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000071,"explanation":"Thời điểm cụ thể đi với 「に」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000071,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000072,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000073,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000074,"content":"が","order":4,"isCorrect":false}],"order":17,"selectedOptionId":1800000071,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000008,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"としょかん( )べんきょうします。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000081,"explanation":"Nơi diễn ra hành động dùng 「で」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000081,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000082,"content":"に","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000083,"content":"を","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000084,"content":"へ","order":4,"isCorrect":false}],"order":18,"selectedOptionId":1800000082,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000009,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"きのう えいがを( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000091,"explanation":"「きのう」 là quá khứ nên dùng 「みました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000091,"content":"みました","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000092,"content":"みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000093,"content":"みません","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000094,"content":"みて","order":4,"isCorrect":false}],"order":19,"selectedOptionId":1800000092,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000010,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","sectionOrder":2,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","content":"この りんごは( )です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000101,"explanation":"Tính từ đuôi い đứng trước 「です」 giữ nguyên dạng.","topic":null,"options":[{"imageUrl":null,"optionId":1800000101,"content":"おいしい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000102,"content":"おいしいな","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000103,"content":"おいしく","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000104,"content":"おいしくて","order":4,"isCorrect":false}],"order":20,"selectedOptionId":1800000102,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":11,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #1: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":41,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":41,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":42,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":43,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":44,"content":"Đáp án D","order":4,"isCorrect":false}],"order":21,"selectedOptionId":41,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":12,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #2: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":45,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":45,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":46,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":47,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":48,"content":"Đáp án D","order":4,"isCorrect":false}],"order":22,"selectedOptionId":45,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":13,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #3: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":49,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":49,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":50,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":51,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":52,"content":"Đáp án D","order":4,"isCorrect":false}],"order":23,"selectedOptionId":49,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":14,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #4: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":53,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":53,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":54,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":55,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":56,"content":"Đáp án D","order":4,"isCorrect":false}],"order":24,"selectedOptionId":53,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":15,"mockTestId":1,"mockTestSectionId":3,"sectionTitle":"N5 Reading","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"[N5 · Reading] Câu hỏi mẫu #5: Hãy chọn đáp án đúng nhất.","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":57,"explanation":null,"topic":null,"options":[{"imageUrl":null,"optionId":57,"content":"Đáp án A (Chính xác)","order":1,"isCorrect":true},{"imageUrl":null,"optionId":58,"content":"Đáp án B","order":2,"isCorrect":false},{"imageUrl":null,"optionId":59,"content":"Đáp án C","order":3,"isCorrect":false},{"imageUrl":null,"optionId":60,"content":"Đáp án D","order":4,"isCorrect":false}],"order":25,"selectedOptionId":57,"isCorrect":true,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000011,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なんじに おきますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000111,"explanation":"Câu đầu: 「まいにち 6じに おきます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000111,"content":"6じ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000112,"content":"7じ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000113,"content":"8じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000114,"content":"2じ","order":4,"isCorrect":false}],"order":26,"selectedOptionId":1800000112,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000012,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"ひるごはんは どこで たべますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000121,"explanation":"「ひるごはんは がっこうで…たべます」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000121,"content":"がっこう","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000122,"content":"うち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000123,"content":"レストラン","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000124,"content":"えき","order":4,"isCorrect":false}],"order":27,"selectedOptionId":1800000122,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000013,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"うちへ かえってから なにを しますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"わたしは まいにち 6じに おきます。あさごはんを たべて、8じに がっこうへ いきます。ひるごはんは がっこうで ともだちと たべます。うちへ かえってから、2じかん にほんごを べんきょうします。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000131,"explanation":"Câu cuối của đoạn văn.","topic":null,"options":[{"imageUrl":null,"optionId":1800000131,"content":"にほんごを べんきょうします","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000132,"content":"テレビを みます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000133,"content":"ねます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000134,"content":"かいものを します","order":4,"isCorrect":false}],"order":28,"selectedOptionId":1800000132,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000014,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"だれと デパートへ いきましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000141,"explanation":"「あねと デパートへ いきました」.","topic":null,"options":[{"imageUrl":null,"optionId":1800000141,"content":"あね","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000142,"content":"はは","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000143,"content":"ともだち","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000144,"content":"せんせい","order":4,"isCorrect":false}],"order":29,"selectedOptionId":1800000142,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null},{"questionId":1900000015,"mockTestId":0,"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","content":"わたしは なにを かいましたか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":"Đoạn văn","passageText":"きょうは にちようびです。あねと デパートへ いきました。あねは くつを かいました。わたしは あおい かばんを かいました。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1800000151,"explanation":"Chị mua giày, \"tôi\" mua cặp xanh.","topic":null,"options":[{"imageUrl":null,"optionId":1800000151,"content":"かばん","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1800000152,"content":"くつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1800000153,"content":"ほん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1800000154,"content":"とけい","order":4,"isCorrect":false}],"order":30,"selectedOptionId":1800000152,"isCorrect":false,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null}],"completedResult":{"attemptId":0,"attemptType":"courseFinal","status":"completed","startedAt":"2026-10-15T12:00:00Z","durationSeconds":1500,"submittedAt":"2026-10-15T12:25:00Z","assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"totalScore":66.67,"correctCount":20,"notStudiedCount":0,"totalQuestions":30,"assessedJlptLevelId":1,"assessedJlptLevelName":"N5","recommendedTargetJlptLevelId":1,"recommendedTargetJlptLevelName":"N5","wrongQuestionIds":[1900000004,1900000005,1900000008,1900000009,1900000010,1900000011,1900000012,1900000013,1900000014,1900000015],"levelBreakdowns":[{"jlptLevelId":1,"jlptLevelName":"N5","correctCount":20,"totalCount":30,"scorePercent":66.67}],"sections":[{"mockTestSectionId":0,"sectionTitle":"Từ vựng","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":3,"totalCount":5,"score":60.0,"scorePercent":60.0},{"mockTestSectionId":1,"sectionTitle":"N5 Vocabulary","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":5,"totalCount":5,"score":100.0,"scorePercent":100.0},{"mockTestSectionId":0,"sectionTitle":"Ngữ pháp","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":2,"totalCount":5,"score":40.0,"scorePercent":40.0},{"mockTestSectionId":2,"sectionTitle":"N5 Grammar","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":5,"totalCount":5,"score":100.0,"scorePercent":100.0},{"mockTestSectionId":0,"sectionTitle":"Đọc hiểu","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":5,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":3,"sectionTitle":"N5 Reading","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":5,"totalCount":5,"score":100.0,"scorePercent":100.0}]},"purpose":"ClassQuiz","cohortId":"__COHORT_ID__","enrollmentId":"__ENROLLMENT_ID__","quizId":"__QUIZ_ID__","quizAssignmentId":"__ASSIGNMENT_ID__"}$json$, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_attempt; + INSERT INTO "ClassQuizAssignments" ("QuizId","LearnerId","EnrollmentId","AttemptId","AssignedAtUtc","CompletedAtUtc") VALUES (v_quiz, 900009, v_course, v_attempt, '2026-10-15 02:45:00+00'::timestamptz, '2026-10-15 12:25:00+00'::timestamptz) RETURNING "Id" INTO v_assign; + UPDATE "MockTestAttempts" SET "QuestionSnapshotJson" = replace(replace(replace(replace("QuestionSnapshotJson", '"__COHORT_ID__"', v_cohort::text), '"__ENROLLMENT_ID__"', v_course::text), '"__QUIZ_ID__"', v_quiz::text), '"__ASSIGNMENT_ID__"', v_assign::text) WHERE "Id" = v_attempt; + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 1, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 5, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 9, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 4, 13, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 5, 17, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 6, 21, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 7, 25, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 8, 29, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 9, 33, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 10, 37, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 11, 41, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 12, 45, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 13, 49, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 14, 53, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 15, 57, true, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 1, 5, 5, 100.0, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 2, 5, 5, 100.0, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 3, 5, 5, 100.0, '2026-10-15 12:25:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + RAISE NOTICE 'Quiz demo seeded for cohort %', v_cohort; +END +$seed$; diff --git a/seed-data/dev-stage5-competency-demo-cleanup.sql b/seed-data/dev-stage5-competency-demo-cleanup.sql new file mode 100644 index 0000000..7d6129e --- /dev/null +++ b/seed-data/dev-stage5-competency-demo-cleanup.sql @@ -0,0 +1,32 @@ +-- ============================================================================================= +-- RikiPath Stage 5 — remove the competency demo seed (DEVELOPMENT / LOCAL ONLY). +-- Deletes only rows created by dev-stage5-competency-demo.sql (identified by its markers). +-- ============================================================================================= +DO $cleanup$ +DECLARE v_cohort int; v_course int; +BEGIN + IF current_database() <> 'rikipath_local' THEN RAISE EXCEPTION 'Cleanup runs only on rikipath_local (found %)', current_database(); END IF; + SELECT "Id" INTO v_cohort FROM "StudyCohorts" WHERE "Name" = '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành'; + SELECT "Id" INTO v_course FROM "StudyCourses" WHERE "LearnerId" = 900009 AND "PurchaseKey" = '5e5d0005-de30-4000-8000-000000900009'::uuid; + IF v_cohort IS NOT NULL THEN + DELETE FROM "ClassQuizAssignments" WHERE "QuizId" IN (SELECT "Id" FROM "ClassQuizzes" WHERE "CohortId" = v_cohort); + DELETE FROM "ClassQuizzes" WHERE "CohortId" = v_cohort; + END IF; + DELETE FROM "MockTestSectionResults" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid; + DELETE FROM "MockTestAnswers" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid; + DELETE FROM "MockTestAttempts" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid AND "UserId" = 900009 AND "AttemptKind" = 2; + DELETE FROM "GradingResults" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid; + DELETE FROM "HomeworkSubmissions" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid; + DELETE FROM "HomeworkAssignments" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid; + IF v_course IS NOT NULL THEN + DELETE FROM "StudyCourseSessions" WHERE "CourseId" = v_course; + DELETE FROM "StudyCourses" WHERE "Id" = v_course; + END IF; + IF v_cohort IS NOT NULL THEN + DELETE FROM "StudyCohortSessions" WHERE "CohortId" = v_cohort; + DELETE FROM "StudyCohorts" WHERE "Id" = v_cohort; + END IF; + DELETE FROM "MentorAvailabilities" WHERE "CreatedBy" = '5e5d0005-de30-4000-8000-000000000005'::uuid AND "MentorId" = 900002; + RAISE NOTICE 'Stage 5 demo removed (cohort %, enrollment %)', v_cohort, v_course; +END +$cleanup$; diff --git a/seed-data/dev-stage5-competency-demo.sql b/seed-data/dev-stage5-competency-demo.sql new file mode 100644 index 0000000..25673b3 --- /dev/null +++ b/seed-data/dev-stage5-competency-demo.sql @@ -0,0 +1,254 @@ +-- ============================================================================================= +-- RikiPath Stage 5 — competency demo seed (DEVELOPMENT / LOCAL ONLY). Generated, do not edit by hand. +-- Learner: Hoang Pham (UserId 900009, learner4.meeting@rikipath.local) · Mentor: Mentor One (900002). +-- Creates ONE separate, already completed N5 class with 10 sessions (9 present / 1 absent), 10 graded +-- homework (5.5 → 9.0 /10), a class-pinned pre-course baseline (30%) and an end-of-course assessment (70%). +-- Idempotent: it does nothing when the demo class already exists. Remove with +-- dev-stage5-competency-demo-cleanup.sql. Never run against Staging/Production/Supabase. +-- Markers: StudyCohorts.Name = '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành', StudyCourses.PurchaseKey = 5e5d0005-de30-4000-8000-000000900009, +-- CreatedBy = 5e5d0005-de30-4000-8000-000000000005 on availability/homework/assessment rows. +-- ============================================================================================= +DO $seed$ +DECLARE + v_cohort int; v_course int; v_avail int; v_hw int; v_sub int; v_attempt int; v_existing int; + v_avail_ids int[] := ARRAY[]::int[]; +BEGIN + IF current_database() <> 'rikipath_local' THEN RAISE EXCEPTION 'Stage 5 demo seed runs only on rikipath_local (found %)', current_database(); END IF; + IF NOT EXISTS (SELECT 1 FROM "Users" WHERE "Id" = 900009 AND "Email" = 'learner4.meeting@rikipath.local' AND "Role" = 'Learner') THEN RAISE EXCEPTION 'Demo learner 900009 not found'; END IF; + IF NOT EXISTS (SELECT 1 FROM "Users" WHERE "Id" = 900002 AND "Role" = 'Mentor') THEN RAISE EXCEPTION 'Demo mentor 900002 not found'; END IF; + IF NOT EXISTS (SELECT 1 FROM "StudyCoursePlans" WHERE "Id" = 5 AND "CertificateLevelId" = 1 AND "SessionType" = 'Group') THEN RAISE EXCEPTION 'N5 group plan 5 not found'; END IF; + SELECT "Id" INTO v_existing FROM "StudyCohorts" WHERE "Name" = '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành'; + IF v_existing IS NOT NULL THEN RAISE NOTICE 'Stage 5 demo class already exists (cohort %), nothing to do.', v_existing; RETURN; END IF; + IF EXISTS (SELECT 1 FROM "MentorAvailabilities" WHERE "MentorId" = 900002 AND NOT "IsDeleted" AND "StartTime" < '2026-10-17' AND "EndTime" > '2026-10-05') THEN RAISE EXCEPTION 'Mentor 900002 already has slots between 2026-10-05 and 2026-10-16; refusing to create overlapping demo sessions'; END IF; + + -- 1. Separate demo class, already completed (all 10 sessions delivered). + INSERT INTO "StudyCohorts" ("PlanId","Name","MentorId","StartsAt","EndsAt","Capacity","Status","Revision","CapacitySnapshot","CreatedAtUtc","GroupPolicyId","PolicyVersionSnapshot","CourseDurationWeeks","EnrollmentOpensAtUtc","EnrollmentClosesAtUtc","EnrollmentClosedAtUtc") + VALUES (5, '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành', 900002, '2026-10-05 01:00:00'::timestamp, '2026-10-16 02:30:00'::timestamp, 4, 'Completed', 1, 4, '2026-09-20 02:00:00', 1, 1, 2, '2026-09-20 02:00:00+00', '2026-10-02 16:59:59+00', '2026-10-02 17:00:00+00') + RETURNING "Id" INTO v_cohort; + + -- 2. Ten approved teaching slots of Mentor One (no meeting-room history is created). + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-05 01:00:00'::timestamp, '2026-10-05 02:30:00'::timestamp, md5('stage5-demo-room-1')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 1, v_avail, 'Completed', '2026-10-05 01:00:00+00'::timestamptz, '2026-10-05 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-06 01:00:00'::timestamp, '2026-10-06 02:30:00'::timestamp, md5('stage5-demo-room-2')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 2, v_avail, 'Completed', '2026-10-06 01:00:00+00'::timestamptz, '2026-10-06 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-07 01:00:00'::timestamp, '2026-10-07 02:30:00'::timestamp, md5('stage5-demo-room-3')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 3, v_avail, 'Completed', '2026-10-07 01:00:00+00'::timestamptz, '2026-10-07 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-08 01:00:00'::timestamp, '2026-10-08 02:30:00'::timestamp, md5('stage5-demo-room-4')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 4, v_avail, 'Completed', '2026-10-08 01:00:00+00'::timestamptz, '2026-10-08 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-09 01:00:00'::timestamp, '2026-10-09 02:30:00'::timestamp, md5('stage5-demo-room-5')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 5, v_avail, 'Completed', '2026-10-09 01:00:00+00'::timestamptz, '2026-10-09 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-12 01:00:00'::timestamp, '2026-10-12 02:30:00'::timestamp, md5('stage5-demo-room-6')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 6, v_avail, 'Completed', '2026-10-12 01:00:00+00'::timestamptz, '2026-10-12 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-13 01:00:00'::timestamp, '2026-10-13 02:30:00'::timestamp, md5('stage5-demo-room-7')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 7, v_avail, 'Completed', '2026-10-13 01:00:00+00'::timestamptz, '2026-10-13 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-14 01:00:00'::timestamp, '2026-10-14 02:30:00'::timestamp, md5('stage5-demo-room-8')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 8, v_avail, 'Completed', '2026-10-14 01:00:00+00'::timestamptz, '2026-10-14 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-15 01:00:00'::timestamp, '2026-10-15 02:30:00'::timestamp, md5('stage5-demo-room-9')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 9, v_avail, 'Completed', '2026-10-15 01:00:00+00'::timestamptz, '2026-10-15 02:30:00+00'::timestamptz); + INSERT INTO "MentorAvailabilities" ("MentorId","StartTime","EndTime","RoomId","MaxLearners","BookedCount","IsApproved","AdminName","PublishedAt","CreatedDate","IsDeleted","AttendanceTrackingEnabled","CreatedBy") + VALUES (900002, '2026-10-16 01:00:00'::timestamp, '2026-10-16 02:30:00'::timestamp, md5('stage5-demo-room-10')::uuid, 4, 0, true, 'Mentor One', '2026-09-20 02:00:00', '2026-09-20 02:00:00', false, true, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_avail; + v_avail_ids := v_avail_ids || v_avail; + INSERT INTO "StudyCohortSessions" ("CohortId","Number","AvailabilityId","Status","ActualStartedAtUtc","ActualEndedAtUtc") + VALUES (v_cohort, 10, v_avail, 'Completed', '2026-10-16 01:00:00+00'::timestamptz, '2026-10-16 02:30:00+00'::timestamptz); + + -- 3. Hoang Pham enrollment (confirmed, completed). Amount 0: no payment or PayOS transaction is simulated. + INSERT INTO "StudyCourses" ("LearnerId","PurchaseKey","MentorId","PlanId","Name","CertificateLevelId","PlanRevision","DurationMonths","SessionsPerWeek","SessionMinutes","TotalSessions","RetakeClaimDays","MinimumHomeworkPercent","MaximumAbsencePercent","Amount","PaymentStatus","Status","CreatedAt","StartsAt","EndsAt","CompletedAt","CohortId","SessionType","CapacitySnapshot","GroupPolicyId","PolicyVersionSnapshot","Currency","OrderSnapshot","PaymentConfirmedAtUtc","RefundedAmount") + VALUES (900009, '5e5d0005-de30-4000-8000-000000900009'::uuid, 900002, 5, '[Demo Stage 5] Lớp JLPT N5 đã hoàn thành', 1, 1, 1, 5, 90, 10, 30, 90, 20, 0, 'Paid', 'Completed', '2026-09-26 03:00:00', '2026-10-05 01:00:00'::timestamp, '2026-10-16 02:30:00'::timestamp, '2026-10-16 02:30:00'::timestamp, v_cohort, 'Group', 4, 1, 1, 'VND', '{"cohortName": "[Demo Stage 5] Lớp JLPT N5 đã hoàn thành", "planId": 5, "planRevision": 1, "totalSessions": 10, "sessionMinutes": 90, "currency": "VND", "demoSeed": "stage5-competency"}', '2026-09-26 03:00:00', 0) + RETURNING "Id" INTO v_course; + + -- 4. Attendance: present 9/10 (session 6 absent), confirmed by the Mentor at the end of each session. + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 1, 1, '2026-10-05 01:00:00'::timestamp, 'Present', 900002, '2026-10-05 02:30:00'::timestamp, v_avail_ids[1]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 2, 1, '2026-10-06 01:00:00'::timestamp, 'Present', 900002, '2026-10-06 02:30:00'::timestamp, v_avail_ids[2]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 3, 1, '2026-10-07 01:00:00'::timestamp, 'Present', 900002, '2026-10-07 02:30:00'::timestamp, v_avail_ids[3]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 4, 1, '2026-10-08 01:00:00'::timestamp, 'Present', 900002, '2026-10-08 02:30:00'::timestamp, v_avail_ids[4]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 5, 1, '2026-10-09 01:00:00'::timestamp, 'Present', 900002, '2026-10-09 02:30:00'::timestamp, v_avail_ids[5]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 6, 1, '2026-10-12 01:00:00'::timestamp, 'Absent', 900002, '2026-10-12 02:30:00'::timestamp, v_avail_ids[6]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 7, 1, '2026-10-13 01:00:00'::timestamp, 'Present', 900002, '2026-10-13 02:30:00'::timestamp, v_avail_ids[7]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 8, 1, '2026-10-14 01:00:00'::timestamp, 'Present', 900002, '2026-10-14 02:30:00'::timestamp, v_avail_ids[8]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 9, 1, '2026-10-15 01:00:00'::timestamp, 'Present', 900002, '2026-10-15 02:30:00'::timestamp, v_avail_ids[9]); + INSERT INTO "StudyCourseSessions" ("CourseId","Number","Attempt","ScheduledAt","Status","ConfirmedById","ConfirmedAt","AvailabilityId") + VALUES (v_course, 10, 1, '2026-10-16 01:00:00'::timestamp, 'Present', 900002, '2026-10-16 02:30:00'::timestamp, v_avail_ids[10]); + + -- 5. Ten class homework: submitted before the deadline, graded and published after submission (0–100 stored = score × 10). + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 1 · Chào hỏi và giới thiệu bản thân', 'Hoàn thành bài luyện tập của buổi 1 và nộp trước hạn.', '2026-10-05 16:59:00'::timestamp, 'Graded', '2026-10-05 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-1')::uuid, v_cohort, 'Nắm được các câu chào cơ bản nhưng còn nhầm です/ます ở câu giới thiệu. Ôn lại mẫu câu tự giới thiệu và viết lại 3 câu.', 55, 900002, '2026-10-06 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 1 của học viên.', '2026-10-05 12:15:00'::timestamp, '2026-10-05 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 55, '{"feedback": "Nắm được các câu chào cơ bản nhưng còn nhầm です/ます ở câu giới thiệu. Ôn lại mẫu câu tự giới thiệu và viết lại 3 câu.", "corrections": []}', '2026-10-06 03:00:00'::timestamp, '2026-10-06 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 2 · Số đếm và thời gian', 'Hoàn thành bài luyện tập của buổi 2 và nộp trước hạn.', '2026-10-06 16:59:00'::timestamp, 'Graded', '2026-10-06 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-2')::uuid, v_cohort, 'Đọc số và giờ đã đúng phần lớn. Cần luyện thêm cách đọc phút (ふん/ぷん) và các ngày trong tháng.', 60, 900002, '2026-10-07 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 2 của học viên.', '2026-10-06 12:15:00'::timestamp, '2026-10-06 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 60, '{"feedback": "Đọc số và giờ đã đúng phần lớn. Cần luyện thêm cách đọc phút (ふん/ぷん) và các ngày trong tháng.", "corrections": []}', '2026-10-07 03:00:00'::timestamp, '2026-10-07 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 3 · Trợ từ は・が・を', 'Hoàn thành bài luyện tập của buổi 3 và nộp trước hạn.', '2026-10-07 16:59:00'::timestamp, 'Graded', '2026-10-07 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-3')::uuid, v_cohort, 'Đã phân biệt được は và を trong câu đơn. Một số câu còn dùng が chưa đúng ngữ cảnh, xem lại phần ví dụ.', 65, 900002, '2026-10-08 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 3 của học viên.', '2026-10-07 12:15:00'::timestamp, '2026-10-07 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 65, '{"feedback": "Đã phân biệt được は và を trong câu đơn. Một số câu còn dùng が chưa đúng ngữ cảnh, xem lại phần ví dụ.", "corrections": []}', '2026-10-08 03:00:00'::timestamp, '2026-10-08 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 4 · Động từ thể ます', 'Hoàn thành bài luyện tập của buổi 4 và nộp trước hạn.', '2026-10-08 16:59:00'::timestamp, 'Graded', '2026-10-08 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-4')::uuid, v_cohort, 'Chia thể ます chính xác ở hầu hết động từ nhóm 1 và 2. Chú ý thêm động từ bất quy tắc する・くる.', 70, 900002, '2026-10-09 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 4 của học viên.', '2026-10-08 12:15:00'::timestamp, '2026-10-08 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 70, '{"feedback": "Chia thể ます chính xác ở hầu hết động từ nhóm 1 và 2. Chú ý thêm động từ bất quy tắc する・くる.", "corrections": []}', '2026-10-09 03:00:00'::timestamp, '2026-10-09 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 5 · Tính từ đuôi い và な', 'Hoàn thành bài luyện tập của buổi 5 và nộp trước hạn.', '2026-10-09 16:59:00'::timestamp, 'Graded', '2026-10-09 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-5')::uuid, v_cohort, 'Dùng tính từ đúng trong câu khẳng định. Phần phủ định của tính từ な cần luyện thêm.', 75, 900002, '2026-10-10 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 5 của học viên.', '2026-10-09 12:15:00'::timestamp, '2026-10-09 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 75, '{"feedback": "Dùng tính từ đúng trong câu khẳng định. Phần phủ định của tính từ な cần luyện thêm.", "corrections": []}', '2026-10-10 03:00:00'::timestamp, '2026-10-10 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 6 · Hỏi đường và địa điểm', 'Hoàn thành bài luyện tập của buổi 6 và nộp trước hạn.', '2026-10-12 16:59:00'::timestamp, 'Graded', '2026-10-12 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-6')::uuid, v_cohort, 'Bài làm tốt, dùng đúng どこ・ここ・そこ・あそこ. Có thể tập nói lại đoạn hội thoại để nhớ lâu hơn.', 80, 900002, '2026-10-13 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 6 của học viên.', '2026-10-12 12:15:00'::timestamp, '2026-10-12 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 80, '{"feedback": "Bài làm tốt, dùng đúng どこ・ここ・そこ・あそこ. Có thể tập nói lại đoạn hội thoại để nhớ lâu hơn.", "corrections": []}', '2026-10-13 03:00:00'::timestamp, '2026-10-13 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 7 · Thể て và câu yêu cầu', 'Hoàn thành bài luyện tập của buổi 7 và nộp trước hạn.', '2026-10-13 16:59:00'::timestamp, 'Graded', '2026-10-13 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-7')::uuid, v_cohort, 'Chia thể て đúng và đặt câu yêu cầu tự nhiên. Tiếp tục duy trì như vậy.', 80, 900002, '2026-10-14 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 7 của học viên.', '2026-10-13 12:15:00'::timestamp, '2026-10-13 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 80, '{"feedback": "Chia thể て đúng và đặt câu yêu cầu tự nhiên. Tiếp tục duy trì như vậy.", "corrections": []}', '2026-10-14 03:00:00'::timestamp, '2026-10-14 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 8 · Đọc hiểu đoạn văn ngắn', 'Hoàn thành bài luyện tập của buổi 8 và nộp trước hạn.', '2026-10-14 16:59:00'::timestamp, 'Graded', '2026-10-14 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-8')::uuid, v_cohort, 'Tìm đúng ý chính của đoạn văn. Lần sau gạch chân từ khóa trước khi chọn đáp án để làm nhanh hơn.', 85, 900002, '2026-10-15 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 8 của học viên.', '2026-10-14 12:15:00'::timestamp, '2026-10-14 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 85, '{"feedback": "Tìm đúng ý chính của đoạn văn. Lần sau gạch chân từ khóa trước khi chọn đáp án để làm nhanh hơn.", "corrections": []}', '2026-10-15 03:00:00'::timestamp, '2026-10-15 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 9 · Nghe hội thoại mua sắm', 'Hoàn thành bài luyện tập của buổi 9 và nộp trước hạn.', '2026-10-15 16:59:00'::timestamp, 'Graded', '2026-10-15 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-9')::uuid, v_cohort, 'Nghe hiểu tốt các con số và giá tiền. Rất tốt, hãy giữ thói quen nghe mỗi ngày.', 90, 900002, '2026-10-16 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 9 của học viên.', '2026-10-15 12:15:00'::timestamp, '2026-10-15 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 90, '{"feedback": "Nghe hiểu tốt các con số và giá tiền. Rất tốt, hãy giữ thói quen nghe mỗi ngày.", "corrections": []}', '2026-10-16 03:00:00'::timestamp, '2026-10-16 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "HomeworkAssignments" ("LearnerId","MentorId","Title","Instructions","DueAt","Status","CreatedDate","IsDeleted","AssignmentScope","CohortAssignmentGroupKey","CohortId","MentorFeedback","MentorScore","PublishedByMentorId","PublishedFeedbackAtUtc","StudyCourseId","CreatedBy") + VALUES (900009, 900002, 'Bài 10 · Ôn tập tổng hợp N5', 'Hoàn thành bài luyện tập của buổi 10 và nộp trước hạn.', '2026-10-16 16:59:00'::timestamp, 'Graded', '2026-10-16 02:40:00'::timestamp, false, 'CohortCommon', md5('stage5-demo-hw-10')::uuid, v_cohort, 'Kết quả ôn tập tốt và đều ở các phần. Nên tiếp tục luyện đề đọc hiểu trước kỳ thi.', 90, 900002, '2026-10-17 03:00:00'::timestamp, v_course, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_hw; + INSERT INTO "HomeworkSubmissions" ("HomeworkAssignmentId","LearnerId","TextContent","SubmittedAt","CreatedDate","IsDeleted","RevisionCount","CreatedBy") + VALUES (v_hw, 900009, 'Bài làm buổi 10 của học viên.', '2026-10-16 12:15:00'::timestamp, '2026-10-16 12:15:00'::timestamp, false, 1, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_sub; + INSERT INTO "GradingResults" ("HomeworkSubmissionId","OverallScore","FeedbackJson","GradedAt","CreatedDate","IsDeleted","CreatedBy") + VALUES (v_sub, 90, '{"feedback": "Kết quả ôn tập tốt và đều ở các phần. Nên tiếp tục luyện đề đọc hiểu trước kỳ thi.", "corrections": []}', '2026-10-17 03:00:00'::timestamp, '2026-10-17 03:00:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + + -- 6. Pre-course baseline pinned to this class (taken 2026-10-01, before the first session): 9/30 = 30%. + INSERT INTO "MockTestAttempts" ("UserId","AttemptKind","StartedAt","ExpiresAt","SubmittedAt","IsCompleted","TotalScore","IsPlacementAssessment","QuestionSnapshotJson","CreatedDate","IsDeleted","CreatedBy") + VALUES (900009, 2, '2026-10-01 13:00:00'::timestamp, '2026-10-01 13:30:00'::timestamp, '2026-10-01 13:24:00'::timestamp, true, 30.0, false, + replace(replace($json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"2026-10-01T13:00:00Z","expiresAt":"2026-10-01T13:30:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":299,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":1,"content":"「朝」の読み方はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1194,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1194,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1193,"content":"ひる","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1194,"content":"あさ","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1195,"content":"よる","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1196,"content":"ゆう","order":4,"isCorrect":false}]},{"questionId":300,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":2,"content":"「店」の読み方はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1200,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1200,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1197,"content":"まち","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1198,"content":"えき","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1199,"content":"いえ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1200,"content":"みせ","order":4,"isCorrect":true}]},{"questionId":301,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":3,"content":"この スープは( )です。まだ 飲めません。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1201,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1201,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1201,"content":"あつい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1202,"content":"ひろい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1203,"content":"あかるい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1204,"content":"おそい","order":4,"isCorrect":false}]},{"questionId":302,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":4,"content":"てがみを( )で出しました。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1207,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1207,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1205,"content":"こうえん","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1206,"content":"びょういん","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1207,"content":"ゆうびんきょく","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1208,"content":"きっさてん","order":4,"isCorrect":false}]},{"questionId":303,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":5,"content":"「きょうの つぎの ひ」と同じ意味はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1212,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1209,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1209,"content":"きのう","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1210,"content":"おととい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1211,"content":"けさ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1212,"content":"あした","order":4,"isCorrect":true}]},{"questionId":304,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":6,"content":"「教室」の読み方はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1215,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1213,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1213,"content":"きょしつ","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1214,"content":"きょうじつ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1215,"content":"きょうしつ","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1216,"content":"きゅうしつ","order":4,"isCorrect":false}]},{"questionId":305,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":7,"content":"「午後」の読み方はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1220,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1217,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1217,"content":"ごぜん","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1218,"content":"ごこう","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1219,"content":"こうご","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1220,"content":"ごご","order":4,"isCorrect":true}]},{"questionId":306,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":8,"content":"黒板の 字を ノートに( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1222,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1221,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1221,"content":"飲みます","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1222,"content":"書きます","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1223,"content":"開けます","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1224,"content":"歩きます","order":4,"isCorrect":false}]},{"questionId":307,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":9,"content":"雨ですから、( )を 持って 行きます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1225,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1226,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1225,"content":"かさ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1226,"content":"さら","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1227,"content":"かぎ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1228,"content":"はし","order":4,"isCorrect":false}]},{"questionId":308,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":10,"content":"「近い」の反対はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1231,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1229,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1229,"content":"軽い","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1230,"content":"低い","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1231,"content":"遠い","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1232,"content":"細い","order":4,"isCorrect":false}]},{"questionId":319,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":11,"content":"毎朝、七時( )起きます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1274,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1274,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1273,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1274,"content":"に","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1275,"content":"で","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1276,"content":"が","order":4,"isCorrect":false}]},{"questionId":320,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":12,"content":"これは わたし( )かさです。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1277,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1277,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1277,"content":"の","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1278,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1279,"content":"へ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1280,"content":"と","order":4,"isCorrect":false}]},{"questionId":321,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":13,"content":"この りんごは あまり( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1283,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1283,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1281,"content":"あまいです","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1282,"content":"あまかったです","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1283,"content":"あまくないです","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1284,"content":"あまくなります","order":4,"isCorrect":false}]},{"questionId":322,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":14,"content":"田中さん( )いっしょに 昼ごはんを 食べました。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1286,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1285,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1285,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1286,"content":"と","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1287,"content":"へ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1288,"content":"が","order":4,"isCorrect":false}]},{"questionId":323,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":15,"content":"図書館( )本を 読みます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1290,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1289,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1289,"content":"に","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1290,"content":"で","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1291,"content":"へ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1292,"content":"を","order":4,"isCorrect":false}]},{"questionId":324,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":16,"content":"つくえの 上( )本が あります。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1296,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1293,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1293,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1294,"content":"へ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1295,"content":"と","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1296,"content":"に","order":4,"isCorrect":true}]},{"questionId":325,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":17,"content":"きのうは 学校へ( )。家に いました。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1299,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1297,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1297,"content":"行きません","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1298,"content":"行きます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1299,"content":"行きませんでした","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1300,"content":"行きました","order":4,"isCorrect":false}]},{"questionId":326,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":18,"content":"つぎの ページを( )ください。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1301,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1302,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1301,"content":"見て","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1302,"content":"見る","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1303,"content":"見た","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1304,"content":"見ます","order":4,"isCorrect":false}]},{"questionId":327,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":19,"content":"毎日、電車( )会社へ 行きます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1305,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1306,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1305,"content":"で","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1306,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1307,"content":"に","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1308,"content":"が","order":4,"isCorrect":false}]},{"questionId":328,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":20,"content":"かばんの 中に さいふ( )あります。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1310,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1309,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1309,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1310,"content":"が","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1311,"content":"で","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1312,"content":"へ","order":4,"isCorrect":false}]},{"questionId":343,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":21,"content":"図書館は 土曜日に 開いていますか。","audioUrl":null,"imageUrl":null,"passageId":3,"passageTitle":"【読解】","passageText":"学校の 図書館は 月曜日から 金曜日まで 開いています。水曜日だけ 午後三時に 閉まります。ほかの 日は 午後五時に 閉まります。本は 一人 三冊まで 借りられます。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1370,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1370,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1369,"content":"はい、午後三時までです。","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1370,"content":"いいえ、開いていません。","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1371,"content":"はい、午後五時までです。","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1372,"content":"はい、午前だけです。","order":4,"isCorrect":false}]},{"questionId":344,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":22,"content":"水曜日は 何時に 閉まりますか。","audioUrl":null,"imageUrl":null,"passageId":3,"passageTitle":"【読解】","passageText":"学校の 図書館は 月曜日から 金曜日まで 開いています。水曜日だけ 午後三時に 閉まります。ほかの 日は 午後五時に 閉まります。本は 一人 三冊まで 借りられます。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1376,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1373,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1373,"content":"午前三時","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1374,"content":"午後五時","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1375,"content":"午前五時","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1376,"content":"午後三時","order":4,"isCorrect":true}]},{"questionId":345,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":23,"content":"一人で 本を 何冊まで 借りられますか。","audioUrl":null,"imageUrl":null,"passageId":3,"passageTitle":"【読解】","passageText":"学校の 図書館は 月曜日から 金曜日まで 開いています。水曜日だけ 午後三時に 閉まります。ほかの 日は 午後五時に 閉まります。本は 一人 三冊まで 借りられます。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1377,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1378,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1377,"content":"三冊","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1378,"content":"一冊","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1379,"content":"二冊","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1380,"content":"五冊","order":4,"isCorrect":false}]},{"questionId":346,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":24,"content":"店は どこに ありますか。","audioUrl":null,"imageUrl":null,"passageId":4,"passageTitle":"【読解】","passageText":"さとうさんは 土曜日に 駅の 前の 店へ 行きます。白い シャツは 2,000円で、青い シャツは 1,500円です。さとうさんは 青い シャツを 一枚 買います。それから、駅で 妹を 待ちます。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1383,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1381,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1381,"content":"駅の中","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1382,"content":"学校の前","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1383,"content":"駅の前","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1384,"content":"家の近く","order":4,"isCorrect":false}]},{"questionId":347,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":25,"content":"さとうさんは シャツに いくら 払いますか。","audioUrl":null,"imageUrl":null,"passageId":4,"passageTitle":"【読解】","passageText":"さとうさんは 土曜日に 駅の 前の 店へ 行きます。白い シャツは 2,000円で、青い シャツは 1,500円です。さとうさんは 青い シャツを 一枚 買います。それから、駅で 妹を 待ちます。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1388,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1385,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1385,"content":"2,000円","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1386,"content":"3,000円","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1387,"content":"3,500円","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1388,"content":"1,500円","order":4,"isCorrect":true}]},{"questionId":348,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":26,"content":"買い物の あと、何を しますか。","audioUrl":null,"imageUrl":null,"passageId":4,"passageTitle":"【読解】","passageText":"さとうさんは 土曜日に 駅の 前の 店へ 行きます。白い シャツは 2,000円で、青い シャツは 1,500円です。さとうさんは 青い シャツを 一枚 買います。それから、駅で 妹を 待ちます。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1390,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1389,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1389,"content":"店で妹を待ちます。","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1390,"content":"駅で妹を待ちます。","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1391,"content":"白いシャツを買います。","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1392,"content":"電車に乗ります。","order":4,"isCorrect":false}]},{"questionId":544,"mockTestId":35,"mockTestSectionId":63,"sectionTitle":"Nghe hiểu","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":27,"content":"おんなの人は きのうの よる 何を しましたか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2174,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2174,"isCorrect":true,"options":[{"imageUrl":null,"optionId":2173,"content":"テレビを みました","order":1,"isCorrect":false},{"imageUrl":null,"optionId":2174,"content":"本を よみました","order":2,"isCorrect":true},{"imageUrl":null,"optionId":2175,"content":"てがみを かきました","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2176,"content":"ねました","order":4,"isCorrect":false}]},{"questionId":545,"mockTestId":35,"mockTestSectionId":63,"sectionTitle":"Nghe hiểu","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":28,"content":"おとこの人の かさは どれですか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2177,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2178,"isCorrect":false,"options":[{"imageUrl":null,"optionId":2177,"content":"ながくて くろい かさ","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2178,"content":"みじかくて しろい かさ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":2179,"content":"ながくて あおい かさ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2180,"content":"みじかくて くろい かさ","order":4,"isCorrect":false}]},{"questionId":546,"mockTestId":35,"mockTestSectionId":63,"sectionTitle":"Nghe hiểu","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":29,"content":"みせで おんなの人が 注文したのは どれですか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2182,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2181,"isCorrect":false,"options":[{"imageUrl":null,"optionId":2181,"content":"コーヒー ひとつと ケーキ ふたつ","order":1,"isCorrect":false},{"imageUrl":null,"optionId":2182,"content":"コーヒー ふたつと ケーキ ひとつ","order":2,"isCorrect":true},{"imageUrl":null,"optionId":2183,"content":"おちゃ ひとつと ケーキ ひとつ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2184,"content":"コーヒー ふたつだけ","order":4,"isCorrect":false}]},{"questionId":532,"mockTestId":34,"mockTestSectionId":60,"sectionTitle":"Phần 3: Nghe hiểu N5","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":30,"content":"おとこの人と おんなの人が 話しています。あした 何じに 駅で あいますか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2126,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2125,"isCorrect":false,"options":[{"imageUrl":null,"optionId":2125,"content":"8じ","order":1,"isCorrect":false},{"imageUrl":null,"optionId":2126,"content":"8じはん","order":2,"isCorrect":true},{"imageUrl":null,"optionId":2127,"content":"9じ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2128,"content":"9じはん","order":4,"isCorrect":false}]}],"completedResult":{"attemptId":0,"attemptType":"placement","status":"completed","startedAt":"2026-10-01T13:00:00Z","durationSeconds":1440,"submittedAt":"2026-10-01T13:24:00Z","assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"totalScore":30.0,"correctCount":9,"notStudiedCount":0,"totalQuestions":30,"assessedJlptLevelId":1,"assessedJlptLevelName":"N5","recommendedTargetJlptLevelId":1,"recommendedTargetJlptLevelName":"N5","wrongQuestionIds":[303,304,305,306,307,308,322,323,324,325,326,327,328,344,345,346,347,348,532,545,546],"levelBreakdowns":[{"jlptLevelId":1,"jlptLevelName":"N5","correctCount":9,"totalCount":30,"scorePercent":30.0}],"sections":[{"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":4,"totalCount":10,"score":40.0,"scorePercent":40.0},{"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":3,"totalCount":10,"score":30.0,"scorePercent":30.0},{"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":1,"totalCount":6,"score":16.67,"scorePercent":16.67},{"mockTestSectionId":60,"sectionTitle":"Phần 3: Nghe hiểu N5","languageSkillName":"Listening","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":true,"correctCount":0,"totalCount":1,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":63,"sectionTitle":"Nghe hiểu","languageSkillName":"Listening","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":true,"correctCount":1,"totalCount":3,"score":33.33,"scorePercent":33.33}]},"purpose":"CourseBaseline","cohortId":"__COHORT_ID__","enrollmentId":"__ENROLLMENT_ID__"}$json$, '"__COHORT_ID__"', v_cohort::text), '"__ENROLLMENT_ID__"', v_course::text), + '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_attempt; + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 299, 1194, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 300, 1200, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 301, 1201, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 302, 1207, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 303, 1209, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 304, 1213, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 305, 1217, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 306, 1221, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 307, 1226, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 308, 1229, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 319, 1274, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 320, 1277, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 321, 1283, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 322, 1285, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 323, 1289, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 324, 1293, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 325, 1297, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 326, 1302, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 327, 1306, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 328, 1309, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 343, 1370, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 344, 1373, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 345, 1378, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 346, 1381, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 347, 1385, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 348, 1389, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 544, 2174, true, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 545, 2178, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 546, 2181, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 532, 2125, false, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 36, 4, 10, 40.0, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 37, 3, 10, 30.0, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 38, 1, 6, 16.67, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 60, 0, 1, 0.0, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 63, 1, 3, 33.33, '2026-10-01 13:24:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + -- 7. End-of-course assessment (2026-10-19, after the class completed), different questions: 21/30 = 70%. + INSERT INTO "MockTestAttempts" ("UserId","AttemptKind","StartedAt","ExpiresAt","SubmittedAt","IsCompleted","TotalScore","IsPlacementAssessment","QuestionSnapshotJson","CreatedDate","IsDeleted","CreatedBy") + VALUES (900009, 2, '2026-10-19 13:00:00'::timestamp, '2026-10-19 13:30:00'::timestamp, '2026-10-19 13:27:00'::timestamp, true, 70.0, false, + replace(replace($json${"schemaVersion":2,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"timeLimitMinutes":30,"startedAt":"2026-10-19T13:00:00Z","expiresAt":"2026-10-19T13:30:00Z","isSupersededExpired":false,"isReplaced":false,"catalogLevels":[{"jlptLevelId":1,"jlptLevelName":"N5","rank":1}],"questions":[{"questionId":309,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":1,"content":"「駅」の読み方はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1233,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1233,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1233,"content":"えき","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1234,"content":"いき","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1235,"content":"えぎ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1236,"content":"せき","order":4,"isCorrect":false}]},{"questionId":310,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":2,"content":"「切手」の読み方はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1239,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1239,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1237,"content":"きて","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1238,"content":"きっぷ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1239,"content":"きって","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1240,"content":"きりて","order":4,"isCorrect":false}]},{"questionId":311,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":3,"content":"えんぴつを 三( )買いました。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1242,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1242,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1241,"content":"枚","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1242,"content":"本","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1243,"content":"冊","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1244,"content":"台","order":4,"isCorrect":false}]},{"questionId":312,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":4,"content":"駅まで バスに( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1248,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1248,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1245,"content":"入れます","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1246,"content":"置きます","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1247,"content":"洗います","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1248,"content":"乗ります","order":4,"isCorrect":true}]},{"questionId":313,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":5,"content":"「安い」の反対はどれですか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1251,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1251,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1249,"content":"白い","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1250,"content":"多い","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1251,"content":"高い","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1252,"content":"弱い","order":4,"isCorrect":false}]},{"questionId":314,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":6,"content":"【文字・語彙 1|漢字読み】\n【私】は学生です。\n【 】のことばはどう読みますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1254,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1254,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1253,"content":"わたち","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1254,"content":"わたし","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1255,"content":"せんせい","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1256,"content":"わだし","order":4,"isCorrect":false}]},{"questionId":315,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":7,"content":"【文字・語彙 1|漢字読み】\n毎朝、【学校】へ行きます。\n【 】のことばはどう読みますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1260,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1260,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1257,"content":"がっこ","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1258,"content":"がっごう","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1259,"content":"かっこう","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1260,"content":"がっこう","order":4,"isCorrect":true}]},{"questionId":316,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":8,"content":"【文字・語彙 1|漢字読み】\n図書館で【本】を借りました。\n【 】のことばはどう読みますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1264,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1264,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1261,"content":"ゆうびんきょく","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1262,"content":"ほ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1263,"content":"びょういん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1264,"content":"ほん","order":4,"isCorrect":true}]},{"questionId":317,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":9,"content":"【文字・語彙 1|漢字読み】\n田中【先生】はとても親切です。\n【 】のことばはどう読みますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1265,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1266,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1265,"content":"せんせい","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1266,"content":"せせい","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1267,"content":"びょういん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1268,"content":"たべる","order":4,"isCorrect":false}]},{"questionId":318,"mockTestId":18,"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","sectionOrder":1,"languageSkillName":"Vocabulary","jlptLevelId":1,"jlptLevelName":"N5","order":10,"content":"【文字・語彙 1|漢字読み】\n週末、【友達】と映画を見ました。\n【 】のことばはどう読みますか。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1271,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1269,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1269,"content":"ともたち","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1270,"content":"どもだち","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1271,"content":"ともだち","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1272,"content":"ともだし","order":4,"isCorrect":false}]},{"questionId":329,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":11,"content":"朝ごはんを 食べて( )、うちを 出ます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1316,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1316,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1313,"content":"まで","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1314,"content":"だけ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1315,"content":"より","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1316,"content":"から","order":4,"isCorrect":true}]},{"questionId":330,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":12,"content":"この 店は 安くて( )。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1317,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1317,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1317,"content":"便利です","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1318,"content":"便利なです","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1319,"content":"便利をです","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1320,"content":"便利にです","order":4,"isCorrect":false}]},{"questionId":331,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":13,"content":"【文法 1|文法形式の判断】\nわたしは 昨日、友だち( )映画を 見ました。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1323,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1323,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1321,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1322,"content":"で","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1323,"content":"と","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1324,"content":"が","order":4,"isCorrect":false}]},{"questionId":332,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":14,"content":"【文法 1|文法形式の判断】\n日曜日は どこ( )行きませんでした。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1325,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1325,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1325,"content":"へも","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1326,"content":"までに","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1327,"content":"から","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1328,"content":"と","order":4,"isCorrect":false}]},{"questionId":333,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":15,"content":"【文法 1|文法形式の判断】\nA「いつ 来ましたか。」 B「二週間( )来ました。」","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1332,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1332,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1329,"content":"あとで","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1330,"content":"ごろ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1331,"content":"まで","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1332,"content":"前に","order":4,"isCorrect":true}]},{"questionId":334,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":16,"content":"【文法 1|文法形式の判断】\nA「その かばんは( )ですか。」 B「田中さんのです。」","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1334,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1334,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1333,"content":"どの","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1334,"content":"だれの","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1335,"content":"どんな","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1336,"content":"なんの","order":4,"isCorrect":false}]},{"questionId":335,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":17,"content":"【文法 1|文法形式の判断】\nこれは姉( )傘です。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1338,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1338,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1337,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1338,"content":"の","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1339,"content":"へ","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1340,"content":"が","order":4,"isCorrect":false}]},{"questionId":336,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":18,"content":"【文法 1|文法形式の判断】\n箱の中( )鍵があります。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1341,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1342,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1341,"content":"に","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1342,"content":"を","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1343,"content":"と","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1344,"content":"で","order":4,"isCorrect":false}]},{"questionId":337,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":19,"content":"【文法 1|文法形式の判断】\n食堂( )昼ご飯を食べます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1346,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1345,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1345,"content":"を","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1346,"content":"で","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1347,"content":"が","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1348,"content":"の","order":4,"isCorrect":false}]},{"questionId":338,"mockTestId":19,"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","sectionOrder":1,"languageSkillName":"Grammar","jlptLevelId":1,"jlptLevelName":"N5","order":20,"content":"【文法 1|文法形式の判断】\n毎日牛乳( )飲みます。","audioUrl":null,"imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":1350,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1349,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1349,"content":"で","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1350,"content":"を","order":2,"isCorrect":true},{"imageUrl":null,"optionId":1351,"content":"の","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1352,"content":"へ","order":4,"isCorrect":false}]},{"questionId":340,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":21,"content":"あきさんは いつ パン屋へ 行きますか。","audioUrl":null,"imageUrl":null,"passageId":2,"passageTitle":"【読解】","passageText":"あきさんは 日曜日の 朝、九時に パン屋へ 行きます。パンを 二つ 買ってから、家で 朝ごはんを 食べます。午後は 友だちと 公園で 会います。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1360,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1360,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1357,"content":"日曜日の午後","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1358,"content":"土曜日の朝","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1359,"content":"土曜日の午後","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1360,"content":"日曜日の朝","order":4,"isCorrect":true}]},{"questionId":341,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":22,"content":"パンを いくつ 買いますか。","audioUrl":null,"imageUrl":null,"passageId":2,"passageTitle":"【読解】","passageText":"あきさんは 日曜日の 朝、九時に パン屋へ 行きます。パンを 二つ 買ってから、家で 朝ごはんを 食べます。午後は 友だちと 公園で 会います。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1363,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1363,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1361,"content":"一つ","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1362,"content":"三つ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1363,"content":"二つ","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1364,"content":"四つ","order":4,"isCorrect":false}]},{"questionId":342,"mockTestId":20,"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","sectionOrder":1,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":23,"content":"午後、どこで 友だちと 会いますか。","audioUrl":null,"imageUrl":null,"passageId":2,"passageTitle":"【読解】","passageText":"あきさんは 日曜日の 朝、九時に パン屋へ 行きます。パンを 二つ 買ってから、家で 朝ごはんを 食べます。午後は 友だちと 公園で 会います。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1365,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1365,"isCorrect":true,"options":[{"imageUrl":null,"optionId":1365,"content":"公園","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1366,"content":"家","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1367,"content":"パン屋","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1368,"content":"駅","order":4,"isCorrect":false}]},{"questionId":360,"mockTestId":21,"mockTestSectionId":41,"sectionTitle":"Đọc hiểu tổng hợp","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":24,"content":"あきさんは いつ パン屋へ 行きますか。","audioUrl":null,"imageUrl":null,"passageId":2,"passageTitle":"【読解】","passageText":"あきさんは 日曜日の 朝、九時に パン屋へ 行きます。パンを 二つ 買ってから、家で 朝ごはんを 食べます。午後は 友だちと 公園で 会います。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1440,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1437,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1437,"content":"日曜日の午後","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1438,"content":"土曜日の朝","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1439,"content":"土曜日の午後","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1440,"content":"日曜日の朝","order":4,"isCorrect":true}]},{"questionId":361,"mockTestId":21,"mockTestSectionId":41,"sectionTitle":"Đọc hiểu tổng hợp","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":25,"content":"パンを いくつ 買いますか。","audioUrl":null,"imageUrl":null,"passageId":2,"passageTitle":"【読解】","passageText":"あきさんは 日曜日の 朝、九時に パン屋へ 行きます。パンを 二つ 買ってから、家で 朝ごはんを 食べます。午後は 友だちと 公園で 会います。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1443,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1441,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1441,"content":"一つ","order":1,"isCorrect":false},{"imageUrl":null,"optionId":1442,"content":"三つ","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1443,"content":"二つ","order":3,"isCorrect":true},{"imageUrl":null,"optionId":1444,"content":"四つ","order":4,"isCorrect":false}]},{"questionId":362,"mockTestId":21,"mockTestSectionId":41,"sectionTitle":"Đọc hiểu tổng hợp","sectionOrder":3,"languageSkillName":"Reading","jlptLevelId":1,"jlptLevelName":"N5","order":26,"content":"午後、どこで 友だちと 会いますか。","audioUrl":null,"imageUrl":null,"passageId":2,"passageTitle":"【読解】","passageText":"あきさんは 日曜日の 朝、九時に パン屋へ 行きます。パンを 二つ 買ってから、家で 朝ごはんを 食べます。午後は 友だちと 公園で 会います。","passageInstructions":null,"passageImageUrl":null,"correctOptionId":1445,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":1446,"isCorrect":false,"options":[{"imageUrl":null,"optionId":1445,"content":"公園","order":1,"isCorrect":true},{"imageUrl":null,"optionId":1446,"content":"家","order":2,"isCorrect":false},{"imageUrl":null,"optionId":1447,"content":"パン屋","order":3,"isCorrect":false},{"imageUrl":null,"optionId":1448,"content":"駅","order":4,"isCorrect":false}]},{"questionId":557,"mockTestId":36,"mockTestSectionId":66,"sectionTitle":"Nghe hiểu","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":27,"content":"おとこの人は これから どこへ いきますか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2225,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2225,"isCorrect":true,"options":[{"imageUrl":null,"optionId":2225,"content":"ゆうびんきょく","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2226,"content":"ぎんこう","order":2,"isCorrect":false},{"imageUrl":null,"optionId":2227,"content":"びょういん","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2228,"content":"えき","order":4,"isCorrect":false}]},{"questionId":558,"mockTestId":36,"mockTestSectionId":66,"sectionTitle":"Nghe hiểu","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":28,"content":"パーティーは 何ようびですか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2230,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2230,"isCorrect":true,"options":[{"imageUrl":null,"optionId":2229,"content":"きんようび","order":1,"isCorrect":false},{"imageUrl":null,"optionId":2230,"content":"どようび","order":2,"isCorrect":true},{"imageUrl":null,"optionId":2231,"content":"にちようび","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2232,"content":"もくようび","order":4,"isCorrect":false}]},{"questionId":559,"mockTestId":36,"mockTestSectionId":66,"sectionTitle":"Nghe hiểu","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":29,"content":"クラスに 学生が ぜんぶで 何人 いますか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2235,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2235,"isCorrect":true,"options":[{"imageUrl":null,"optionId":2233,"content":"12人","order":1,"isCorrect":false},{"imageUrl":null,"optionId":2234,"content":"15人","order":2,"isCorrect":false},{"imageUrl":null,"optionId":2235,"content":"18人","order":3,"isCorrect":true},{"imageUrl":null,"optionId":2236,"content":"20人","order":4,"isCorrect":false}]},{"questionId":533,"mockTestId":34,"mockTestSectionId":60,"sectionTitle":"Phần 3: Nghe hiểu N5","sectionOrder":3,"languageSkillName":"Listening","jlptLevelId":1,"jlptLevelName":"N5","order":30,"content":"おんなの人は スーパーで 何を 買いますか。","audioUrl":"/api/FileStorage/local/jlpt-listening/a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4.mp3","imageUrl":null,"passageId":null,"passageTitle":null,"passageText":null,"passageInstructions":null,"passageImageUrl":null,"correctOptionId":2129,"orderingTokens":null,"orderingAnswerKey":null,"orderingResponse":null,"selectedOptionId":2130,"isCorrect":false,"options":[{"imageUrl":null,"optionId":2129,"content":"ぎゅうにゅうと パン","order":1,"isCorrect":true},{"imageUrl":null,"optionId":2130,"content":"たまごと パン","order":2,"isCorrect":false},{"imageUrl":null,"optionId":2131,"content":"ぎゅうにゅうと りんご","order":3,"isCorrect":false},{"imageUrl":null,"optionId":2132,"content":"おちゃと パン","order":4,"isCorrect":false}]}],"completedResult":{"attemptId":0,"attemptType":"courseFinal","status":"completed","startedAt":"2026-10-19T13:00:00Z","durationSeconds":1620,"submittedAt":"2026-10-19T13:27:00Z","assessmentTargetLevelId":1,"parentAssessmentAttemptId":null,"isComprehensiveAssessment":false,"isShortenedAssessment":false,"totalScore":70.0,"correctCount":21,"notStudiedCount":0,"totalQuestions":30,"assessedJlptLevelId":1,"assessedJlptLevelName":"N5","recommendedTargetJlptLevelId":1,"recommendedTargetJlptLevelName":"N5","wrongQuestionIds":[317,318,336,337,338,360,361,362,533],"levelBreakdowns":[{"jlptLevelId":1,"jlptLevelName":"N5","correctCount":21,"totalCount":30,"scorePercent":70.0}],"sections":[{"mockTestSectionId":36,"sectionTitle":"Từ vựng & Chữ Hán","languageSkillName":"Vocabulary","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":8,"totalCount":10,"score":80.0,"scorePercent":80.0},{"mockTestSectionId":37,"sectionTitle":"Ngữ pháp","languageSkillName":"Grammar","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":7,"totalCount":10,"score":70.0,"scorePercent":70.0},{"mockTestSectionId":38,"sectionTitle":"Đọc hiểu","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":3,"totalCount":3,"score":100.0,"scorePercent":100.0},{"mockTestSectionId":41,"sectionTitle":"Đọc hiểu tổng hợp","languageSkillName":"Reading","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":false,"correctCount":0,"totalCount":3,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":60,"sectionTitle":"Phần 3: Nghe hiểu N5","languageSkillName":"Listening","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":true,"correctCount":0,"totalCount":1,"score":0.0,"scorePercent":0.0},{"mockTestSectionId":66,"sectionTitle":"Nghe hiểu","languageSkillName":"Listening","languageSkillCode":null,"jlptLevelId":1,"jlptLevelName":"N5","hasAudioEvidence":true,"correctCount":3,"totalCount":3,"score":100.0,"scorePercent":100.0}]},"purpose":"CourseFinal","cohortId":"__COHORT_ID__","enrollmentId":"__ENROLLMENT_ID__"}$json$, '"__COHORT_ID__"', v_cohort::text), '"__ENROLLMENT_ID__"', v_course::text), + '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid) RETURNING "Id" INTO v_attempt; + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 309, 1233, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 310, 1239, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 311, 1242, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 312, 1248, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 313, 1251, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 314, 1254, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 315, 1260, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 316, 1264, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 317, 1266, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 318, 1269, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 329, 1316, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 330, 1317, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 331, 1323, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 332, 1325, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 333, 1332, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 334, 1334, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 335, 1338, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 336, 1342, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 337, 1345, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 338, 1349, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 340, 1360, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 341, 1363, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 342, 1365, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 360, 1437, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 361, 1441, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 362, 1446, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 557, 2225, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 558, 2230, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 559, 2235, true, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestAnswers" ("PracticeTestAttemptId","PracticeQuestionId","SelectedOptionId","IsCorrect","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 533, 2130, false, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 36, 8, 10, 80.0, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 37, 7, 10, 70.0, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 38, 3, 3, 100.0, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 41, 0, 3, 0.0, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 60, 0, 1, 0.0, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + INSERT INTO "MockTestSectionResults" ("MockTestAttemptId","MockTestSectionId","CorrectCount","TotalCount","ScorePercent","CreatedDate","IsDeleted","CreatedBy") VALUES (v_attempt, 66, 3, 3, 100.0, '2026-10-19 13:27:00'::timestamp, false, '5e5d0005-de30-4000-8000-000000000005'::uuid); + + RAISE NOTICE 'Stage 5 demo seeded: cohort %, enrollment %', v_cohort, v_course; +END +$seed$; From 81ddcd17b2b7fca2cde35425c1196fed7515e306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Xu=C3=A2n=20Minh?= Date: Wed, 2 Dec 2026 21:25:49 +0700 Subject: [PATCH 2/2] feat(backend): add unified content author search, dedup approval linking, and standardize authoring services --- .../ContentAuthoring/CanonicalContentDtos.cs | 9 + .../DTOs/SrsTemplates/SrsTemplateDtos.cs | 2 + .../IServices/IContentModerationV2Service.cs | 3 + .../ICurriculumPackageImportService.cs | 19 - .../IServices/IExamBuilderService.cs | 2 + .../IServices/ISharedBankSearchService.cs | 5 + .../IServices/IUnifiedImportService.cs | 4 +- .../Requests/Content/BulkReviewRequest.cs | 1 + .../Requests/Content/ConfirmImportRequest.cs | 1 + .../Requests/Content/ReviewContentRequest.cs | 1 + .../ContentAuthoringRequest.cs | 6 + .../ContentAuthoring/ContentPlanRequest.cs | 1 + .../Requests/SharedBanks/SearchFilters.cs | 4 + .../ContentApprovalListItemResponse.cs | 4 +- .../Content/CurriculumPackageDtos.cs | 162 -- .../Content/UnifiedAuthorContentDtos.cs | 76 + .../SharedBanks/BankCardResponses.cs | 18 + .../Services/ContentApprovalService.cs | 176 +- .../ContentModerationV2Service.cs | 104 +- .../ContentAuthoring/ExamBuilderService.cs | 132 +- .../ContentAuthoring/QuestionBankService.cs | 10 + .../ContentAuthoring/ReviewHistoryHelper.cs | 83 + .../ContentAuthoring/UnifiedImportService.cs | 36 +- .../Services/ContentAuthoringService.cs | 63 +- .../Services/ContentPlanningService.cs | 46 +- .../Services/ExcelContentImportService.cs | 12 +- .../Services/KanjiWritingPracticeService.cs | 8 +- .../Services/ListeningAudioFilePolicy.cs | 21 - .../Services/ManualContentService.cs | 733 +++++- .../Services/PracticeExerciseService.cs | 18 +- .../Services/SharedBankSearchService.cs | 91 + .../Services/SrsCardTemplateService.cs | 36 +- RikiPath.Domain/Enums/ImportEntityType.cs | 1 - RikiPath.Infrastructure/AppDbContext.cs | 98 - .../Repositories/LessonRepository.cs | 2 +- .../Services/AwsAudioFileStorageService.cs | 2 +- .../ContentAudioTranscriptionService.cs | 18 +- .../CurriculumPackageImportService.cs | 2122 ----------------- .../Controllers/ContentApprovalController.cs | 13 + .../Controllers/ContentImportController.cs | 83 +- .../ContentTemplatesAndExportController.cs | 3 +- .../Controllers/ExamBuilderController.cs | 7 + .../Controllers/FileStorageController.cs | 2 +- .../Controllers/ManualContentController.cs | 21 +- .../Controllers/SharedBankController.cs | 16 + RikiPath.WebApi/Services/ImportAudioFiles.cs | 12 +- 46 files changed, 1549 insertions(+), 2738 deletions(-) delete mode 100644 RikiPath.Application/IServices/ICurriculumPackageImportService.cs delete mode 100644 RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs create mode 100644 RikiPath.Application/Responses/Content/UnifiedAuthorContentDtos.cs create mode 100644 RikiPath.Application/Services/ContentAuthoring/ReviewHistoryHelper.cs delete mode 100644 RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs diff --git a/RikiPath.Application/DTOs/ContentAuthoring/CanonicalContentDtos.cs b/RikiPath.Application/DTOs/ContentAuthoring/CanonicalContentDtos.cs index 2244b4a..a388122 100644 --- a/RikiPath.Application/DTOs/ContentAuthoring/CanonicalContentDtos.cs +++ b/RikiPath.Application/DTOs/ContentAuthoring/CanonicalContentDtos.cs @@ -113,6 +113,11 @@ public sealed class CanonicalPassageDto { public int? Id { get; set; } public int? MockTestSectionId { get; set; } + public int? MockTestId { get; set; } + public string? MockTestTitle { get; set; } + public string? MockTestExamKind { get; set; } + public string? SectionTitle { get; set; } + public int QuestionCount { get; set; } public Guid? PassageIdentity { get; set; } public string PassageCode { get; set; } = string.Empty; public int CertificateLevelId { get; set; } @@ -142,6 +147,10 @@ public sealed class CanonicalQuestionDto { public int? Id { get; set; } public int? MockTestSectionId { get; set; } + public int? MockTestId { get; set; } + public string? MockTestTitle { get; set; } + public string? MockTestExamKind { get; set; } + public string? SectionTitle { get; set; } public Guid? QuestionIdentity { get; set; } public int Version { get; set; } = 1; public int? ParentQuestionId { get; set; } diff --git a/RikiPath.Application/DTOs/SrsTemplates/SrsTemplateDtos.cs b/RikiPath.Application/DTOs/SrsTemplates/SrsTemplateDtos.cs index e73e888..286e972 100644 --- a/RikiPath.Application/DTOs/SrsTemplates/SrsTemplateDtos.cs +++ b/RikiPath.Application/DTOs/SrsTemplates/SrsTemplateDtos.cs @@ -43,11 +43,13 @@ public sealed class SaveSrsCardTemplateRequest public int? VocabularyId { get; set; } public int? KanjiId { get; set; } public int? GrammarPatternId { get; set; } + public bool SubmitForReview { get; set; } } public sealed class ReviewSrsCardTemplateRequest { public bool Approve { get; set; } + public bool RequestChanges { get; set; } [MaxLength(1000)] public string? ReviewNote { get; set; } diff --git a/RikiPath.Application/IServices/IContentModerationV2Service.cs b/RikiPath.Application/IServices/IContentModerationV2Service.cs index cba00e6..7907720 100644 --- a/RikiPath.Application/IServices/IContentModerationV2Service.cs +++ b/RikiPath.Application/IServices/IContentModerationV2Service.cs @@ -72,4 +72,7 @@ Task> ModerateAsync( Task UnpublishAsync( UnpublishContentRequest request, int adminUserId, CancellationToken ct); + + Task RepublishAsync( + UnpublishContentRequest request, int adminUserId, string adminName, CancellationToken ct); } diff --git a/RikiPath.Application/IServices/ICurriculumPackageImportService.cs b/RikiPath.Application/IServices/ICurriculumPackageImportService.cs deleted file mode 100644 index 4beb0b1..0000000 --- a/RikiPath.Application/IServices/ICurriculumPackageImportService.cs +++ /dev/null @@ -1,19 +0,0 @@ -using RikiPath.Application.Responses; -using RikiPath.Application.Responses.Content; - -namespace RikiPath.Application.IServices -{ - public interface ICurriculumPackageImportService - { - Task> GetInventoryAsync(CancellationToken cancellationToken); - - Task> PreviewAsync( - CurriculumPackagePreviewRequest request, - CancellationToken cancellationToken); - - Task> ConfirmAsync( - CurriculumPackageConfirmRequest request, - int actorUserId, - CancellationToken cancellationToken); - } -} diff --git a/RikiPath.Application/IServices/IExamBuilderService.cs b/RikiPath.Application/IServices/IExamBuilderService.cs index e604624..a834f08 100644 --- a/RikiPath.Application/IServices/IExamBuilderService.cs +++ b/RikiPath.Application/IServices/IExamBuilderService.cs @@ -86,6 +86,8 @@ Task>> ListAuthorExamsAsync( Task> SaveDraftAsync(ExamBuilderDto request, int actorUserId, CancellationToken ct); + Task> SaveAndSubmitAsync(ExamBuilderDto request, int actorUserId, CancellationToken ct); + Task> CreateNewVersionAsync(int sourceExamId, int actorUserId, CancellationToken ct); Task> ValidateExamAsync(int examId, CancellationToken ct); diff --git a/RikiPath.Application/IServices/ISharedBankSearchService.cs b/RikiPath.Application/IServices/ISharedBankSearchService.cs index d49ba1f..90cbd44 100644 --- a/RikiPath.Application/IServices/ISharedBankSearchService.cs +++ b/RikiPath.Application/IServices/ISharedBankSearchService.cs @@ -26,5 +26,10 @@ Task>> SearchQuestionsAsync( QuestionBankSearchFilter filter, CancellationToken cancellationToken); Task> GetQuestionDetailAsync(int id, CancellationToken cancellationToken); + + Task>> SearchLessonsAsync( + LessonSearchFilter filter, CancellationToken cancellationToken); + + Task> GetLessonDetailAsync(int id, CancellationToken cancellationToken); } } diff --git a/RikiPath.Application/IServices/IUnifiedImportService.cs b/RikiPath.Application/IServices/IUnifiedImportService.cs index 3c44ec4..3bee513 100644 --- a/RikiPath.Application/IServices/IUnifiedImportService.cs +++ b/RikiPath.Application/IServices/IUnifiedImportService.cs @@ -95,6 +95,7 @@ public sealed class ConfirmUnifiedImportRequest public string SourceFileName { get; set; } = string.Empty; public string SourceFormat { get; set; } = "Excel"; // Excel | Json | Zip | Pdf public string? IdempotencyKey { get; set; } + public bool SubmitForReview { get; set; } public UnifiedImportExamPreviewDto? ExamBlueprint { get; set; } public List Rows { get; set; } = []; } @@ -137,5 +138,6 @@ Task> ConfirmFromArchiveAsync( UnifiedImportKind expectedKind, string? idempotencyKey, int actorUserId, - CancellationToken ct); + CancellationToken ct, + bool submitForReview = false); } diff --git a/RikiPath.Application/Requests/Content/BulkReviewRequest.cs b/RikiPath.Application/Requests/Content/BulkReviewRequest.cs index 01fd967..a42f5f2 100644 --- a/RikiPath.Application/Requests/Content/BulkReviewRequest.cs +++ b/RikiPath.Application/Requests/Content/BulkReviewRequest.cs @@ -9,6 +9,7 @@ public class BulkReviewItem { public int RequestId { get; set; } public bool Approve { get; set; } + public bool RequestChanges { get; set; } public string? ReviewNote { get; set; } // riêng cho request này } } diff --git a/RikiPath.Application/Requests/Content/ConfirmImportRequest.cs b/RikiPath.Application/Requests/Content/ConfirmImportRequest.cs index 1a42d1a..dc1b631 100644 --- a/RikiPath.Application/Requests/Content/ConfirmImportRequest.cs +++ b/RikiPath.Application/Requests/Content/ConfirmImportRequest.cs @@ -4,6 +4,7 @@ public class ConfirmImportRequest { public string? SourceFileName { get; set; } public Guid? BatchId { get; set; } + public bool SubmitForReview { get; set; } public List Rows { get; set; } = new(); } } diff --git a/RikiPath.Application/Requests/Content/ReviewContentRequest.cs b/RikiPath.Application/Requests/Content/ReviewContentRequest.cs index 02d4224..1b8b53b 100644 --- a/RikiPath.Application/Requests/Content/ReviewContentRequest.cs +++ b/RikiPath.Application/Requests/Content/ReviewContentRequest.cs @@ -3,6 +3,7 @@ namespace RikiPath.Application.Requests.Content public class ReviewContentRequest { public bool Approve { get; set; } + public bool RequestChanges { get; set; } public string? ReviewNote { get; set; } } } diff --git a/RikiPath.Application/Requests/ContentAuthoring/ContentAuthoringRequest.cs b/RikiPath.Application/Requests/ContentAuthoring/ContentAuthoringRequest.cs index 12934ed..026db3a 100644 --- a/RikiPath.Application/Requests/ContentAuthoring/ContentAuthoringRequest.cs +++ b/RikiPath.Application/Requests/ContentAuthoring/ContentAuthoringRequest.cs @@ -43,6 +43,7 @@ public class ConfirmKanjiSuggestionsRequest { public int? LessonId { get; set; } public int? CertificateLevelId { get; set; } + public bool SubmitForReview { get; set; } public List Items { get; set; } = new(); } @@ -71,6 +72,7 @@ public class ConfirmVocabularySuggestionsRequest { public int? LessonId { get; set; } public int? CertificateLevelId { get; set; } + public bool SubmitForReview { get; set; } public List Items { get; set; } = new(); } @@ -99,6 +101,7 @@ public class ConfirmGrammarSuggestionsRequest { public int? LessonId { get; set; } public int? CertificateLevelId { get; set; } + public bool SubmitForReview { get; set; } public List Items { get; set; } = new(); } @@ -122,6 +125,7 @@ public class ConfirmLessonSuggestionRequest public string Title { get; set; } = string.Empty; public string? Description { get; set; } public int SortOrder { get; set; } + public bool SubmitForReview { get; set; } public List KanjiIds { get; set; } = new(); public List VocabularyIds { get; set; } = new(); public List GrammarPatternIds { get; set; } = new(); @@ -144,6 +148,7 @@ public class ConfirmPracticeExerciseRequest public int LanguageSkillId { get; set; } public string Title { get; set; } = string.Empty; public string? Description { get; set; } + public bool SubmitForReview { get; set; } public List Questions { get; set; } = new(); } @@ -183,6 +188,7 @@ public class ConfirmMockTestRequest public int CertificateLevelId { get; set; } public string Title { get; set; } = string.Empty; public int TimeLimitMinutes { get; set; } + public bool SubmitForReview { get; set; } public List Sections { get; set; } = new(); } diff --git a/RikiPath.Application/Requests/ContentAuthoring/ContentPlanRequest.cs b/RikiPath.Application/Requests/ContentAuthoring/ContentPlanRequest.cs index 783fc45..b3a914b 100644 --- a/RikiPath.Application/Requests/ContentAuthoring/ContentPlanRequest.cs +++ b/RikiPath.Application/Requests/ContentAuthoring/ContentPlanRequest.cs @@ -67,6 +67,7 @@ public class ExecuteContentPlanRequest public class ConfirmContentPlanRequest { + public bool SubmitForReview { get; set; } public List KanjiGroups { get; set; } = new(); public List VocabularyGroups { get; set; } = new(); public List GrammarGroups { get; set; } = new(); diff --git a/RikiPath.Application/Requests/SharedBanks/SearchFilters.cs b/RikiPath.Application/Requests/SharedBanks/SearchFilters.cs index 8f2aca5..a86525f 100644 --- a/RikiPath.Application/Requests/SharedBanks/SearchFilters.cs +++ b/RikiPath.Application/Requests/SharedBanks/SearchFilters.cs @@ -22,6 +22,10 @@ public class GrammarSearchFilter : PagedFilterBase { } + public class LessonSearchFilter : PagedFilterBase + { + } + public class QuestionBankSearchFilter : PagedFilterBase { public string? QuestionType { get; set; } diff --git a/RikiPath.Application/Responses/Content/ContentApprovalListItemResponse.cs b/RikiPath.Application/Responses/Content/ContentApprovalListItemResponse.cs index d6c04fe..4ca222d 100644 --- a/RikiPath.Application/Responses/Content/ContentApprovalListItemResponse.cs +++ b/RikiPath.Application/Responses/Content/ContentApprovalListItemResponse.cs @@ -1,4 +1,5 @@ -using RikiPath.Domain.Enums; +using RikiPath.Application.DTOs.ContentAuthoring; +using RikiPath.Domain.Enums; namespace RikiPath.Application.Responses.Content { @@ -19,6 +20,7 @@ public class ContentApprovalListItemResponse public string? ReviewedByName { get; set; } public DateTime? ReviewedAt { get; set; } public string? ReviewNote { get; set; } + public List ReviewHistory { get; set; } = []; /// Số trường thay đổi theo bản tóm tắt lưu lúc import (null nếu không có). public int? ChangedFieldCount { get; set; } public int? CertificateLevelId { get; set; } diff --git a/RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs b/RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs deleted file mode 100644 index f7c38ec..0000000 --- a/RikiPath.Application/Responses/Content/CurriculumPackageDtos.cs +++ /dev/null @@ -1,162 +0,0 @@ -namespace RikiPath.Application.Responses.Content -{ - public sealed class CurriculumPackageArchiveInfo - { - public string FileName { get; set; } = string.Empty; - public string? LevelCode { get; set; } - public bool Exists { get; set; } - public long SizeBytes { get; set; } - public int EntryCount { get; set; } - public int UnsafeEntryCount { get; set; } - public string? Sha256Short { get; set; } - } - - public sealed class CurriculumPackageLevelSummary - { - public string LevelCode { get; set; } = string.Empty; - public int? CertificateLevelId { get; set; } - public int TopicCount { get; set; } - public int LessonCount { get; set; } - public int VocabularyCount { get; set; } - public int KanjiCount { get; set; } - public int GrammarCount { get; set; } - public int PracticeExerciseCount { get; set; } - public int MockTestCount { get; set; } - public int AudioCount { get; set; } - public int ImageCount { get; set; } - public int SrsTemplateCount { get; set; } - } - - public sealed class CurriculumPackageChapterInfo - { - public string LevelCode { get; set; } = string.Empty; - public string TopicCode { get; set; } = string.Empty; - public int OrderIndex { get; set; } - public string TitleVi { get; set; } = string.Empty; - public string? TitleJa { get; set; } - public string? Description { get; set; } - public int LessonCount { get; set; } - public int ExistingPublishedLessonCount { get; set; } - public int ExistingDraftCount { get; set; } - } - - public sealed class CurriculumPackageInventoryResponse - { - public bool PackageRootFound { get; set; } - public string? PackageRootDisplay { get; set; } - public int TotalGlobalSrsTemplates { get; set; } - public List Archives { get; set; } = []; - public List Levels { get; set; } = []; - public List Chapters { get; set; } = []; - public List Warnings { get; set; } = []; - } - - public sealed class CurriculumPackagePreviewRequest - { - public List? Levels { get; set; } - public List? TopicCodes { get; set; } - public List? MockTestIds { get; set; } - public bool IncludeLessons { get; set; } = true; - public bool IncludeVocabKanjiGrammar { get; set; } = true; - public bool IncludePracticeExercises { get; set; } = true; - public bool IncludeSrsTemplates { get; set; } = true; - public bool IncludeMockTests { get; set; } = true; - public bool UploadAssets { get; set; } = true; - public int Page { get; set; } = 1; - public int PageSize { get; set; } = 25; - } - - public sealed class CurriculumPackagePreviewItemResponse - { - public string ExternalId { get; set; } = string.Empty; - public string EntityType { get; set; } = string.Empty; - public string LevelCode { get; set; } = string.Empty; - public string? TopicCode { get; set; } - public string RowKey { get; set; } = string.Empty; - public string Title { get; set; } = string.Empty; - public string Action { get; set; } = "New"; - public string Status { get; set; } = "Draft"; - public bool PublishedReady { get; set; } - public string? AudioAsset { get; set; } - public string? ImageAsset { get; set; } - public int ChildCount { get; set; } - public List Warnings { get; set; } = []; - public List Errors { get; set; } = []; - } - - public sealed class CurriculumPackageIssueResponse - { - public string Severity { get; set; } = "Warning"; - public string Code { get; set; } = string.Empty; - public string Target { get; set; } = string.Empty; - public string Message { get; set; } = string.Empty; - } - - public sealed class CurriculumPackagePreviewResponse - { - public List SelectedLevels { get; set; } = []; - public List SelectedTopicCodes { get; set; } = []; - public int TotalItems { get; set; } - public int NewCount { get; set; } - public int ExistingCount { get; set; } - public int ModifiedCount { get; set; } - public int WarningCount { get; set; } - public int ErrorCount { get; set; } - public int AudioAssetCount { get; set; } - public int ImageAssetCount { get; set; } - public bool CanConfirm { get; set; } - public Dictionary ByEntityType { get; set; } = new(StringComparer.OrdinalIgnoreCase); - public List DependencyOrder { get; set; } = []; - public List Issues { get; set; } = []; - public int Page { get; set; } = 1; - public int PageSize { get; set; } = 25; - public int TotalPages { get; set; } = 1; - public List Items { get; set; } = []; - } - - public sealed class CurriculumPackageConfirmRequest - { - public List? Levels { get; set; } - public List? TopicCodes { get; set; } - public List? MockTestIds { get; set; } - public bool IncludeLessons { get; set; } = true; - public bool IncludeVocabKanjiGrammar { get; set; } = true; - public bool IncludePracticeExercises { get; set; } = true; - public bool IncludeSrsTemplates { get; set; } = true; - public bool IncludeMockTests { get; set; } = true; - public bool UploadAssets { get; set; } = true; - public string? IdempotencyKey { get; set; } - } - - public sealed class CurriculumPackageConfirmResponse - { - public Guid BatchId { get; set; } - public string Status { get; set; } = "Draft"; - public bool PublishedReady { get; set; } - public string RightsStatus { get; set; } = "Pending"; - public int DraftsCreatedCount { get; set; } - public int SkippedExistingCount { get; set; } - public int UploadedAudioCount { get; set; } - public int UploadedImageCount { get; set; } - public Dictionary ByEntityType { get; set; } = new(StringComparer.OrdinalIgnoreCase); - public List CreatedRequestIds { get; set; } = []; - public List Warnings { get; set; } = []; - } - - public sealed class SrsCardTemplateImportPayloadResponse - { - public string CardType { get; set; } = "Vocabulary"; - public string FrontText { get; set; } = string.Empty; - public string BackText { get; set; } = string.Empty; - public string? Reading { get; set; } - public string? Meaning { get; set; } - public string? ExampleSentence { get; set; } - public string? ExampleMeaning { get; set; } - public string? UsageNotes { get; set; } - public string? AudioUrl { get; set; } - public int CertificateLevelId { get; set; } - public string CertificateLevelCode { get; set; } = string.Empty; - public string NormalizedContentKey { get; set; } = string.Empty; - public string? ExternalStableId { get; set; } - } -} diff --git a/RikiPath.Application/Responses/Content/UnifiedAuthorContentDtos.cs b/RikiPath.Application/Responses/Content/UnifiedAuthorContentDtos.cs new file mode 100644 index 0000000..e00139b --- /dev/null +++ b/RikiPath.Application/Responses/Content/UnifiedAuthorContentDtos.cs @@ -0,0 +1,76 @@ +namespace RikiPath.Application.Responses.Content; + +public sealed class UnifiedAuthorContentSearchRequest +{ + public string? Keyword { get; set; } + public int? JlptLevelId { get; set; } + public int? SkillId { get; set; } + public string? Status { get; set; } + public string? Scope { get; set; } + public string? SortBy { get; set; } + public int Page { get; set; } = 1; + public int PageSize { get; set; } = 20; +} + +public sealed class UnifiedAuthorContentItem +{ + public string CanonicalId { get; set; } = string.Empty; + public string SourceKind { get; set; } = string.Empty; + public int? EntityId { get; set; } + public int? ApprovalRequestId { get; set; } + public string Status { get; set; } = string.Empty; + public bool IsMine { get; set; } + public bool HasPendingProposal { get; set; } + public int? PendingProposalId { get; set; } + public string? PendingProposalStatus { get; set; } + public string? ReviewNote { get; set; } + public string? ReviewedByName { get; set; } + public DateTime? ReviewedAt { get; set; } + public bool HasReviewFeedback { get; set; } + public DateTime? UpdatedAt { get; set; } + + public int? CertificateLevelId { get; set; } + public string? JlptLevelName { get; set; } + + // Vocabulary + public string? Word { get; set; } + public string? Reading { get; set; } + public string? Meaning { get; set; } + public string? ExampleSentence { get; set; } + public string? ExampleSentenceMeaning { get; set; } + public string? AudioUrl { get; set; } + + // Kanji + public string? Character { get; set; } + public string? SinoVietnamese { get; set; } + public string? OnYomi { get; set; } + public string? KunYomi { get; set; } + public int? StrokeCount { get; set; } + public string? StrokeOrderUrl { get; set; } + + // Grammar & Lesson shared + public string? Title { get; set; } + public string? Structure { get; set; } + public string? Explanation { get; set; } + public string? Description { get; set; } + + // Lesson + public int? LanguageSkillId { get; set; } + public string? SkillName { get; set; } + public string? TopicTitle { get; set; } + public int? SortOrder { get; set; } + public int? EstimatedMinutes { get; set; } + public int? VocabularyCount { get; set; } + public int? KanjiCount { get; set; } + public int? GrammarCount { get; set; } +} + +public sealed class UnifiedAuthorContentSearchResponse +{ + public int Page { get; set; } + public int PageSize { get; set; } + public int TotalCount { get; set; } + public int UnfilteredTotalCount { get; set; } + public bool HasLegacyDrafts { get; set; } + public IReadOnlyList Items { get; set; } = []; +} diff --git a/RikiPath.Application/Responses/SharedBanks/BankCardResponses.cs b/RikiPath.Application/Responses/SharedBanks/BankCardResponses.cs index 764f6fc..acb97b2 100644 --- a/RikiPath.Application/Responses/SharedBanks/BankCardResponses.cs +++ b/RikiPath.Application/Responses/SharedBanks/BankCardResponses.cs @@ -73,4 +73,22 @@ public class QuestionBankCardResponse public string? SourceType { get; set; } public IReadOnlyList Options { get; set; } = []; } + + public class LessonCardResponse + { + public int Id { get; set; } + public string Title { get; set; } = string.Empty; + public string? Description { get; set; } + public int SortOrder { get; set; } + public int EstimatedMinutes { get; set; } + public int CertificateLevelId { get; set; } + public string JlptLevelName { get; set; } = string.Empty; + public int LanguageSkillId { get; set; } + public string SkillName { get; set; } = string.Empty; + public string? TopicTitle { get; set; } + public string? LearningObjectives { get; set; } + public int VocabularyCount { get; set; } + public int KanjiCount { get; set; } + public int GrammarCount { get; set; } + } } diff --git a/RikiPath.Application/Services/ContentApprovalService.cs b/RikiPath.Application/Services/ContentApprovalService.cs index 7492a3e..8432210 100644 --- a/RikiPath.Application/Services/ContentApprovalService.cs +++ b/RikiPath.Application/Services/ContentApprovalService.cs @@ -457,7 +457,7 @@ await unitOfWork.ExecuteInTransactionAsync(async token => } req.ReviewedByName = reviewerName; - await ApplyReviewAsync(req, request.Approve, request.ReviewNote, token); + await ApplyReviewAsync(req, request.Approve, request.ReviewNote, token, request.RequestChanges, actor.Id); if (unitOfWork.AdminAuditLogs is not null) { @@ -466,7 +466,7 @@ await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog ActorUserId = actor.Id, EntityType = "ContentApprovalRequest", EntityId = req.Id, - Action = request.Approve ? "Approved" : "Rejected", + Action = request.Approve ? "Approved" : (request.RequestChanges ? "ChangesRequested" : "Rejected"), AfterJson = JsonSerializer.Serialize(new { req.Id, EntityType = req.EntityType.ToString(), req.RowKey, Status = req.Status.ToString() }), Reason = request.ReviewNote?.Trim(), CreatedAtUtc = DateTime.UtcNow, @@ -579,7 +579,7 @@ await unitOfWork.ExecuteInTransactionAsync(async token => if (request.Approve) { lessonRequest.ReviewedByName = reviewerName; - await ApplyReviewAsync(lessonRequest, true, request.ReviewNote, token); + await ApplyReviewAsync(lessonRequest, true, request.ReviewNote, token, false, actor.Id); await unitOfWork.SaveChangesAsync(token); } else @@ -587,7 +587,7 @@ await unitOfWork.ExecuteInTransactionAsync(async token => foreach (var item in group) { item.ReviewedByName = reviewerName; - await ApplyReviewAsync(item, false, request.ReviewNote, token); + await ApplyReviewAsync(item, false, request.ReviewNote, token, request.RequestChanges, actor.Id); } } @@ -598,7 +598,7 @@ await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog ActorUserId = actor.Id, EntityType = "ContentApprovalLessonGroup", EntityId = lessonRequest.Id, - Action = request.Approve ? "Approved" : "Rejected", + Action = request.Approve ? "Approved" : (request.RequestChanges ? "ChangesRequested" : "Rejected"), AfterJson = JsonSerializer.Serialize(new { LessonRequestId = lessonRequest.Id, Count = group.Count }), Reason = request.ReviewNote?.Trim(), CreatedAtUtc = DateTime.UtcNow, @@ -606,7 +606,8 @@ await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog } var completedStatus = request.Approve - ? ContentApprovalStatus.Approved : ContentApprovalStatus.Rejected; + ? ContentApprovalStatus.Approved + : (request.RequestChanges ? ContentApprovalStatus.ChangesRequested : ContentApprovalStatus.Rejected); if (group.Any(item => item.Status != completedStatus)) throw new InvalidOperationException("Một số nội dung trong lô chưa được xử lý. Vui lòng tải lại."); result.SuccessCount = group.Count; @@ -723,7 +724,7 @@ await unitOfWork.ExecuteInTransactionAsync(async token => } approval.ReviewedByName = reviewerName; - await ApplyReviewAsync(approval, item.Approve, item.ReviewNote, token); + await ApplyReviewAsync(approval, item.Approve, item.ReviewNote, token, item.RequestChanges, actor.Id); cascaded = relatedCandidates .Where(row => row.Status == ContentApprovalStatus.Approved) .ToList(); @@ -870,6 +871,7 @@ public async Task>> GetMyAppro ReviewedByName = request.ReviewedByName, ReviewedAt = request.ReviewedAt, ReviewNote = request.ReviewNote, + ReviewHistory = ReviewHistoryHelper.Parse(request.ReviewHistoryJson), CertificateLevelId = levelId, CertificateLevelCode = levelCode, }; @@ -881,7 +883,7 @@ private async Task NotifyAuthorsAsync(IEnumerable review foreach (var group in reviewed.Where(request => request.SubmittedByUserId > 0).GroupBy(request => request.SubmittedByUserId)) { var rejected = group - .Where(request => request.Status == ContentApprovalStatus.Rejected) + .Where(request => request.Status is (ContentApprovalStatus.Rejected or ContentApprovalStatus.ChangesRequested)) .Select(request => (request.RowKey, request.ReviewNote ?? "Không có ghi chú")) .ToList(); await notifier.NotifyAuthorOnReviewResultAsync(group.Key, group.Count(), rejected, cancellationToken); @@ -909,13 +911,30 @@ private static bool IsReviewable(ContentApprovalStatus status) => status == ContentApprovalStatus.PendingReview; private async Task ApplyReviewAsync( - ContentApprovalRequest req, bool approve, string? reviewNote, CancellationToken cancellationToken) + ContentApprovalRequest req, + bool approve, + string? reviewNote, + CancellationToken cancellationToken, + bool requestChanges = false, + int reviewerUserId = 0) { + var priorStatus = req.Status; if (!approve) { - req.Status = ContentApprovalStatus.Rejected; + var nextStatus = requestChanges ? ContentApprovalStatus.ChangesRequested : ContentApprovalStatus.Rejected; + var now = DateTime.UtcNow; + req.Status = nextStatus; req.ReviewNote = reviewNote; - req.ReviewedAt = DateTime.UtcNow; + req.ReviewedAt = now; + ReviewHistoryHelper.Append( + req, + requestChanges ? "ChangesRequested" : "Rejected", + priorStatus, + nextStatus, + reviewerUserId, + req.ReviewedByName ?? "Admin", + now, + reviewNote); await SyncContentBankAsync(req, cancellationToken); return; } @@ -927,7 +946,7 @@ private async Task ApplyReviewAsync( var lesson = ReadLessonPayload(req); if (lesson.TopicId.HasValue || lesson.TopicTitle is not null) { - await ApplyLessonTopicApprovalAsync(req, reviewNote, cancellationToken); + await ApplyLessonTopicApprovalAsync(req, reviewNote, cancellationToken, reviewerUserId); await SyncContentBankAsync(req, cancellationToken); return; } @@ -949,14 +968,11 @@ private async Task ApplyReviewAsync( case ImportEntityType.PracticeSet: await ApplyMockTestApprovalAsync(req, cancellationToken); break; - case ImportEntityType.SrsCardTemplate: - await ApplySrsCardTemplateApprovalAsync(req, cancellationToken); - break; default: throw new NotSupportedException($"Chưa hỗ trợ phê duyệt tự động cho loại {req.EntityType}."); } - MarkApproved(req, reviewNote); + MarkApproved(req, reviewNote, reviewerUserId); await SyncContentBankAsync(req, cancellationToken); } @@ -985,11 +1001,22 @@ private async Task SyncContentBankAsync(ContentApprovalRequest request, Cancella entry.LatestBatchId = request.BatchId; } - private static void MarkApproved(ContentApprovalRequest request, string? reviewNote) + private static void MarkApproved(ContentApprovalRequest request, string? reviewNote, int reviewerUserId = 0) { + var priorStatus = request.Status; + var now = DateTime.UtcNow; request.Status = ContentApprovalStatus.Approved; request.ReviewNote = reviewNote; - request.ReviewedAt = DateTime.UtcNow; + request.ReviewedAt = now; + ReviewHistoryHelper.Append( + request, + "Approved", + priorStatus, + ContentApprovalStatus.Approved, + reviewerUserId, + request.ReviewedByName ?? "Admin", + now, + reviewNote); } #region Helper Methods Thực thi lưu Entity + ContentLevelMapping @@ -1027,6 +1054,10 @@ private async Task ApplyVocabularyApprovalAsync(ContentApprovalRequest req, Canc vocab.ExampleSentence = p.ExampleSentence; vocab.ExampleSentenceMeaning = p.ExampleSentenceMeaning; if (!string.IsNullOrEmpty(p.AudioUrl)) vocab.AudioUrl = p.AudioUrl; + vocab.Status = ContentStatus.Published; + vocab.UnpublishedAtUtc = null; + vocab.UnpublishedReason = null; + vocab.Version += 1; unitOfWork.Vocabularies.Update(vocab); } @@ -1034,7 +1065,6 @@ private async Task ApplyVocabularyApprovalAsync(ContentApprovalRequest req, Canc if (!string.IsNullOrWhiteSpace(p.LessonTitle)) await LinkVocabularyToLessonAsync(vocab, p.LessonTitle, p.CertificateLevelId, cancellationToken); - // Gắn Cấp độ vào ContentLevelMappings if (p.CertificateLevelId > 0) { var existingMapping = await unitOfWork.ContentLevelMappings.FirstOrDefaultAsync( @@ -1050,6 +1080,11 @@ await unitOfWork.ContentLevelMappings.AddAsync(new ContentLevelMapping } } + if (req.Action == ImportRowAction.New) + { + await unitOfWork.SaveChangesAsync(cancellationToken); + req.TargetEntityId = vocab.Id; + } } private async Task ApplyKanjiApprovalAsync(ContentApprovalRequest req, CancellationToken cancellationToken) @@ -1090,6 +1125,10 @@ private async Task ApplyKanjiApprovalAsync(ContentApprovalRequest req, Cancellat kanji.StrokeCount = p.StrokeCount; if (p.StrokeOrderImageUrl is not null) kanji.StrokeOrderImageUrl = p.StrokeOrderImageUrl; if (p.AudioUrl is not null) kanji.AudioUrl = p.AudioUrl; + kanji.Status = ContentStatus.Published; + kanji.UnpublishedAtUtc = null; + kanji.UnpublishedReason = null; + kanji.Version += 1; unitOfWork.Kanjis.Update(kanji); } @@ -1111,6 +1150,12 @@ await unitOfWork.ContentLevelMappings.AddAsync(new ContentLevelMapping if (!string.IsNullOrWhiteSpace(p.LessonTitle)) await LinkKanjiToLessonAsync(kanji, p.LessonTitle, p.CertificateLevelId, cancellationToken); + + if (req.Action == ImportRowAction.New) + { + await unitOfWork.SaveChangesAsync(cancellationToken); + req.TargetEntityId = kanji.Id; + } } private async Task FindLessonAsync(string title, int levelId, CancellationToken cancellationToken) => @@ -1161,7 +1206,11 @@ private async Task>> GetCertificateSectionIdsByCode return _certificateSectionIdsByCode; } - private async Task ApplyLessonTopicApprovalAsync(ContentApprovalRequest request, string? reviewNote, CancellationToken ct) + private async Task ApplyLessonTopicApprovalAsync( + ContentApprovalRequest request, + string? reviewNote, + CancellationToken ct, + int reviewerUserId = 0) { // In batch review, earlier items may have staged changes before this separate transaction. await unitOfWork.SaveChangesAsync(ct); @@ -1176,8 +1225,9 @@ await unitOfWork.ExecuteLessonTopicApprovalAsync(async token => var current = await unitOfWork.ContentApprovalRequests.GetByIdAsync(id, token) ?? throw new InvalidOperationException("Không tìm thấy yêu cầu bài học."); + current.ReviewedByName = request.ReviewedByName; await ApplyLessonApprovalAsync(current, ReadLessonPayload(current), token); - MarkApproved(current, reviewNote); + MarkApproved(current, reviewNote, reviewerUserId); await unitOfWork.SaveChangesAsync(token); }, ct); } @@ -1215,6 +1265,10 @@ private async Task ApplyLessonApprovalAsync(ContentApprovalRequest req, LessonIm } lesson.CertificateLevelId = p.CertificateLevelId; lesson.LanguageSkillId = p.LanguageSkillId; + lesson.Status = ContentStatus.Published; + lesson.UnpublishedAtUtc = null; + lesson.UnpublishedReason = null; + if (!isNew) lesson.Version += 1; if (isNew) await unitOfWork.Lessons.AddAsync(lesson, cancellationToken); await unitOfWork.SaveChangesAsync(cancellationToken); @@ -1294,9 +1348,7 @@ private async Task ApplyPracticeExerciseApprovalAsync(ContentApprovalRequest req .Where(t => !t.IsDeleted && (t.CertificateLevelId == resolvedLevelId || resolvedLevelId == 0 || t.CertificateLevelId == null)) .OrderByDescending(t => t.CertificateLevelId == resolvedLevelId) .ToListAsync(cancellationToken); - var matchedTopic = topicRow.FirstOrDefault(t => - string.Equals(t.Title.Trim().Normalize(), normalizedTopic, StringComparison.OrdinalIgnoreCase) || - (!string.IsNullOrWhiteSpace(t.StageCode) && string.Equals(t.StageCode.Trim(), p.TopicTitle.Trim(), StringComparison.OrdinalIgnoreCase))); + var matchedTopic = topicRow.FirstOrDefault(t => string.Equals(t.Title.Trim().Normalize(), normalizedTopic, StringComparison.OrdinalIgnoreCase)); if (matchedTopic is null) throw new InvalidOperationException($"Không tìm thấy Topic/Chặng '{p.TopicTitle}' để lưu GroupQuiz."); resolvedTopicId = matchedTopic.Id; @@ -1328,7 +1380,7 @@ static List MapQuestions(IEnumerable MapQuestions(IEnumerable 0 ? resolvedLevelId : null, LanguageSkillId = p.LanguageSkillId, Questions = MapQuestions(p.Questions) - }; - await unitOfWork.PracticeExercises.AddAsync(createdExercise, cancellationToken); - await unitOfWork.SaveChangesAsync(cancellationToken); - req.TargetEntityId = createdExercise.Id; + }, cancellationToken); return; } @@ -1545,6 +1594,10 @@ private async Task ApplyGrammarApprovalAsync(ContentApprovalRequest req, Cancell grammar.UsageNotes = p.UsageNotes; grammar.ExampleSentence = p.ExampleSentence; grammar.ExampleSentenceMeaning = p.ExampleSentenceMeaning; + grammar.Status = ContentStatus.Published; + grammar.UnpublishedAtUtc = null; + grammar.UnpublishedReason = null; + grammar.Version += 1; unitOfWork.GrammarPatterns.Update(grammar); } @@ -1566,6 +1619,12 @@ await unitOfWork.ContentLevelMappings.AddAsync(new ContentLevelMapping }, cancellationToken); } } + + if (req.Action == ImportRowAction.New) + { + await unitOfWork.SaveChangesAsync(cancellationToken); + req.TargetEntityId = grammar.Id; + } } private async Task ApplyMockTestApprovalAsync(ContentApprovalRequest req, CancellationToken cancellationToken) @@ -1645,8 +1704,6 @@ private async Task ApplyMockTestApprovalAsync(ContentApprovalRequest req, Cancel CertificateLevelId = p.CertificateLevelId, ExamKind = resolvedKind, IsManagedWorkflow = true, - SourceType = string.IsNullOrWhiteSpace(req.SourceType) ? "ImportExcel" : req.SourceType, - SourceReference = string.IsNullOrWhiteSpace(req.SourceReference) ? req.RowKey : req.SourceReference, Sections = p.Sections!.Select(s => CreateImportedSection(s, sectionIdByCode)).ToList() }; @@ -1759,63 +1816,6 @@ private static MockTestSection CreateImportedSection(MockTestSectionPayloadRespo } #endregion - private async Task ApplySrsCardTemplateApprovalAsync(ContentApprovalRequest req, CancellationToken cancellationToken) - { - var p = JsonSerializer.Deserialize(req.PayloadJson, JsonOptions) - ?? throw new InvalidOperationException("Payload thẻ mẫu SRS rỗng."); - if (string.IsNullOrWhiteSpace(p.FrontText) || string.IsNullOrWhiteSpace(p.BackText)) - throw new InvalidOperationException("Thẻ mẫu SRS thiếu mặt trước hoặc mặt sau."); - - var normalizedKey = string.IsNullOrWhiteSpace(p.NormalizedContentKey) - ? $"{p.CertificateLevelCode}:{p.CardType}:{p.FrontText.Trim()}" - : p.NormalizedContentKey.Trim(); - if (normalizedKey.Length > 300) normalizedKey = normalizedKey[..300]; - - var entity = req.TargetEntityId.HasValue - ? await unitOfWork.SrsCardTemplates.GetByIdAsync(req.TargetEntityId.Value, cancellationToken) - : null; - entity ??= await unitOfWork.SrsCardTemplates.FirstOrDefaultAsync( - x => !x.IsDeleted && x.NormalizedContentKey == normalizedKey, cancellationToken); - - var reviewer = claimService.GetUserClaim(); - var now = DateTime.UtcNow; - - if (entity is null) - { - entity = new SrsCardTemplate - { - NormalizedContentKey = normalizedKey, - SubmittedByUserId = req.SubmittedByUserId, - SubmittedAtUtc = req.SubmittedAt, - Version = 1, - }; - await unitOfWork.SrsCardTemplates.AddAsync(entity, cancellationToken); - } - else - { - entity.Version++; - unitOfWork.SrsCardTemplates.Update(entity); - } - - entity.CardType = p.CardType.Length > 30 ? p.CardType[..30] : p.CardType; - entity.FrontText = p.FrontText.Length > 500 ? p.FrontText[..500] : p.FrontText; - entity.BackText = p.BackText.Length > 1000 ? p.BackText[..1000] : p.BackText; - entity.Reading = p.Reading is { Length: > 300 } ? p.Reading[..300] : p.Reading; - entity.Meaning = p.Meaning is { Length: > 500 } ? p.Meaning[..500] : p.Meaning; - entity.ExampleSentence = p.ExampleSentence is { Length: > 1000 } ? p.ExampleSentence[..1000] : p.ExampleSentence; - entity.ExampleMeaning = p.ExampleMeaning is { Length: > 1000 } ? p.ExampleMeaning[..1000] : p.ExampleMeaning; - entity.UsageNotes = p.UsageNotes is { Length: > 2000 } ? p.UsageNotes[..2000] : p.UsageNotes; - entity.AudioUrl = p.AudioUrl is { Length: > 1000 } ? p.AudioUrl[..1000] : p.AudioUrl; - entity.CertificateLevelId = p.CertificateLevelId > 0 ? p.CertificateLevelId : null; - entity.JlptLevel = p.CertificateLevelCode.Length > 10 ? p.CertificateLevelCode[..10] : p.CertificateLevelCode; - entity.Status = ContentStatus.Published; - entity.ReviewedByAdminId = reviewer.Id > 0 ? reviewer.Id : null; - entity.ReviewedAtUtc = now; - - await unitOfWork.SaveChangesAsync(cancellationToken); - req.TargetEntityId = entity.Id; - } - private static string NormalizeMockQuestionType(string? questionType) => JlptMockQuestionFormats.NormalizeQuestionType(questionType) ?? throw new InvalidOperationException($"Dạng câu MockTest không hỗ trợ: {questionType}."); diff --git a/RikiPath.Application/Services/ContentAuthoring/ContentModerationV2Service.cs b/RikiPath.Application/Services/ContentAuthoring/ContentModerationV2Service.cs index f17763e..6af6e57 100644 --- a/RikiPath.Application/Services/ContentAuthoring/ContentModerationV2Service.cs +++ b/RikiPath.Application/Services/ContentAuthoring/ContentModerationV2Service.cs @@ -72,15 +72,31 @@ public async Task> GetDetailAsync(int requestId .Where(test => test.Id == request.TargetEntityId.Value).Select(test => (int?)test.Version) .FirstOrDefaultAsync(ct) : null; + ContentStatus? entityPublishStatus = request.Status == ContentApprovalStatus.Approved + ? ContentStatus.Published + : (request.Status == ContentApprovalStatus.Unpublished ? ContentStatus.Unpublished : null); + if (request.TargetEntityId.HasValue && + (request.EntityType is ImportEntityType.MockTest or ImportEntityType.PracticeSet)) + { + var targetExam = await unitOfWork.MockTests.Query().AsNoTracking() + .FirstOrDefaultAsync(t => t.Id == request.TargetEntityId.Value && !t.IsDeleted, ct); + if (targetExam is not null) + { + entityPublishStatus = await MockContentReviewState.IsApprovedExamAsync(unitOfWork, targetExam, ct) + ? ContentStatus.Published + : (request.Status == ContentApprovalStatus.Approved || request.Status == ContentApprovalStatus.Unpublished + ? ContentStatus.Unpublished + : entityPublishStatus); + } + } return ApiResponse.Success(new ModerationDetailDto { Summary = MapQueueItem(request, levels, skills), PayloadJson = request.PayloadJson, StructuredPreview = preview, ValidationSummaryJson = request.ValidationSummaryJson, - ReviewHistory = DeserializeOrDefault>(request.ReviewHistoryJson) ?? [], - CurrentEntityPublishStatus = request.Status == ContentApprovalStatus.Approved - ? ContentStatus.Published : null, + ReviewHistory = ReviewHistoryHelper.Parse(request.ReviewHistoryJson), + CurrentEntityPublishStatus = entityPublishStatus, CurrentEntityVersion = version }); } @@ -103,14 +119,35 @@ public async Task> ModerateAsync(int requestId, if (decision.Decision == ModerationDecision.RequestChanges) { + var priorStatus = request.Status; + var now = DateTime.UtcNow; request.Status = ContentApprovalStatus.ChangesRequested; request.ReviewNote = decision.ReviewNote?.Trim(); - request.ReviewedAt = DateTime.UtcNow; + request.ReviewedAt = now; request.ReviewedByName = adminName; + ReviewHistoryHelper.Append( + request, + "ChangesRequested", + priorStatus, + ContentApprovalStatus.ChangesRequested, + adminUserId, + adminName, + now, + decision.ReviewNote); var bank = await unitOfWork.ContentBankItems.Query().FirstOrDefaultAsync(item => !item.IsDeleted && item.OwnerUserId == request.SubmittedByUserId && item.EntityType == request.EntityType && item.LatestBatchId == request.BatchId, ct); if (bank is not null) bank.Status = request.Status; + await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog + { + ActorUserId = adminUserId, + EntityType = nameof(ContentApprovalRequest), + EntityId = request.Id, + Action = "ChangesRequested", + AfterJson = JsonSerializer.Serialize(new { request.Id, Status = request.Status.ToString() }, JsonOpts), + Reason = request.ReviewNote, + CreatedAtUtc = now + }, ct); await unitOfWork.SaveChangesAsync(ct); } else @@ -118,6 +155,7 @@ public async Task> ModerateAsync(int requestId, var reviewed = await approvals.ReviewRequestAsync(requestId, new ReviewContentRequest { Approve = approving, + RequestChanges = !approving && decision.Decision == ModerationDecision.RequestChanges, ReviewNote = decision.ReviewNote }, ct); if (!reviewed.IsSuccess) @@ -148,6 +186,7 @@ public async Task UnpublishAsync(UnpublishContentRequest request, i if (!await MockContentReviewState.IsApprovedExamAsync(unitOfWork, exam, ct)) return ApiResponse.Fail("Đề thi đã ngừng xuất bản.", HttpStatusCode.Conflict); var now = DateTime.UtcNow; + var reason = request.Reason.Trim(); exam.IsManagedWorkflow = true; var entry = new ContentApprovalRequest { @@ -163,9 +202,11 @@ public async Task UnpublishAsync(UnpublishContentRequest request, i SubmittedByUserId = adminUserId, SubmittedAt = now, ReviewedAt = now, - ReviewNote = request.Reason.Trim(), + ReviewedByName = "Admin", + ReviewNote = reason, SourceType = "Admin" }; + ReviewHistoryHelper.Append(entry, "Unpublished", ContentApprovalStatus.Approved, ContentApprovalStatus.Unpublished, adminUserId, "Admin", now, reason); await unitOfWork.ContentApprovalRequests.AddAsync(entry, ct); await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog { @@ -174,10 +215,61 @@ await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog EntityId = exam.Id, Action = "Unpublish", AfterJson = JsonSerializer.Serialize(new { status = "Unpublished" }), - Reason = request.Reason.Trim(), + Reason = reason, + CreatedAtUtc = now + }, ct); + await unitOfWork.SaveChangesAsync(ct); + if (sidebarNotifier is not null) await sidebarNotifier.NotifyAdminsAsync("content_unpublished", ct); + return ApiResponse.Success(); + } + + public async Task RepublishAsync(UnpublishContentRequest request, int adminUserId, string adminName, CancellationToken ct) + { + if (!string.Equals(request.TargetType, "Exam", StringComparison.OrdinalIgnoreCase)) + return ApiResponse.Fail("Chỉ hỗ trợ xuất bản lại đề thi hoặc bộ luyện tập.", HttpStatusCode.BadRequest); + var exam = await unitOfWork.MockTests.Query().FirstOrDefaultAsync(t => t.Id == request.TargetId && !t.IsDeleted, ct); + if (exam is null) return ApiResponse.NotFound("Không tìm thấy đề thi."); + if (await MockContentReviewState.IsApprovedExamAsync(unitOfWork, exam, ct)) + return ApiResponse.Fail("Đề thi đang được sử dụng.", HttpStatusCode.Conflict); + + var latest = await unitOfWork.ContentApprovalRequests.Query().AsNoTracking() + .Where(r => !r.IsDeleted && r.TargetEntityId == exam.Id && + (r.EntityType == ImportEntityType.MockTest || r.EntityType == ImportEntityType.PracticeSet)) + .OrderByDescending(r => r.Id).FirstOrDefaultAsync(ct); + var now = DateTime.UtcNow; + var reason = string.IsNullOrWhiteSpace(request.Reason) ? "Xuất bản lại" : request.Reason.Trim(); + var entry = new ContentApprovalRequest + { + BatchId = Guid.NewGuid(), + EntityType = latest?.EntityType ?? (exam.ExamKind == ExamKind.FullMockTest ? ImportEntityType.MockTest : ImportEntityType.PracticeSet), + Action = ImportRowAction.Modified, + TargetEntityId = exam.Id, + RowKey = exam.Title, + PayloadJson = latest?.PayloadJson ?? "{}", + SourceRowNumber = 1, + SourceFileName = "Admin", + Status = ContentApprovalStatus.Approved, + SubmittedByUserId = adminUserId, + SubmittedAt = now, + ReviewedAt = now, + ReviewedByName = adminName, + ReviewNote = reason, + SourceType = "Admin" + }; + ReviewHistoryHelper.Append(entry, "Republished", ContentApprovalStatus.Unpublished, ContentApprovalStatus.Approved, adminUserId, adminName, now, reason); + await unitOfWork.ContentApprovalRequests.AddAsync(entry, ct); + await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog + { + ActorUserId = adminUserId, + EntityType = "Exam", + EntityId = exam.Id, + Action = "Republish", + AfterJson = JsonSerializer.Serialize(new { status = "Published" }), + Reason = reason, CreatedAtUtc = now }, ct); await unitOfWork.SaveChangesAsync(ct); + if (sidebarNotifier is not null) await sidebarNotifier.NotifyAdminsAsync("content_republished", ct); return ApiResponse.Success(); } diff --git a/RikiPath.Application/Services/ContentAuthoring/ExamBuilderService.cs b/RikiPath.Application/Services/ContentAuthoring/ExamBuilderService.cs index 8d8ec00..86d85ca 100644 --- a/RikiPath.Application/Services/ContentAuthoring/ExamBuilderService.cs +++ b/RikiPath.Application/Services/ContentAuthoring/ExamBuilderService.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using RikiPath.Application.Common; using RikiPath.Application.DTOs.ContentAuthoring; +using RikiPath.Application.Helpers; using RikiPath.Application.IServices; using RikiPath.Application.Responses; using RikiPath.Domain.Entities; @@ -175,6 +176,8 @@ public async Task> SaveDraftAsync(ExamBuilderDto req }; await unitOfWork.ContentBankItems.AddAsync(bank, ct); } + if (request.ParentExamId is > 0) + bank.TargetEntityId = request.ParentExamId; request.Id = null; bank.PayloadJson = JsonSerializer.Serialize(request, JsonOpts); bank.Status = ContentApprovalStatus.Draft; @@ -183,6 +186,42 @@ public async Task> SaveDraftAsync(ExamBuilderDto req return ApiResponse.Success(request); } + public async Task> SaveAndSubmitAsync(ExamBuilderDto request, int actorUserId, CancellationToken ct) + { + if (actorUserId <= 0) return ApiResponse.Unauthorized(); + ApiResponse result = ApiResponse.Fail("Không thể gửi duyệt đề thi."); + ApiResponse? failedSubmit = null; + try + { + await unitOfWork.ExecuteInTransactionAsync(async token => + { + var saved = await SaveDraftAsync(request, actorUserId, token); + if (!saved.IsSuccess || saved.Result?.Id is not int draftId) + { + failedSubmit = saved; + throw new InvalidOperationException(saved.ErrorMessage ?? "Không thể lưu đề thi."); + } + var submitted = await SubmitExamInternalAsync(draftId, actorUserId, notify: false, token); + if (!submitted.IsSuccess) + { + failedSubmit = submitted; + throw new InvalidOperationException(submitted.ErrorMessage ?? "Đề thi chưa đủ điều kiện gửi duyệt."); + } + result = submitted; + }, ct); + } + catch (InvalidOperationException) when (failedSubmit is not null) + { + return failedSubmit; + } + if (result.IsSuccess && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("exam_submitted", ct); + await sidebarNotifier.NotifyUsersAsync([actorUserId], "exam_submitted", ct); + } + return result; + } + public async Task> CreateNewVersionAsync(int sourceExamId, int actorUserId, CancellationToken ct) { var source = await GetDetailAsync(sourceExamId, actorUserId, false, ct); @@ -233,10 +272,14 @@ public async Task> ValidateExamAsyn allowed.Where(CanonicalQuestionValidator.SupportedJlptLevelCodes.Contains).ToHashSet(StringComparer.OrdinalIgnoreCase))); } - public async Task> SubmitExamAsync(int examId, int actorUserId, CancellationToken ct) + public Task> SubmitExamAsync(int examId, int actorUserId, CancellationToken ct) => + SubmitExamInternalAsync(examId, actorUserId, notify: true, ct); + + private async Task> SubmitExamInternalAsync( + int examId, int actorUserId, bool notify, CancellationToken ct) { if (examId >= 0) - return ApiResponse.Fail("Hãy tạo phiên bản nháp trong Content Bank trước khi gửi duyệt."); + return ApiResponse.Fail("Hãy tạo đề mới hoặc đề xuất chỉnh sửa trước khi gửi duyệt."); var bank = await Drafts(actorUserId).FirstOrDefaultAsync(item => item.Id == -examId, ct); if (bank is null) return ApiResponse.NotFound("Không tìm thấy bản nháp của bạn."); if (bank.Status == ContentApprovalStatus.PendingReview) @@ -331,25 +374,78 @@ public async Task> SubmitExamAsync(int examId, int a requireFullCoverage: bank.EntityType == ImportEntityType.MockTest); if (validationError is not null) return ApiResponse.Fail(validationError); var now = DateTime.UtcNow; - var approval = new ContentApprovalRequest + var targetId = bank.TargetEntityId ?? draft.ParentExamId; + var rowKey = $"{draft.Title} / {level.Code}"; + var actor = await unitOfWork.UserAccounts.Query().AsNoTracking() + .Where(u => u.Id == actorUserId) + .Select(u => new { u.FirstName, u.LastName }) + .FirstOrDefaultAsync(ct); + var actorName = actor is null ? $"User #{actorUserId}" : UserNameHelper.FormatFullName(actor.FirstName, actor.LastName); + + ContentApprovalRequest? existingApproval = null; + if (bank.LatestBatchId.HasValue) { - BatchId = Guid.NewGuid(), EntityType = bank.EntityType, - Action = bank.TargetEntityId.HasValue ? ImportRowAction.Modified : ImportRowAction.New, - TargetEntityId = bank.TargetEntityId, - RowKey = $"{draft.Title} / {level.Code} (v{draft.Version})", - PayloadJson = payloadJson, SourceRowNumber = 1, - SourceFileName = "Exam Builder", Status = ContentApprovalStatus.PendingReview, - SubmittedByUserId = actorUserId, SubmittedAt = now, - SourceType = draft.SourceType, SourceReference = draft.SourceReference, - CertificateLevelId = level.Id, - AiProvenanceJson = draft.AiProvenance is null ? null : JsonSerializer.Serialize(draft.AiProvenance, JsonOpts), - ValidationSummaryJson = JsonSerializer.Serialize(validation.Result, JsonOpts) - }; - await unitOfWork.ContentApprovalRequests.AddAsync(approval, ct); + existingApproval = await unitOfWork.ContentApprovalRequests.Query() + .FirstOrDefaultAsync(r => !r.IsDeleted && r.BatchId == bank.LatestBatchId.Value && + r.SubmittedByUserId == actorUserId && + (r.EntityType == ImportEntityType.MockTest || r.EntityType == ImportEntityType.PracticeSet) && + (r.Status == ContentApprovalStatus.Draft || + r.Status == ContentApprovalStatus.Rejected || + r.Status == ContentApprovalStatus.ChangesRequested), ct); + } + + if (existingApproval is not null) + { + ReviewHistoryHelper.EnsurePreviousDecisionRecorded(existingApproval); + var prev = existingApproval.Status; + existingApproval.EntityType = bank.EntityType; + existingApproval.Action = targetId.HasValue ? ImportRowAction.Modified : ImportRowAction.New; + existingApproval.TargetEntityId = targetId; + existingApproval.RowKey = rowKey; + existingApproval.PayloadJson = payloadJson; + existingApproval.Status = ContentApprovalStatus.PendingReview; + existingApproval.SubmittedAt = now; + existingApproval.ModifiedDate = now; + existingApproval.ReviewedAt = null; + existingApproval.ReviewedByName = null; + existingApproval.ReviewNote = null; + existingApproval.CertificateLevelId = level.Id; + existingApproval.SourceType = draft.SourceType; + existingApproval.SourceReference = draft.SourceReference; + existingApproval.AiProvenanceJson = draft.AiProvenance is null ? null : JsonSerializer.Serialize(draft.AiProvenance, JsonOpts); + existingApproval.ValidationSummaryJson = JsonSerializer.Serialize(validation.Result, JsonOpts); + ReviewHistoryHelper.Append(existingApproval, "Resubmitted", prev, ContentApprovalStatus.PendingReview, actorUserId, actorName, now); + bank.LatestBatchId = existingApproval.BatchId; + } + else + { + var approval = new ContentApprovalRequest + { + BatchId = Guid.NewGuid(), EntityType = bank.EntityType, + Action = targetId.HasValue ? ImportRowAction.Modified : ImportRowAction.New, + TargetEntityId = targetId, + RowKey = rowKey, + PayloadJson = payloadJson, SourceRowNumber = 1, + SourceFileName = "Exam Builder", Status = ContentApprovalStatus.PendingReview, + SubmittedByUserId = actorUserId, SubmittedAt = now, + SourceType = draft.SourceType, SourceReference = draft.SourceReference, + CertificateLevelId = level.Id, + AiProvenanceJson = draft.AiProvenance is null ? null : JsonSerializer.Serialize(draft.AiProvenance, JsonOpts), + ValidationSummaryJson = JsonSerializer.Serialize(validation.Result, JsonOpts) + }; + ReviewHistoryHelper.Append(approval, "Submitted", ContentApprovalStatus.Draft, ContentApprovalStatus.PendingReview, actorUserId, actorName, now); + await unitOfWork.ContentApprovalRequests.AddAsync(approval, ct); + bank.LatestBatchId = approval.BatchId; + } + + bank.TargetEntityId = targetId; bank.Status = ContentApprovalStatus.PendingReview; - bank.LatestBatchId = approval.BatchId; await unitOfWork.SaveChangesAsync(ct); - if (sidebarNotifier is not null) await sidebarNotifier.NotifyAdminsAsync("exam_submitted", ct); + if (notify && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("exam_submitted", ct); + await sidebarNotifier.NotifyUsersAsync([actorUserId], "exam_submitted", ct); + } draft.Id = examId; draft.PublishStatus = ContentStatus.PendingReview; return ApiResponse.Success(draft); diff --git a/RikiPath.Application/Services/ContentAuthoring/QuestionBankService.cs b/RikiPath.Application/Services/ContentAuthoring/QuestionBankService.cs index af1a4f8..bf1d509 100644 --- a/RikiPath.Application/Services/ContentAuthoring/QuestionBankService.cs +++ b/RikiPath.Application/Services/ContentAuthoring/QuestionBankService.cs @@ -123,6 +123,7 @@ public async Task>> ListPassagesAsync(int? var query = unitOfWork.ContentPassages.Query().AsNoTracking() .Include(p => p.MockTestSection!).ThenInclude(section => section.MockTest).ThenInclude(test => test.CertificateLevel) .Include(p => p.MockTestSection!).ThenInclude(section => section.LanguageSkill) + .Include(p => p.Questions) .Where(p => !p.IsDeleted && p.MockTestSectionId.HasValue && !p.MockTestSection!.IsDeleted && !p.MockTestSection.MockTest.IsDeleted); if (!isAdmin) @@ -196,6 +197,10 @@ internal static CanonicalQuestionDto MapToDto(QuestionBankItem e, bool includeTr { Id = e.Id, MockTestSectionId = e.MockTestSectionId, + MockTestId = e.MockTestSection?.MockTestId, + MockTestTitle = e.MockTestSection?.MockTest?.Title, + MockTestExamKind = e.MockTestSection?.MockTest?.ExamKind.ToString(), + SectionTitle = e.MockTestSection?.Title, QuestionIdentity = e.QuestionIdentity, Version = e.Version, ParentQuestionId = e.ParentQuestionId, @@ -234,6 +239,11 @@ internal static CanonicalQuestionDto MapToDto(QuestionBankItem e, bool includeTr { Id = p.Id, MockTestSectionId = p.MockTestSectionId, + MockTestId = p.MockTestSection?.MockTestId, + MockTestTitle = p.MockTestSection?.MockTest?.Title, + MockTestExamKind = p.MockTestSection?.MockTest?.ExamKind.ToString(), + SectionTitle = p.MockTestSection?.Title, + QuestionCount = p.Questions?.Count(q => !q.IsDeleted) ?? 0, PassageIdentity = p.PassageIdentity, PassageCode = p.PassageCode, CertificateLevelId = p.MockTestSection?.MockTest.CertificateLevelId ?? 0, diff --git a/RikiPath.Application/Services/ContentAuthoring/ReviewHistoryHelper.cs b/RikiPath.Application/Services/ContentAuthoring/ReviewHistoryHelper.cs new file mode 100644 index 0000000..216bbd8 --- /dev/null +++ b/RikiPath.Application/Services/ContentAuthoring/ReviewHistoryHelper.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using RikiPath.Application.DTOs.ContentAuthoring; +using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; + +namespace RikiPath.Application.Services.ContentAuthoring; + +internal static class ReviewHistoryHelper +{ + private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web) + { + PropertyNameCaseInsensitive = true + }; + + internal static List Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try { return JsonSerializer.Deserialize>(json, JsonOpts) ?? []; } + catch (JsonException) { return []; } + } + + internal static void Append( + ContentApprovalRequest request, + string action, + ContentApprovalStatus? fromStatus, + ContentApprovalStatus toStatus, + int actorUserId, + string actorName, + DateTime atUtc, + string? note = null) + { + var entries = Parse(request.ReviewHistoryJson); + entries.Add(new ReviewHistoryEntryDto + { + Action = action, + FromStatus = fromStatus?.ToString(), + ToStatus = toStatus.ToString(), + ActorUserId = actorUserId, + ActorName = string.IsNullOrWhiteSpace(actorName) ? $"User #{actorUserId}" : actorName.Trim(), + AtUtc = atUtc, + Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(), + }); + request.ReviewHistoryJson = JsonSerializer.Serialize(entries, JsonOpts); + } + + /// + /// Ensures a legacy review decision already stored on the request row is captured in + /// ReviewHistoryJson before an author revision clears current ReviewNote/ReviewedAt columns. + /// + internal static void EnsurePreviousDecisionRecorded(ContentApprovalRequest request) + { + if (request.Status is not (ContentApprovalStatus.Rejected or ContentApprovalStatus.ChangesRequested or ContentApprovalStatus.Approved or ContentApprovalStatus.Unpublished)) + return; + if (string.IsNullOrWhiteSpace(request.ReviewNote) && !request.ReviewedAt.HasValue) + return; + + var entries = Parse(request.ReviewHistoryJson); + var atUtc = request.ReviewedAt ?? request.ModifiedDate ?? request.SubmittedAt; + var expectedAction = request.Status switch + { + ContentApprovalStatus.Approved => "Approved", + ContentApprovalStatus.ChangesRequested => "ChangesRequested", + ContentApprovalStatus.Unpublished => "Unpublished", + _ => "Rejected", + }; + var alreadyCaptured = entries.Any(e => + string.Equals(e.Action, expectedAction, StringComparison.OrdinalIgnoreCase) && + Math.Abs((e.AtUtc - atUtc).TotalSeconds) < 2); + if (alreadyCaptured) return; + + entries.Add(new ReviewHistoryEntryDto + { + Action = expectedAction, + FromStatus = ContentApprovalStatus.PendingReview.ToString(), + ToStatus = request.Status.ToString(), + ActorUserId = 0, + ActorName = string.IsNullOrWhiteSpace(request.ReviewedByName) ? "Admin" : request.ReviewedByName.Trim(), + AtUtc = atUtc, + Note = string.IsNullOrWhiteSpace(request.ReviewNote) ? null : request.ReviewNote.Trim(), + }); + request.ReviewHistoryJson = JsonSerializer.Serialize(entries, JsonOpts); + } +} diff --git a/RikiPath.Application/Services/ContentAuthoring/UnifiedImportService.cs b/RikiPath.Application/Services/ContentAuthoring/UnifiedImportService.cs index 291793e..bd2cbcc 100644 --- a/RikiPath.Application/Services/ContentAuthoring/UnifiedImportService.cs +++ b/RikiPath.Application/Services/ContentAuthoring/UnifiedImportService.cs @@ -21,7 +21,8 @@ namespace RikiPath.Application.Services.ContentAuthoring; public sealed partial class UnifiedImportService( IUnitOfWork unitOfWork, IQuestionBankService questionBankService, - IFileStorageService fileStorage) : IUnifiedImportService + IFileStorageService fileStorage, + ISidebarCounterNotifier? sidebarNotifier = null) : IUnifiedImportService { private const long MaxUploadBytes = 25 * 1024 * 1024; private const long MaxZipUncompressedBytes = 50 * 1024 * 1024; @@ -133,7 +134,9 @@ public async Task> ConfirmAsync( PassagesDrafted = existing.Count(e => e.EntityType == ImportEntityType.Passage), QuestionsDrafted = existing.Count(e => e.EntityType == ImportEntityType.QuestionBank), ExamDraftId = existing.FirstOrDefault(e => e.EntityType is ImportEntityType.MockTest or ImportEntityType.PracticeSet)?.TargetEntityId, - ResultingStatus = ContentStatus.Draft, + ResultingStatus = existing[0].Status == ContentApprovalStatus.PendingReview + ? ContentStatus.PendingReview + : ContentStatus.Draft, Warnings = ["Yêu cầu này đã được xác nhận trước đó (idempotent)."], }); } @@ -321,8 +324,11 @@ public async Task> ConfirmAsync( } else if (bank.Status == ContentApprovalStatus.PendingReview) return ApiResponse.Conflict("Đề này đang chờ admin duyệt."); + var submitNow = request.SubmitForReview; + var targetStatus = submitNow ? ContentApprovalStatus.PendingReview : ContentApprovalStatus.Draft; + var now = DateTime.UtcNow; bank.PayloadJson = payloadJson; - bank.Status = ContentApprovalStatus.Draft; + bank.Status = targetStatus; bank.LatestBatchId = batchId; var approval = new ContentApprovalRequest { @@ -331,19 +337,31 @@ public async Task> ConfirmAsync( TargetEntityId = bank.TargetEntityId, RowKey = $"{payload.Title} / {level.Code}", PayloadJson = payloadJson, SourceRowNumber = 1, SourceFileName = request.SourceFileName, - Status = ContentApprovalStatus.Draft, SubmittedByUserId = actorUserId, - SubmittedAt = DateTime.UtcNow, SourceType = NormalizeSourceType(request.SourceFormat), + Status = targetStatus, SubmittedByUserId = actorUserId, + SubmittedAt = now, SourceType = NormalizeSourceType(request.SourceFormat), SourceReference = blueprint.SourceReference, CertificateLevelId = level.Id, IdempotencyKey = string.IsNullOrWhiteSpace(request.IdempotencyKey) ? null : request.IdempotencyKey.Trim() }; + if (submitNow) + { + ReviewHistoryHelper.Append(approval, "Submitted", ContentApprovalStatus.Draft, ContentApprovalStatus.PendingReview, actorUserId, $"User #{actorUserId}", now); + } await unitOfWork.ContentApprovalRequests.AddAsync(approval, ct); await unitOfWork.SaveChangesAsync(ct); + if (submitNow && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("unified_import_submitted", ct); + await sidebarNotifier.NotifyUsersAsync([actorUserId], "unified_import_submitted", ct); + } var result = new ConfirmUnifiedImportResponse { BatchId = batchId, ExamDraftId = null, PassagesDrafted = passageCount, - QuestionsDrafted = questionCount, ResultingStatus = ContentStatus.Draft, - Warnings = ["Đã lưu bản nháp trong Content Bank; các bảng đề thi chỉ được ghi sau khi admin duyệt."] + QuestionsDrafted = questionCount, + ResultingStatus = submitNow ? ContentStatus.PendingReview : ContentStatus.Draft, + Warnings = [submitNow + ? "Đã gửi nội dung để quản trị viên xét duyệt." + : "Đã lưu bản nháp; nội dung sẽ được đưa vào kho học liệu sau khi quản trị viên duyệt."] }; return ApiResponse.Success(result); } @@ -354,7 +372,8 @@ public async Task> ConfirmFromArchiveA UnifiedImportKind expectedKind, string? idempotencyKey, int actorUserId, - CancellationToken ct) + CancellationToken ct, + bool submitForReview = false) { await using var buffer = new MemoryStream(); await CopyBoundedAsync(zipOrDataStream, buffer, MaxUploadBytes, ct); @@ -393,6 +412,7 @@ public async Task> ConfirmFromArchiveA SourceFileName = preview.FileName, SourceFormat = "Zip", IdempotencyKey = idempotencyKey, + SubmitForReview = submitForReview, ExamBlueprint = preview.ExamBlueprint, Rows = preview.Rows, }, extractedStreams, actorUserId, ct); diff --git a/RikiPath.Application/Services/ContentAuthoringService.cs b/RikiPath.Application/Services/ContentAuthoringService.cs index bb08299..8c11f12 100644 --- a/RikiPath.Application/Services/ContentAuthoringService.cs +++ b/RikiPath.Application/Services/ContentAuthoringService.cs @@ -7,6 +7,7 @@ using RikiPath.Application.Responses; using RikiPath.Application.Responses.Content; using RikiPath.Application.Responses.ContentAuthoring; +using RikiPath.Application.Services.ContentAuthoring; using RikiPath.Domain.Entities; using RikiPath.Domain.Enums; using System.Net; @@ -30,7 +31,8 @@ public class ContentAuthoringService( IUnitOfWork unitOfWork, IAiContentAuthoringClient aiClient, IClaimService claimService, - ILogger logger) : IContentAuthoringService + ILogger logger, + ISidebarCounterNotifier? sidebarNotifier = null) : IContentAuthoringService { private const int MaxItemsAllowed = 30; private const int MaxAiAttempts = 2; @@ -681,6 +683,8 @@ public async Task> ConfirmKanjiSuggesti var batchId = Guid.NewGuid(); var now = DateTime.UtcNow; + var submitNow = request.SubmitForReview; + var rowStatus = submitNow ? ContentApprovalStatus.PendingReview : ContentApprovalStatus.Draft; var rows = new List(); var sortOrder = 1; foreach (var item in request.Items) @@ -697,24 +701,26 @@ public async Task> ConfirmKanjiSuggesti certificateLevelId = ctx.Level.Id, }; - rows.Add(new ContentApprovalRequest + var row = new ContentApprovalRequest { BatchId = batchId, - // TODO: xác nhận lại đúng tên giá trị enum ImportEntityType cho Kanji nếu khác. EntityType = ImportEntityType.Kanji, - // TODO: xác nhận lại đúng tên giá trị enum ImportRowAction (New/Modified). Action = item.IsDuplicate ? ImportRowAction.Modified : ImportRowAction.New, TargetEntityId = item.ExistingKanjiId, RowKey = item.Character, PayloadJson = JsonSerializer.Serialize(payload), SourceRowNumber = sortOrder++, SourceFileName = "AI Content Assistant", - // TODO: xác nhận lại đúng tên giá trị enum ContentApprovalStatus mặc định - // khi content author vừa gửi (Draft hay PendingReview...). - Status = ContentApprovalStatus.Draft, + Status = rowStatus, SubmittedByUserId = userId, SubmittedAt = now, - }); + SourceType = "AI", + }; + if (submitNow) + { + ReviewHistoryHelper.Append(row, "Submitted", ContentApprovalStatus.Draft, ContentApprovalStatus.PendingReview, userId, $"User #{userId}", now); + } + rows.Add(row); } var stagedBanks = new Dictionary(StringComparer.Ordinal); @@ -742,12 +748,17 @@ public async Task> ConfirmKanjiSuggesti } stagedBanks[naturalKey] = bank; bank.PayloadJson = row.PayloadJson; - bank.Status = ContentApprovalStatus.Draft; + bank.Status = rowStatus; bank.TargetEntityId = row.TargetEntityId; bank.LatestBatchId = batchId; } await unitOfWork.ContentApprovalRequests.AddRangeAsync(rows, cancellationToken); await unitOfWork.SaveChangesAsync(cancellationToken); + if (submitNow && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("ai_kanji_submitted", cancellationToken); + await sidebarNotifier.NotifyUsersAsync([userId], "ai_kanji_submitted", cancellationToken); + } return ApiResponse.Success(new SubmitKanjiApprovalResponse { @@ -874,7 +885,7 @@ public async Task> ConfirmVocabularyS IsExisting: i.IsDuplicate, TargetId: i.ExistingVocabularyId)).ToList(); - return await SubmitForApprovalAsync(ImportEntityType.Vocabulary, drafts, cancellationToken); + return await SubmitForApprovalAsync(ImportEntityType.Vocabulary, drafts, cancellationToken, request.SubmitForReview); } private static string BuildListUserPrompt( @@ -1068,7 +1079,7 @@ public async Task> ConfirmGrammarSugg HttpStatusCode.InternalServerError); } - return await SubmitForApprovalAsync(GrammarEntityType.Value, drafts, cancellationToken); + return await SubmitForApprovalAsync(GrammarEntityType.Value, drafts, cancellationToken, request.SubmitForReview); } private sealed record GrammarAiRawItem( @@ -1315,7 +1326,7 @@ await unitOfWork.GrammarPatterns.Query().CountAsync(g => !g.IsDeleted && grammar }; return await SubmitForApprovalAsync(ImportEntityType.Lesson, - new List { new(request.Title.Trim(), payload, false, null) }, cancellationToken); + new List { new(request.Title.Trim(), payload, false, null) }, cancellationToken, request.SubmitForReview); } catch (OperationCanceledException) { throw; } catch (Exception ex) @@ -1490,7 +1501,7 @@ public async Task> ConfirmPracticeExe request.Questions); return await SubmitForApprovalAsync(ImportEntityType.PracticeExercise, - new List { new(request.Title.Trim(), canonicalPractice, false, null) }, cancellationToken); + new List { new(request.Title.Trim(), canonicalPractice, false, null) }, cancellationToken, request.SubmitForReview); } catch (OperationCanceledException) { throw; } catch (Exception ex) @@ -1652,7 +1663,7 @@ public async Task> ConfirmMockTestSug mappedSections); return await SubmitForApprovalAsync(ImportEntityType.MockTest, - new List { new(request.Title.Trim(), canonicalMock, false, null) }, cancellationToken); + new List { new(request.Title.Trim(), canonicalMock, false, null) }, cancellationToken, request.SubmitForReview); } catch (OperationCanceledException) { throw; } catch (Exception ex) @@ -1990,19 +2001,23 @@ private sealed record ApprovalDraft(string RowKey, object Payload, bool IsExisti /// Ghi các bản nháp vào ContentApprovalRequest (cùng 1 BatchId) để admin duyệt — giống luồng Confirm Kanji. private async Task> SubmitForApprovalAsync( - ImportEntityType entityType, List drafts, CancellationToken cancellationToken) + ImportEntityType entityType, + List drafts, + CancellationToken cancellationToken, + bool submitForReview = false) { try { var userId = claimService.GetUserClaim().Id; var batchId = Guid.NewGuid(); var now = DateTime.UtcNow; + var rowStatus = submitForReview ? ContentApprovalStatus.PendingReview : ContentApprovalStatus.Draft; var rows = new List(); var sortOrder = 1; foreach (var draft in drafts) { - rows.Add(new ContentApprovalRequest + var row = new ContentApprovalRequest { BatchId = batchId, EntityType = entityType, @@ -2012,17 +2027,25 @@ private async Task> SubmitForApproval PayloadJson = JsonSerializer.Serialize(draft.Payload, JsonOpts), SourceRowNumber = sortOrder++, SourceFileName = "AI Content Assistant", - Status = ContentApprovalStatus.Draft, + Status = rowStatus, SubmittedByUserId = userId, SubmittedAt = now, SourceType = "AI", - }); + }; + if (submitForReview) + { + ReviewHistoryHelper.Append(row, "Submitted", ContentApprovalStatus.Draft, ContentApprovalStatus.PendingReview, userId, $"User #{userId}", now); + } + rows.Add(row); } - // TODO: nếu IContentApprovalRequestRepository không có AddRangeAsync, đổi thành - // foreach (var row in rows) await unitOfWork.ContentApprovalRequests.AddAsync(row, cancellationToken); await unitOfWork.ContentApprovalRequests.AddRangeAsync(rows, cancellationToken); await unitOfWork.SaveChangesAsync(cancellationToken); + if (submitForReview && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("ai_content_submitted", cancellationToken); + await sidebarNotifier.NotifyUsersAsync([userId], "ai_content_submitted", cancellationToken); + } return ApiResponse.Success(new SubmitContentApprovalResponse { diff --git a/RikiPath.Application/Services/ContentPlanningService.cs b/RikiPath.Application/Services/ContentPlanningService.cs index 77e0cf2..6c66103 100644 --- a/RikiPath.Application/Services/ContentPlanningService.cs +++ b/RikiPath.Application/Services/ContentPlanningService.cs @@ -6,6 +6,7 @@ using RikiPath.Application.Requests.ContentAuthoring; using RikiPath.Application.Responses; using RikiPath.Application.Responses.ContentAuthoring; +using RikiPath.Application.Services.ContentAuthoring; using RikiPath.Domain.Entities; using RikiPath.Domain.Enums; using System.Net; @@ -35,7 +36,8 @@ public class ContentPlanningService( IAiContentAuthoringClient aiClient, IClaimService claimService, IContentAuthoringService authoringService, - ILogger logger) : IContentPlanningService + ILogger logger, + ISidebarCounterNotifier? sidebarNotifier = null) : IContentPlanningService { private const int MaxPlanTasks = 8; private const int MaxAiAttempts = 2; @@ -1051,26 +1053,38 @@ await unitOfWork.GrammarPatterns.Query().CountAsync(g => !g.IsDeleted && grammar var now = DateTime.UtcNow; var sortOrder = 1; - var rows = planRows.Select(r => new ContentApprovalRequest + var rowStatus = request.SubmitForReview ? ContentApprovalStatus.PendingReview : ContentApprovalStatus.Draft; + var rows = planRows.Select(r => { - BatchId = batchId, - EntityType = r.EntityType, - // TODO: xác nhận lại đúng tên giá trị enum ImportRowAction (New/Modified). - Action = r.IsExisting ? ImportRowAction.Modified : ImportRowAction.New, - TargetEntityId = r.TargetId, - RowKey = r.RowKey, - PayloadJson = JsonSerializer.Serialize(r.Payload, JsonOpts), - SourceRowNumber = sortOrder++, - SourceFileName = "AI Content Assistant (Plan)", - // TODO: xác nhận lại đúng tên giá trị enum ContentApprovalStatus mặc định khi author vừa gửi. - Status = ContentApprovalStatus.Draft, - SubmittedByUserId = userId, - SubmittedAt = now, + var row = new ContentApprovalRequest + { + BatchId = batchId, + EntityType = r.EntityType, + Action = r.IsExisting ? ImportRowAction.Modified : ImportRowAction.New, + TargetEntityId = r.TargetId, + RowKey = r.RowKey, + PayloadJson = JsonSerializer.Serialize(r.Payload, JsonOpts), + SourceRowNumber = sortOrder++, + SourceFileName = "AI Content Assistant (Plan)", + Status = rowStatus, + SubmittedByUserId = userId, + SubmittedAt = now, + SourceType = "AI", + }; + if (request.SubmitForReview) + { + ReviewHistoryHelper.Append(row, "Submitted", ContentApprovalStatus.Draft, ContentApprovalStatus.PendingReview, userId, $"User #{userId}", now); + } + return row; }).ToList(); - // TODO: nếu repo không có AddRangeAsync, đổi thành vòng lặp AddAsync. await unitOfWork.ContentApprovalRequests.AddRangeAsync(rows, cancellationToken); await unitOfWork.SaveChangesAsync(cancellationToken); + if (request.SubmitForReview && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("ai_plan_submitted", cancellationToken); + await sidebarNotifier.NotifyUsersAsync([userId], "ai_plan_submitted", cancellationToken); + } return ApiResponse.Success(new SubmitContentApprovalResponse { diff --git a/RikiPath.Application/Services/ExcelContentImportService.cs b/RikiPath.Application/Services/ExcelContentImportService.cs index 47c964c..bf6eb50 100644 --- a/RikiPath.Application/Services/ExcelContentImportService.cs +++ b/RikiPath.Application/Services/ExcelContentImportService.cs @@ -155,11 +155,21 @@ public async Task> ConfirmAsync( ConfirmImportRequest request, int actorUserId, CancellationToken cancellationToken) { var batchId = request.BatchId ?? Guid.NewGuid(); - var response = ApiResponse.Fail("Không thể lưu bản nháp."); + var response = ApiResponse.Fail("Không thể lưu nội dung."); try { await unitOfWork.ExecuteContentAuthorWriteAsync(actorUserId, async token => response = await SaveDraftsAsync(request, actorUserId, batchId, token), cancellationToken); + if (response.IsSuccess && request.SubmitForReview && response.Result is not null) + { + var submitResult = await manualContent.SubmitBatchAsync(response.Result.BatchId, cancellationToken); + if (!submitResult.IsSuccess) + { + return ApiResponse.Fail( + submitResult.ErrorMessage ?? "Đã lưu dữ liệu nhưng chưa gửi duyệt được. Vui lòng kiểm tra trong Lịch sử nhập liệu.", + (System.Net.HttpStatusCode)submitResult.StatusCode); + } + } return response; } catch (OperationCanceledException) { throw; } diff --git a/RikiPath.Application/Services/KanjiWritingPracticeService.cs b/RikiPath.Application/Services/KanjiWritingPracticeService.cs index 9610052..ffaf0c3 100644 --- a/RikiPath.Application/Services/KanjiWritingPracticeService.cs +++ b/RikiPath.Application/Services/KanjiWritingPracticeService.cs @@ -33,7 +33,7 @@ public async Task>> GetDueForPracticeAsy foreach (var item in dueItems) { var kanji = await unitOfWork.Kanjis.GetByIdAsync(item.KanjiId!.Value, cancellationToken); - if (kanji is not null) + if (kanji is not null && !kanji.IsDeleted && kanji.Status == ContentStatus.Published) result.Add(MapToQueueItem(kanji, isNew: false)); } @@ -54,7 +54,8 @@ public async Task>> GetDueForPracticeAsy .ToHashSet(); var candidates = (await unitOfWork.Kanjis.FindAsync( - k => k.ContentLevelMappings != null && + k => !k.IsDeleted && k.Status == ContentStatus.Published && + k.ContentLevelMappings != null && k.ContentLevelMappings.Any(m => m.CertificateLevelId == targetLevelId.Value && !m.IsDeleted), cancellationToken)) .Where(k => !existingKanjiIds.Contains(k.Id)) @@ -102,7 +103,8 @@ public async Task>> GetAllForPracticeAsy return ApiResponse>.Success([]); var kanjis = (await unitOfWork.Kanjis.FindAsync( - k => k.ContentLevelMappings != null && + k => !k.IsDeleted && k.Status == ContentStatus.Published && + k.ContentLevelMappings != null && k.ContentLevelMappings.Any(m => m.CertificateLevelId == targetLevelId && !m.IsDeleted), cancellationToken)) .OrderBy(k => k.Id) diff --git a/RikiPath.Application/Services/ListeningAudioFilePolicy.cs b/RikiPath.Application/Services/ListeningAudioFilePolicy.cs index 1941bcb..ce30564 100644 --- a/RikiPath.Application/Services/ListeningAudioFilePolicy.cs +++ b/RikiPath.Application/Services/ListeningAudioFilePolicy.cs @@ -6,27 +6,6 @@ public static class ListeningAudioFilePolicy // Keep the limit high enough for the upload flow; each request still accepts one file. public const int MaxBytes = 500 * 1024 * 1024; - public static bool IsSupportedExtension(string? extension) => - string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase) || - string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase); - - public static string GetContentType(string? extension) => - string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase) ? "audio/wav" : "audio/mpeg"; - - public static async Task HasSupportedAudioHeaderAsync(Stream audio, string fileName, CancellationToken ct) => - string.Equals(Path.GetExtension(fileName), ".wav", StringComparison.OrdinalIgnoreCase) - ? await HasWavHeaderAsync(audio, ct) - : await HasMp3HeaderAsync(audio, ct); - - public static async Task HasWavHeaderAsync(Stream audio, CancellationToken ct) - { - var header = new byte[12]; - if (await audio.ReadAtLeastAsync(header, header.Length, false, ct) < header.Length) - return false; - return header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F' && - header[8] == 'W' && header[9] == 'A' && header[10] == 'V' && header[11] == 'E'; - } - public static async Task HasMp3HeaderAsync(Stream audio, CancellationToken ct) { var header = new byte[4]; diff --git a/RikiPath.Application/Services/ManualContentService.cs b/RikiPath.Application/Services/ManualContentService.cs index 370a591..49b8751 100644 --- a/RikiPath.Application/Services/ManualContentService.cs +++ b/RikiPath.Application/Services/ManualContentService.cs @@ -1,10 +1,13 @@ +using System.Globalization; using System.Net; using System.Text.Json; using Microsoft.EntityFrameworkCore; using RikiPath.Application.Handlers; +using RikiPath.Application.Helpers; using RikiPath.Application.IServices; using RikiPath.Application.Responses; using RikiPath.Application.Responses.Content; +using RikiPath.Application.Services.ContentAuthoring; using RikiPath.Domain.Entities; using RikiPath.Domain.Enums; @@ -19,6 +22,556 @@ public sealed class ManualContentService(IUnitOfWork uow, IClaimService claims, private const string ManualSource = "Nhập tay"; private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; + public async Task> SearchUnifiedAsync( + ImportEntityType type, + UnifiedAuthorContentSearchRequest filter, + CancellationToken ct) + { + if (type is not (ImportEntityType.Vocabulary or ImportEntityType.Kanji or ImportEntityType.Grammar or ImportEntityType.Lesson)) + return ApiResponse.Fail("Loại học liệu không hỗ trợ danh sách hợp nhất."); + + var userId = claims.GetUserClaim().Id; + var page = Math.Max(1, filter.Page); + var pageSize = Math.Clamp(filter.PageSize, 1, 100); + + var levels = await uow.CertificateLevels.Query().AsNoTracking() + .Where(x => !x.IsDeleted) + .Select(x => new { x.Id, x.Code }) + .ToDictionaryAsync(x => x.Id, x => x.Code, ct); + + var skills = await uow.LanguageSkills.Query().AsNoTracking() + .Where(x => !x.IsDeleted) + .Select(x => new { x.Id, x.Name }) + .ToDictionaryAsync(x => x.Id, x => x.Name, ct); + + var myRequests = await uow.ContentApprovalRequests.Query().AsNoTracking() + .Where(r => !r.IsDeleted && r.SubmittedByUserId == userId && r.EntityType == type + && r.Status != ContentApprovalStatus.Unpublished) + .OrderByDescending(r => r.ModifiedDate ?? r.CreatedDate ?? r.SubmittedAt) + .ThenByDescending(r => r.Id) + .ToListAsync(ct); + + var ownedEntityIds = (await uow.ContentBankItems.Query().AsNoTracking() + .Where(b => !b.IsDeleted && b.OwnerUserId == userId && b.EntityType == type && b.TargetEntityId.HasValue) + .Select(b => b.TargetEntityId!.Value) + .ToListAsync(ct)).ToHashSet(); + + foreach (var req in myRequests) + { + if (req.Status == ContentApprovalStatus.Approved && req.TargetEntityId is > 0) + ownedEntityIds.Add(req.TargetEntityId.Value); + } + + var legacyApprovedKeys = myRequests + .Where(r => r.Status == ContentApprovalStatus.Approved && !r.TargetEntityId.HasValue && !string.IsNullOrWhiteSpace(r.RowKey)) + .Select(r => r.RowKey.Trim()) + .ToHashSet(StringComparer.Ordinal); + + var proposalByEntityId = new Dictionary(); + var unlinkedActiveRequests = new List(); + + var rows = new List<(UnifiedAuthorContentItem Item, IReadOnlyCollection LevelIds)>(); + + async Task PopulateEntitiesAsync() + { + var liveEntityIds = new HashSet(); + + if (type == ImportEntityType.Vocabulary) + { + var entities = await uow.Vocabularies.Query().AsNoTracking() + .Where(v => !v.IsDeleted && v.Status == ContentStatus.Published) + .Select(v => new + { + v.Id, + v.Word, + v.Reading, + v.Meaning, + v.ExampleSentence, + v.ExampleSentenceMeaning, + v.AudioUrl, + UpdatedAt = v.ModifiedDate ?? v.CreatedDate, + Levels = v.ContentLevelMappings! + .Where(m => !m.IsDeleted && m.CertificateLevel != null && !m.CertificateLevel.IsDeleted) + .OrderBy(m => m.CertificateLevel.SortOrder) + .ThenBy(m => m.CertificateLevelId) + .Select(m => new { m.CertificateLevelId, m.CertificateLevel.Code }) + .ToList(), + }) + .ToListAsync(ct); + + foreach (var e in entities) liveEntityIds.Add(e.Id); + PartitionRequests(myRequests, liveEntityIds, proposalByEntityId, unlinkedActiveRequests); + + foreach (var e in entities) + { + var key = $"{e.Word.Trim()} / {e.Reading.Trim()}"; + var isMine = ownedEntityIds.Contains(e.Id) || legacyApprovedKeys.Contains(key); + proposalByEntityId.TryGetValue(e.Id, out var proposal); + var levelIds = e.Levels.Select(l => l.CertificateLevelId).ToArray(); + var dto = new UnifiedAuthorContentItem + { + CanonicalId = $"entity:{e.Id}", + SourceKind = "Entity", + EntityId = e.Id, + Status = "Approved", + IsMine = isMine, + CertificateLevelId = levelIds.FirstOrDefault(), + JlptLevelName = string.Join(", ", e.Levels.Select(l => l.Code)), + Word = e.Word, + Reading = e.Reading, + Meaning = e.Meaning, + ExampleSentence = e.ExampleSentence, + ExampleSentenceMeaning = e.ExampleSentenceMeaning, + AudioUrl = e.AudioUrl, + UpdatedAt = e.UpdatedAt, + }; + AttachProposal(dto, proposal); + rows.Add((dto, levelIds)); + } + } + else if (type == ImportEntityType.Kanji) + { + var entities = await uow.Kanjis.Query().AsNoTracking() + .Where(k => !k.IsDeleted && k.Status == ContentStatus.Published) + .Select(k => new + { + k.Id, + k.Character, + k.Meaning, + k.SinoVietnamese, + k.OnYomi, + k.KunYomi, + k.StrokeCount, + k.StrokeOrderImageUrl, + k.AudioUrl, + UpdatedAt = k.ModifiedDate ?? k.CreatedDate, + Levels = k.ContentLevelMappings! + .Where(m => !m.IsDeleted && m.CertificateLevel != null && !m.CertificateLevel.IsDeleted) + .OrderBy(m => m.CertificateLevel.SortOrder) + .ThenBy(m => m.CertificateLevelId) + .Select(m => new { m.CertificateLevelId, m.CertificateLevel.Code }) + .ToList(), + }) + .ToListAsync(ct); + + foreach (var e in entities) liveEntityIds.Add(e.Id); + PartitionRequests(myRequests, liveEntityIds, proposalByEntityId, unlinkedActiveRequests); + + foreach (var e in entities) + { + var key = e.Character.Trim(); + var isMine = ownedEntityIds.Contains(e.Id) || legacyApprovedKeys.Contains(key); + proposalByEntityId.TryGetValue(e.Id, out var proposal); + var levelIds = e.Levels.Select(l => l.CertificateLevelId).ToArray(); + var dto = new UnifiedAuthorContentItem + { + CanonicalId = $"entity:{e.Id}", + SourceKind = "Entity", + EntityId = e.Id, + Status = "Approved", + IsMine = isMine, + CertificateLevelId = levelIds.FirstOrDefault(), + JlptLevelName = string.Join(", ", e.Levels.Select(l => l.Code)), + Character = e.Character, + Meaning = e.Meaning, + SinoVietnamese = e.SinoVietnamese, + OnYomi = e.OnYomi, + KunYomi = e.KunYomi, + StrokeCount = e.StrokeCount, + StrokeOrderUrl = e.StrokeOrderImageUrl, + AudioUrl = e.AudioUrl, + UpdatedAt = e.UpdatedAt, + }; + AttachProposal(dto, proposal); + rows.Add((dto, levelIds)); + } + } + else if (type == ImportEntityType.Grammar) + { + var entities = await uow.GrammarPatterns.Query().AsNoTracking() + .Where(g => !g.IsDeleted && g.Status == ContentStatus.Published) + .Select(g => new + { + g.Id, + g.Title, + g.Structure, + g.UsageNotes, + g.ExampleSentence, + g.ExampleSentenceMeaning, + UpdatedAt = g.ModifiedDate ?? g.CreatedDate, + Levels = g.ContentLevelMappings! + .Where(m => !m.IsDeleted && m.CertificateLevel != null && !m.CertificateLevel.IsDeleted) + .OrderBy(m => m.CertificateLevel.SortOrder) + .ThenBy(m => m.CertificateLevelId) + .Select(m => new { m.CertificateLevelId, m.CertificateLevel.Code }) + .ToList(), + }) + .ToListAsync(ct); + + foreach (var e in entities) liveEntityIds.Add(e.Id); + PartitionRequests(myRequests, liveEntityIds, proposalByEntityId, unlinkedActiveRequests); + + foreach (var e in entities) + { + var key = e.Title.Trim(); + var isMine = ownedEntityIds.Contains(e.Id) || legacyApprovedKeys.Contains(key); + proposalByEntityId.TryGetValue(e.Id, out var proposal); + var levelIds = e.Levels.Select(l => l.CertificateLevelId).ToArray(); + var dto = new UnifiedAuthorContentItem + { + CanonicalId = $"entity:{e.Id}", + SourceKind = "Entity", + EntityId = e.Id, + Status = "Approved", + IsMine = isMine, + CertificateLevelId = levelIds.FirstOrDefault(), + JlptLevelName = string.Join(", ", e.Levels.Select(l => l.Code)), + Title = e.Title, + Structure = e.Structure, + Explanation = e.UsageNotes, + ExampleSentence = e.ExampleSentence, + ExampleSentenceMeaning = e.ExampleSentenceMeaning, + UpdatedAt = e.UpdatedAt, + }; + AttachProposal(dto, proposal); + rows.Add((dto, levelIds)); + } + } + else + { + var entities = await uow.Lessons.Query().AsNoTracking() + .Where(l => !l.IsDeleted && l.Status == ContentStatus.Published) + .Select(l => new + { + l.Id, + l.Title, + l.Description, + l.AudioUrl, + l.SortOrder, + l.EstimatedMinutes, + l.CertificateLevelId, + LevelCode = l.CertificateLevel.Code, + l.LanguageSkillId, + SkillName = l.LanguageSkill.Name, + TopicTitle = l.Topic != null && !l.Topic.IsDeleted ? l.Topic.Title : null, + UpdatedAt = l.ModifiedDate ?? l.CreatedDate, + VocabCount = l.LessonVocabularies != null ? l.LessonVocabularies.Count : 0, + KanjiCount = l.LessonKanjis != null ? l.LessonKanjis.Count : 0, + GrammarCount = l.LessonGrammars != null ? l.LessonGrammars.Count : 0, + }) + .ToListAsync(ct); + + foreach (var e in entities) liveEntityIds.Add(e.Id); + PartitionRequests(myRequests, liveEntityIds, proposalByEntityId, unlinkedActiveRequests); + + foreach (var e in entities) + { + var key = $"{e.Title.Trim()} / {e.LevelCode.Trim()}"; + var isMine = ownedEntityIds.Contains(e.Id) || legacyApprovedKeys.Contains(key); + proposalByEntityId.TryGetValue(e.Id, out var proposal); + var dto = new UnifiedAuthorContentItem + { + CanonicalId = $"entity:{e.Id}", + SourceKind = "Entity", + EntityId = e.Id, + Status = "Approved", + IsMine = isMine, + CertificateLevelId = e.CertificateLevelId, + JlptLevelName = e.LevelCode, + LanguageSkillId = e.LanguageSkillId, + SkillName = e.SkillName, + Title = e.Title, + Description = e.Description, + AudioUrl = e.AudioUrl, + TopicTitle = e.TopicTitle, + SortOrder = e.SortOrder, + EstimatedMinutes = e.EstimatedMinutes, + VocabularyCount = e.VocabCount, + KanjiCount = e.KanjiCount, + GrammarCount = e.GrammarCount, + UpdatedAt = e.UpdatedAt, + }; + AttachProposal(dto, proposal); + rows.Add((dto, [e.CertificateLevelId])); + } + } + } + + await PopulateEntitiesAsync(); + + foreach (var req in unlinkedActiveRequests) + { + var reqItem = BuildRequestRow(type, req, levels, skills); + var levelIds = reqItem.CertificateLevelId is > 0 ? [reqItem.CertificateLevelId.Value] : Array.Empty(); + rows.Add((reqItem, levelIds)); + } + + var hasLegacyDrafts = rows.Any(r => + r.Item.Status == "Draft" || r.Item.PendingProposalStatus == "Draft"); + var unfilteredTotal = rows.Count; + + IEnumerable<(UnifiedAuthorContentItem Item, IReadOnlyCollection LevelIds)> filtered = rows; + + if (string.Equals(filter.Scope, "mine", StringComparison.OrdinalIgnoreCase)) + { + filtered = filtered.Where(r => r.Item.IsMine || r.Item.SourceKind == "Request" || r.Item.HasPendingProposal); + } + + var normalizedStatusFilter = NormalizeUnifiedStatusFilter(filter.Status); + if (!string.IsNullOrEmpty(normalizedStatusFilter)) + { + filtered = normalizedStatusFilter switch + { + "Approved" => filtered.Where(r => r.Item.Status == "Approved"), + "PendingReview" => filtered.Where(r => r.Item.Status == "PendingReview" || r.Item.PendingProposalStatus == "PendingReview"), + "ChangesRequested" => filtered.Where(r => r.Item.Status == "ChangesRequested" || r.Item.PendingProposalStatus == "ChangesRequested"), + "Draft" => filtered.Where(r => r.Item.Status == "Draft" || r.Item.PendingProposalStatus == "Draft"), + _ => filtered, + }; + } + + if (filter.JlptLevelId is > 0) + { + var lvlId = filter.JlptLevelId.Value; + filtered = filtered.Where(r => r.LevelIds.Contains(lvlId)); + } + + if (filter.SkillId is > 0) + { + var skillId = filter.SkillId.Value; + filtered = filtered.Where(r => r.Item.LanguageSkillId == skillId); + } + + if (!string.IsNullOrWhiteSpace(filter.Keyword)) + { + var term = filter.Keyword.Trim(); + filtered = filtered.Where(r => MatchesKeyword(r.Item, term)); + } + + var sortKey = (filter.SortBy ?? (type == ImportEntityType.Lesson ? "order" : "recent")).Trim().ToLowerInvariant(); + var sorted = sortKey switch + { + "name" => filtered + .OrderBy(r => PrimarySortText(type, r.Item), StringComparer.Create(CultureInfo.GetCultureInfo("vi-VN"), true)) + .ThenBy(r => r.Item.EntityId ?? r.Item.ApprovalRequestId ?? 0), + "oldest" => filtered + .OrderBy(r => r.Item.UpdatedAt ?? DateTime.MinValue) + .ThenBy(r => r.Item.EntityId ?? r.Item.ApprovalRequestId ?? 0), + "order" when type == ImportEntityType.Lesson => filtered + .OrderBy(r => r.Item.CertificateLevelId ?? int.MaxValue) + .ThenBy(r => r.Item.SortOrder ?? int.MaxValue) + .ThenBy(r => r.Item.Title ?? string.Empty, StringComparer.Create(CultureInfo.GetCultureInfo("vi-VN"), true)), + _ => filtered + .OrderByDescending(r => r.Item.HasPendingProposal || r.Item.SourceKind == "Request" ? 1 : 0) + .ThenByDescending(r => r.Item.UpdatedAt ?? DateTime.MinValue) + .ThenByDescending(r => r.Item.ApprovalRequestId ?? r.Item.EntityId ?? 0), + }; + + var materialized = sorted.Select(r => r.Item).ToList(); + var total = materialized.Count; + var paged = materialized.Skip((page - 1) * pageSize).Take(pageSize).ToList(); + + return ApiResponse.Success(new UnifiedAuthorContentSearchResponse + { + Page = page, + PageSize = pageSize, + TotalCount = total, + UnfilteredTotalCount = unfilteredTotal, + HasLegacyDrafts = hasLegacyDrafts, + Items = paged, + }); + } + + private static void PartitionRequests( + List myRequests, + HashSet liveEntityIds, + Dictionary proposalByEntityId, + List unlinkedActiveRequests) + { + foreach (var req in myRequests) + { + if (req.Status == ContentApprovalStatus.Approved) continue; + if (req.TargetEntityId is int targetId && liveEntityIds.Contains(targetId)) + { + proposalByEntityId.TryAdd(targetId, req); + } + else + { + unlinkedActiveRequests.Add(req); + } + } + } + + private static void AttachProposal(UnifiedAuthorContentItem dto, ContentApprovalRequest? proposal) + { + if (proposal is null) return; + dto.HasPendingProposal = true; + dto.PendingProposalId = proposal.Id; + dto.PendingProposalStatus = NormalizeAuthorStatus(proposal.Status); + dto.ReviewNote = proposal.ReviewNote; + dto.ReviewedByName = proposal.ReviewedByName; + dto.ReviewedAt = proposal.ReviewedAt; + dto.HasReviewFeedback = !string.IsNullOrWhiteSpace(proposal.ReviewNote); + var proposalAt = proposal.ModifiedDate ?? proposal.CreatedDate ?? proposal.SubmittedAt; + if (!dto.UpdatedAt.HasValue || proposalAt > dto.UpdatedAt.Value) + dto.UpdatedAt = proposalAt; + } + + private static UnifiedAuthorContentItem BuildRequestRow( + ImportEntityType type, + ContentApprovalRequest req, + IReadOnlyDictionary levels, + IReadOnlyDictionary skills) + { + var item = new UnifiedAuthorContentItem + { + CanonicalId = $"request:{req.Id}", + SourceKind = "Request", + EntityId = req.TargetEntityId, + ApprovalRequestId = req.Id, + Status = NormalizeAuthorStatus(req.Status), + IsMine = true, + ReviewNote = req.ReviewNote, + ReviewedByName = req.ReviewedByName, + ReviewedAt = req.ReviewedAt, + HasReviewFeedback = !string.IsNullOrWhiteSpace(req.ReviewNote), + UpdatedAt = req.ModifiedDate ?? req.CreatedDate ?? req.SubmittedAt, + }; + + try + { + if (type == ImportEntityType.Vocabulary) + { + var p = JsonSerializer.Deserialize(req.PayloadJson, Json); + if (p is not null) + { + item.CertificateLevelId = p.CertificateLevelId; + item.JlptLevelName = ResolveLevelCode(p.CertificateLevelId, p.CertificateLevelCode, levels); + item.Word = p.Word; + item.Reading = p.Reading; + item.Meaning = p.Meaning; + item.ExampleSentence = p.ExampleSentence; + item.ExampleSentenceMeaning = p.ExampleSentenceMeaning; + item.AudioUrl = p.AudioUrl; + } + } + else if (type == ImportEntityType.Kanji) + { + var p = JsonSerializer.Deserialize(req.PayloadJson, Json); + if (p is not null) + { + item.CertificateLevelId = p.CertificateLevelId; + item.JlptLevelName = ResolveLevelCode(p.CertificateLevelId, p.CertificateLevelCode, levels); + item.Character = p.Character; + item.Meaning = p.Meaning; + item.SinoVietnamese = p.SinoVietnamese; + item.OnYomi = p.OnYomi; + item.KunYomi = p.KunYomi; + item.StrokeCount = p.StrokeCount > 0 ? p.StrokeCount : null; + item.StrokeOrderUrl = p.StrokeOrderImageUrl; + item.AudioUrl = p.AudioUrl; + } + } + else if (type == ImportEntityType.Grammar) + { + var p = JsonSerializer.Deserialize(req.PayloadJson, Json); + if (p is not null) + { + item.CertificateLevelId = p.CertificateLevelId; + item.JlptLevelName = ResolveLevelCode(p.CertificateLevelId, p.CertificateLevelCode, levels); + item.Title = p.Title; + item.Structure = p.Structure; + item.Explanation = p.UsageNotes; + item.ExampleSentence = p.ExampleSentence; + item.ExampleSentenceMeaning = p.ExampleSentenceMeaning; + } + } + else if (type == ImportEntityType.Lesson) + { + var p = JsonSerializer.Deserialize(req.PayloadJson, Json); + if (p is not null) + { + item.CertificateLevelId = p.CertificateLevelId; + item.JlptLevelName = ResolveLevelCode(p.CertificateLevelId, p.CertificateLevelCode, levels); + item.LanguageSkillId = p.LanguageSkillId; + item.SkillName = skills.GetValueOrDefault(p.LanguageSkillId); + item.Title = p.Title; + item.Description = p.Description; + item.AudioUrl = p.AudioUrl; + item.TopicTitle = p.TopicTitle; + item.SortOrder = p.SortOrder; + item.EstimatedMinutes = p.EstimatedMinutes; + } + } + } + catch (JsonException) + { + item.Title ??= req.RowKey; + item.Word ??= req.RowKey; + } + + return item; + } + + private static string ResolveLevelCode(int levelId, string? fallback, IReadOnlyDictionary levels) + { + if (levelId > 0 && levels.TryGetValue(levelId, out var code)) return code; + return fallback ?? string.Empty; + } + + private static string NormalizeAuthorStatus(ContentApprovalStatus status) => status switch + { + ContentApprovalStatus.Approved => "Approved", + ContentApprovalStatus.PendingReview => "PendingReview", + ContentApprovalStatus.ChangesRequested => "ChangesRequested", + ContentApprovalStatus.Rejected => "ChangesRequested", + ContentApprovalStatus.Draft => "Draft", + _ => status.ToString(), + }; + + private static string NormalizeUnifiedStatusFilter(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return string.Empty; + var s = raw.Trim(); + if (s.Equals("ALL", StringComparison.OrdinalIgnoreCase)) return string.Empty; + if (s.Equals("Rejected", StringComparison.OrdinalIgnoreCase) || s.Equals("ChangesRequested", StringComparison.OrdinalIgnoreCase)) + return "ChangesRequested"; + if (s.Equals("Published", StringComparison.OrdinalIgnoreCase) || s.Equals("Approved", StringComparison.OrdinalIgnoreCase)) + return "Approved"; + if (s.Equals("PendingReview", StringComparison.OrdinalIgnoreCase)) return "PendingReview"; + if (s.Equals("Draft", StringComparison.OrdinalIgnoreCase)) return "Draft"; + return s; + } + + private static bool MatchesKeyword(UnifiedAuthorContentItem item, string term) + { + return Contains(item.Word, term) + || Contains(item.Reading, term) + || Contains(item.Meaning, term) + || Contains(item.Character, term) + || Contains(item.SinoVietnamese, term) + || Contains(item.OnYomi, term) + || Contains(item.KunYomi, term) + || Contains(item.Structure, term) + || Contains(item.Title, term) + || Contains(item.Explanation, term) + || Contains(item.Description, term) + || Contains(item.TopicTitle, term) + || Contains(item.ExampleSentence, term) + || Contains(item.ExampleSentenceMeaning, term); + + static bool Contains(string? source, string value) => + !string.IsNullOrWhiteSpace(source) && source.Contains(value, StringComparison.OrdinalIgnoreCase); + } + + private static string PrimarySortText(ImportEntityType type, UnifiedAuthorContentItem item) => type switch + { + ImportEntityType.Vocabulary => item.Word ?? item.Meaning ?? string.Empty, + ImportEntityType.Kanji => item.Character ?? item.Meaning ?? string.Empty, + ImportEntityType.Grammar => item.Structure ?? item.Title ?? string.Empty, + _ => item.Title ?? string.Empty, + }; + public async Task> ListContentBankAsync(ImportEntityType? type, ContentApprovalStatus? status, int page, int pageSize, CancellationToken ct) { @@ -89,7 +642,8 @@ public async Task> GetImportBatchesAsync(Cancel group.Count(item => item.Status == ContentApprovalStatus.Draft), group.Count(item => item.Status == ContentApprovalStatus.PendingReview), group.Count(item => item.Status == ContentApprovalStatus.Approved), - group.Count(item => item.Status == ContentApprovalStatus.Rejected))) + group.Count(item => item.Status == ContentApprovalStatus.Rejected || + item.Status == ContentApprovalStatus.ChangesRequested))) .ToListAsync(ct); } @@ -120,19 +674,40 @@ public async Task> GetAsync(int id, CancellationToken c return ApiResponse.Success(JsonSerializer.SerializeToElement(lesson)); } - public async Task> SaveAsync(ImportEntityType type, int? id, JsonElement input, CancellationToken ct) + public async Task> SaveAsync( + ImportEntityType type, + int? id, + JsonElement input, + CancellationToken ct, + bool submitForReview = false, + int? targetEntityId = null) { var userId = claims.GetUserClaim().Id; - var response = ApiResponse.Fail("Không thể lưu bản nháp."); + var response = ApiResponse.Fail("Không thể lưu nội dung."); await uow.ExecuteContentAuthorWriteAsync(userId, async token => - response = await SaveDraftAsync(type, id, input, userId, token), ct); - if (sidebarNotifier is not null && response.IsSuccess) - await sidebarNotifier.NotifyUsersAsync([userId], "manual_content_draft_saved", ct); + response = await SaveDraftAsync(type, id, input, userId, submitForReview, targetEntityId, token), ct); + if (response.IsSuccess) + { + if (submitForReview) + { + if (notifier is not null) + await notifier.NotifyAdminsOnRequestCreatedAsync(1, ManualSource, ct); + if (sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("manual_content_submitted", ct); + await sidebarNotifier.NotifyUsersAsync([userId], "manual_content_submitted", ct); + } + } + else if (sidebarNotifier is not null) + { + await sidebarNotifier.NotifyUsersAsync([userId], "manual_content_draft_saved", ct); + } + } return response; } private async Task> SaveDraftAsync(ImportEntityType type, int? id, JsonElement input, - int userId, CancellationToken ct) + int userId, bool submitForReview, int? requestedTargetEntityId, CancellationToken ct) { try { @@ -148,6 +723,20 @@ private async Task> SaveDraftAsync(ImportEntityType type, int? if (rowKey.Length > 500) return ApiResponse.Fail("Tên hoặc khóa nội dung quá dài."); var targetId = source?.TargetEntityId is > 0 ? source.TargetEntityId : null; + if (targetId is null && source is null && requestedTargetEntityId is > 0) + { + var targetExists = type switch + { + ImportEntityType.Vocabulary => await uow.Vocabularies.Query().AnyAsync(x => !x.IsDeleted && x.Id == requestedTargetEntityId.Value, ct), + ImportEntityType.Kanji => await uow.Kanjis.Query().AnyAsync(x => !x.IsDeleted && x.Id == requestedTargetEntityId.Value, ct), + ImportEntityType.Grammar => await uow.GrammarPatterns.Query().AnyAsync(x => !x.IsDeleted && x.Id == requestedTargetEntityId.Value, ct), + ImportEntityType.Lesson => await uow.Lessons.Query().AnyAsync(x => !x.IsDeleted && x.Id == requestedTargetEntityId.Value, ct), + _ => false, + }; + if (!targetExists) + return ApiResponse.NotFound("Không tìm thấy học liệu gốc để đề xuất chỉnh sửa."); + targetId = requestedTargetEntityId; + } if (source?.Status == ContentApprovalStatus.Approved && targetId is null) { targetId = await ResolveTargetAsync(type, JsonSerializer.Deserialize(source.PayloadJson), ct); @@ -166,9 +755,13 @@ private async Task> SaveDraftAsync(ImportEntityType type, int? if (open.Any(item => type != ImportEntityType.PracticeExercise || (targetId.HasValue && item.TargetEntityId == targetId) || ReadListInfo(item.PayloadJson)?.CertificateLevelId == ((PracticeExerciseImportPayloadResponse)payload).CertificateLevelId)) - return ApiResponse.Fail("Nội dung này đã có bản nháp hoặc yêu cầu đang chờ duyệt.", HttpStatusCode.Conflict); + return ApiResponse.Fail("Nội dung này đã có yêu cầu đang chờ duyệt hoặc chưa gửi.", HttpStatusCode.Conflict); + + if (submitForReview && payload is PracticeExerciseImportPayloadResponse exercise) + await ValidatePracticeExerciseLinksAsync(exercise, userId, null, null, ct); var now = DateTime.UtcNow; + var priorStatus = source?.Status; var item = source; if (item is null || item.Status == ContentApprovalStatus.Approved) { @@ -189,16 +782,33 @@ private async Task> SaveDraftAsync(ImportEntityType type, int? // The import workflow resolves lesson links by the original title and level. return ApiResponse.Fail("Hãy giữ tên và cấp độ của bài học trong bản nháp Excel để giữ liên kết với nội dung đi kèm."); } + else + { + ReviewHistoryHelper.EnsurePreviousDecisionRecorded(item); + } item.RowKey = rowKey; item.PayloadJson = JsonSerializer.Serialize(payload); item.DiffSummaryJson = payload is LessonImportPayloadResponse { TopicTitle: not null } lesson && targetId.HasValue ? await DescribeTopicChangeAsync(targetId.Value, lesson.TopicTitle, ct) : null; - item.Status = ContentApprovalStatus.Draft; + item.Status = submitForReview ? ContentApprovalStatus.PendingReview : ContentApprovalStatus.Draft; item.ModifiedDate = now; + if (submitForReview) item.SubmittedAt = now; item.ReviewedAt = null; item.ReviewedByName = null; item.ReviewNote = null; + if (submitForReview) + { + var actor = await uow.UserAccounts.Query().AsNoTracking() + .Where(u => u.Id == userId) + .Select(u => new { u.FirstName, u.LastName }) + .FirstOrDefaultAsync(ct); + var actorName = actor is null ? $"User #{userId}" : UserNameHelper.FormatFullName(actor.FirstName, actor.LastName); + var action = priorStatus is (ContentApprovalStatus.Rejected or ContentApprovalStatus.ChangesRequested) + ? "Resubmitted" + : "Submitted"; + ReviewHistoryHelper.Append(item, action, priorStatus, ContentApprovalStatus.PendingReview, userId, actorName, now); + } var naturalKey = ContentBankKey.From(type, rowKey, item.PayloadJson); if (previousNaturalKey is not null && previousNaturalKey != naturalKey) { @@ -216,7 +826,7 @@ private async Task> SaveDraftAsync(ImportEntityType type, int? } bankItem.PayloadJson = item.PayloadJson; bankItem.TargetEntityId = item.TargetEntityId; - bankItem.Status = ContentApprovalStatus.Draft; + bankItem.Status = item.Status; bankItem.LatestBatchId = item.BatchId; if (audioTranscriptions is not null) await audioTranscriptions.QueuePayloadAsync(JsonSerializer.SerializeToElement(payload), userId, ct); @@ -237,15 +847,15 @@ public async Task> SubmitAsync(int id, CancellationToken ct) public async Task> DeleteDraftAsync(int id, CancellationToken ct) { var userId = claims.GetUserClaim().Id; - var result = ApiResponse.NotFound("Không tìm thấy bản nháp."); + var result = ApiResponse.NotFound("Không tìm thấy nội dung."); await uow.ExecuteContentAuthorWriteAsync(userId, async token => { var item = await FindMineAsync(id, token); if (item is null) return; - if (item.Status is not (ContentApprovalStatus.Draft or ContentApprovalStatus.Rejected)) + if (item.Status is not (ContentApprovalStatus.Draft or ContentApprovalStatus.Rejected or ContentApprovalStatus.ChangesRequested)) { result = ApiResponse.Fail( - "Chỉ có thể xóa bản nháp hoặc nội dung bị từ chối.", + "Chỉ có thể xóa nội dung chưa gửi duyệt hoặc cần chỉnh sửa.", HttpStatusCode.Conflict); return; } @@ -348,34 +958,7 @@ private async Task> SubmitLoadedDraftsAsync(List !lesson.IsDeleted && - lesson.Title == exercise.LessonTitle && lesson.CertificateLevelId == exercise.CertificateLevelId, ct)) - { - throw new ArgumentException($"Hãy gửi bài học '{exercise.LessonTitle}' cùng lô hoặc trước bài luyện tập."); - } - } - else if (scope == Domain.Enums.PracticeExerciseScopes.GroupQuiz) - { - var tt = exercise.TopicTitle?.Trim(); - var topicExistsInBatch = !string.IsNullOrWhiteSpace(tt) && topicKeys.Contains((tt, (int?)exercise.CertificateLevelId)); - var topicExistsInDb = !topicExistsInBatch && !string.IsNullOrWhiteSpace(tt) && - await uow.Topics.Query().AnyAsync(t => !t.IsDeleted && t.Title == tt - && (!t.CertificateLevelId.HasValue || t.CertificateLevelId == exercise.CertificateLevelId), ct); - var topicIdExists = !topicExistsInBatch && !topicExistsInDb && exercise.TopicId.HasValue && - await uow.Topics.Query().AnyAsync(t => !t.IsDeleted && t.Id == exercise.TopicId.Value, ct); - if (!topicExistsInBatch && !topicExistsInDb && !topicIdExists) - throw new ArgumentException($"Hãy gửi bài học thuộc chặng '{exercise.TopicTitle}' cùng lô hoặc trước GroupQuiz."); - } - else if (scope == Domain.Enums.PracticeExerciseScopes.StageAssessment && exercise.CertificateLevelId <= 0) - { - throw new ArgumentException("StageAssessment cần cấp độ JLPT hợp lệ."); - } - } + await ValidatePracticeExerciseLinksAsync(exercise, drafts[0].SubmittedByUserId, lessonKeys, topicKeys, ct); } catch (Exception ex) when (ex is JsonException or ArgumentException) { @@ -414,11 +997,60 @@ await uow.ContentBankItems.Query() HttpStatusCode.Conflict); } + private async Task ValidatePracticeExerciseLinksAsync( + PracticeExerciseImportPayloadResponse exercise, + int userId, + HashSet<(string? Title, int? CertificateLevelId)>? batchLessonKeys, + HashSet<(string TopicTitle, int? CertificateLevelId)>? batchTopicKeys, + CancellationToken ct) + { + var scope = Domain.Enums.PracticeExerciseScopes.Normalize(exercise.Scope); + if (scope == Domain.Enums.PracticeExerciseScopes.LessonQuickCheck) + { + var lessonKnown = batchLessonKeys?.Contains((exercise.LessonTitle, exercise.CertificateLevelId)) == true; + if (!lessonKnown) + { + lessonKnown = await uow.Lessons.Query().AnyAsync(lesson => !lesson.IsDeleted && + lesson.Title == exercise.LessonTitle && lesson.CertificateLevelId == exercise.CertificateLevelId, ct); + } + if (!lessonKnown) + { + var pendingPayloads = await uow.ContentApprovalRequests.Query().AsNoTracking() + .Where(item => !item.IsDeleted && item.SubmittedByUserId == userId && + item.EntityType == ImportEntityType.Lesson && + item.Status == ContentApprovalStatus.PendingReview) + .Select(item => item.PayloadJson) + .ToListAsync(ct); + lessonKnown = pendingPayloads + .Select(ReadListInfo) + .Any(info => info?.Title == exercise.LessonTitle && info?.CertificateLevelId == exercise.CertificateLevelId); + } + if (!lessonKnown) + throw new ArgumentException($"Hãy gửi bài học '{exercise.LessonTitle}' trước hoặc cùng bài luyện tập."); + } + else if (scope == Domain.Enums.PracticeExerciseScopes.GroupQuiz) + { + var tt = exercise.TopicTitle?.Trim(); + var topicExistsInBatch = !string.IsNullOrWhiteSpace(tt) && + batchTopicKeys?.Contains((tt, (int?)exercise.CertificateLevelId)) == true; + var topicExistsInDb = !topicExistsInBatch && !string.IsNullOrWhiteSpace(tt) && + await uow.Topics.Query().AnyAsync(t => !t.IsDeleted && t.Title == tt + && (!t.CertificateLevelId.HasValue || t.CertificateLevelId == exercise.CertificateLevelId), ct); + var topicIdExists = !topicExistsInBatch && !topicExistsInDb && exercise.TopicId.HasValue && + await uow.Topics.Query().AnyAsync(t => !t.IsDeleted && t.Id == exercise.TopicId.Value, ct); + if (!topicExistsInBatch && !topicExistsInDb && !topicIdExists) + throw new ArgumentException($"Hãy gửi bài học thuộc chặng '{exercise.TopicTitle}' trước hoặc cùng bài luyện tập."); + } + else if (scope == Domain.Enums.PracticeExerciseScopes.StageAssessment && exercise.CertificateLevelId <= 0) + { + throw new ArgumentException("Bài đánh giá chặng cần cấp độ JLPT hợp lệ."); + } + } + private static bool IsExcelImportDraft(ContentApprovalRequest item) => item.SourceRowNumber > 0 && (item.SourceFileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) || - item.SourceFileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase) || - string.Equals(item.SourceType, "CurriculumV2", StringComparison.OrdinalIgnoreCase)); + item.SourceFileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase)); private static void ValidateStoredImportPayload(ContentApprovalRequest item) { @@ -529,16 +1161,6 @@ private static void ValidateStoredImportPayload(ContentApprovalRequest item) ? exercise.LessonTitle : (!string.IsNullOrEmpty(exercise.TopicTitle) ? exercise.TopicTitle : level.Code); return (exercise, $"{exercise.Title} / {exTarget}"); - case ImportEntityType.SrsCardTemplate: - var srs = Read(input); - srs.CardType = Required(srs.CardType, "Loại thẻ SRS"); - srs.FrontText = Required(srs.FrontText, "Mặt trước thẻ SRS"); - srs.BackText = Required(srs.BackText, "Mặt sau thẻ SRS"); - srs.AudioUrl = MediaUrl(srs.AudioUrl, "URL âm thanh"); - srs.CertificateLevelCode = level.Code; - if (string.IsNullOrWhiteSpace(srs.NormalizedContentKey)) - srs.NormalizedContentKey = $"{level.Code}:{srs.CardType}:{srs.FrontText}"; - return (srs, srs.NormalizedContentKey); default: throw new ArgumentException("Loại nội dung không được hỗ trợ."); } @@ -708,8 +1330,6 @@ await uow.LanguageSkills.Query().Where(x => !x.IsDeleted && x.Id == id).Select(x ImportEntityType.Vocabulary => uow.Vocabularies.Query().Where(x => !x.IsDeleted && x.Word == fields.Word && x.Reading == fields.Reading).Select(x => x.Id), ImportEntityType.Grammar => uow.GrammarPatterns.Query().Where(x => !x.IsDeleted && x.Title == fields.Title).Select(x => x.Id), - ImportEntityType.SrsCardTemplate => uow.SrsCardTemplates.Query().Where(x => !x.IsDeleted - && x.NormalizedContentKey == fields.NormalizedContentKey).Select(x => x.Id), _ => throw new ArgumentException("Loại nội dung không được hỗ trợ.") }; } @@ -748,8 +1368,7 @@ private static string Required(string? value, string label) => string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{label} không được để trống.") : value.Trim(); private sealed record ManualIdentity(string? Title, string? Character, string? Word, string? Reading, - string? LessonTitle, int CertificateLevelId, string? Scope = null, string? TopicTitle = null, - string? NormalizedContentKey = null); + string? LessonTitle, int CertificateLevelId, string? Scope = null, string? TopicTitle = null); internal sealed record ManualListInfo(int? CertificateLevelId, string? TopicTitle, string? Title); } diff --git a/RikiPath.Application/Services/PracticeExerciseService.cs b/RikiPath.Application/Services/PracticeExerciseService.cs index 4574cd4..a25678c 100644 --- a/RikiPath.Application/Services/PracticeExerciseService.cs +++ b/RikiPath.Application/Services/PracticeExerciseService.cs @@ -5,6 +5,7 @@ using RikiPath.Application.Responses; using RikiPath.Application.Responses.PracticeExercises; using RikiPath.Domain.Entities; +using RikiPath.Domain.Enums; namespace RikiPath.Application.Services { @@ -26,7 +27,7 @@ public async Task>> GetByLesso try { var lesson = await unitOfWork.Lessons.GetByIdAsync(lessonId, cancellationToken); - if (lesson is null || lesson.IsDeleted) + if (lesson is null || lesson.IsDeleted || lesson.Status != ContentStatus.Published) return ApiResponse>.NotFound( "Không tìm thấy bài học."); @@ -133,11 +134,16 @@ public async Task> StartAttemptAsync( return ApiResponse.NotFound( "Không tìm thấy bài luyện tập."); - if (exercise.LessonId is int linkedLessonId && - !await LessonPracticeProgress.HasStudiedAsync(unitOfWork, userId, linkedLessonId, cancellationToken)) - return ApiResponse.Fail( - "Hãy đánh dấu đã học xong bài trước khi làm bài luyện tập.", - HttpStatusCode.Conflict, "LESSON_STUDY_REQUIRED"); + if (exercise.LessonId is int linkedLessonId) + { + var linkedLesson = await unitOfWork.Lessons.GetByIdAsync(linkedLessonId, cancellationToken); + if (linkedLesson is null || linkedLesson.IsDeleted || linkedLesson.Status != ContentStatus.Published) + return ApiResponse.NotFound("Không tìm thấy bài học."); + if (!await LessonPracticeProgress.HasStudiedAsync(unitOfWork, userId, linkedLessonId, cancellationToken)) + return ApiResponse.Fail( + "Hãy đánh dấu đã học xong bài trước khi làm bài luyện tập.", + HttpStatusCode.Conflict, "LESSON_STUDY_REQUIRED"); + } var questions = await unitOfWork.PracticeQuestions.FindAsync( question => question.PracticeExerciseId == practiceExerciseId && !question.IsDeleted, diff --git a/RikiPath.Application/Services/SharedBankSearchService.cs b/RikiPath.Application/Services/SharedBankSearchService.cs index 586fa68..739468b 100644 --- a/RikiPath.Application/Services/SharedBankSearchService.cs +++ b/RikiPath.Application/Services/SharedBankSearchService.cs @@ -353,6 +353,97 @@ private static QuestionBankCardResponse MapQuestion(MockQuestion q) }; } + public async Task>> SearchLessonsAsync( + LessonSearchFilter filter, CancellationToken cancellationToken) + { + try + { + Normalize(filter); + var query = unitOfWork.Lessons.Query().AsNoTracking() + .Include(l => l.CertificateLevel) + .Include(l => l.LanguageSkill) + .Include(l => l.Topic) + .Include(l => l.LessonVocabularies) + .Include(l => l.LessonKanjis) + .Include(l => l.LessonGrammars) + .Where(l => !l.IsDeleted && l.Status == Domain.Enums.ContentStatus.Published); + + if (filter.JlptLevelId.HasValue) + query = query.Where(l => l.CertificateLevelId == filter.JlptLevelId.Value); + + if (!string.IsNullOrWhiteSpace(filter.Keyword)) + { + var term = filter.Keyword.Trim().ToLower(); + query = query.Where(l => l.Title.ToLower().Contains(term) || + (l.Description != null && l.Description.ToLower().Contains(term))); + } + + var total = await query.CountAsync(cancellationToken); + var rows = await query + .OrderBy(l => l.CertificateLevelId) + .ThenBy(l => l.SortOrder) + .ThenBy(l => l.Id) + .Skip((filter.Page - 1) * filter.PageSize) + .Take(filter.PageSize) + .ToListAsync(cancellationToken); + + return ApiResponse>.Success(new PagedResult + { + Page = filter.Page, + PageSize = filter.PageSize, + TotalCount = total, + Items = rows.Select(MapLesson).ToList(), + }); + } + catch (Exception ex) + { + return ApiResponse>.Fail( + "Không thể tải thư viện bài học.", HttpStatusCode.InternalServerError, errors: BuildDebugErrors(ex)); + } + } + + public async Task> GetLessonDetailAsync(int id, CancellationToken cancellationToken) + { + try + { + var lesson = await unitOfWork.Lessons.Query().AsNoTracking() + .Include(l => l.CertificateLevel) + .Include(l => l.LanguageSkill) + .Include(l => l.Topic) + .Include(l => l.LessonVocabularies) + .Include(l => l.LessonKanjis) + .Include(l => l.LessonGrammars) + .FirstOrDefaultAsync(l => l.Id == id && !l.IsDeleted && l.Status == Domain.Enums.ContentStatus.Published, cancellationToken); + + return lesson is null + ? ApiResponse.NotFound("Không tìm thấy bài học đã duyệt.") + : ApiResponse.Success(MapLesson(lesson)); + } + catch (Exception ex) + { + return ApiResponse.Fail( + "Không thể tải chi tiết bài học.", HttpStatusCode.InternalServerError, errors: BuildDebugErrors(ex)); + } + } + + private static LessonCardResponse MapLesson(Lesson lesson) => new() + { + Id = lesson.Id, + Title = lesson.Title, + Description = lesson.Description, + SortOrder = lesson.SortOrder, + EstimatedMinutes = lesson.EstimatedMinutes, + CertificateLevelId = lesson.CertificateLevelId, + JlptLevelName = lesson.CertificateLevel?.Code ?? string.Empty, + LanguageSkillId = lesson.LanguageSkillId, + SkillName = lesson.LanguageSkill?.Name ?? string.Empty, + TopicTitle = lesson.Topic?.Title, + LearningObjectives = lesson.LearningObjectives, + VocabularyCount = lesson.LessonVocabularies?.Count ?? 0, + KanjiCount = lesson.LessonKanjis?.Count ?? 0, + GrammarCount = lesson.LessonGrammars?.Count ?? 0, + }; + private static List BuildDebugErrors(Exception ex) { var errors = new List { $"{ex.GetType().Name}: {ex.Message}" }; diff --git a/RikiPath.Application/Services/SrsCardTemplateService.cs b/RikiPath.Application/Services/SrsCardTemplateService.cs index 599f278..99e647b 100644 --- a/RikiPath.Application/Services/SrsCardTemplateService.cs +++ b/RikiPath.Application/Services/SrsCardTemplateService.cs @@ -150,14 +150,20 @@ public async Task> CreateDraftAsync( KanjiId = data.KanjiId, GrammarPatternId = data.GrammarPatternId, NormalizedContentKey = data.NormalizedKey, - Status = ContentStatus.Draft, + Status = request.SubmitForReview ? ContentStatus.PendingReview : ContentStatus.Draft, Version = 1, SubmittedByUserId = authorId, + SubmittedAtUtc = request.SubmitForReview ? utcNow : null, CreatedDate = utcNow, }; await unitOfWork.SrsCardTemplates.AddAsync(entity, cancellationToken); await unitOfWork.SaveChangesAsync(cancellationToken); + if (request.SubmitForReview && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("srs_template_submitted", cancellationToken); + await sidebarNotifier.NotifyUsersAsync([authorId], "srs_template_submitted", cancellationToken); + } var loaded = await unitOfWork.SrsCardTemplates.GetDetailedByIdAsync(entity.Id, cancellationToken) ?? entity; return ApiResponse.Created(Map(loaded)); @@ -176,7 +182,7 @@ public async Task> UpdateDraftAsync( if (!isAdmin && entity.SubmittedByUserId != authorId) return ApiResponse.Fail("Bạn không có quyền chỉnh sửa thẻ mẫu này.", HttpStatusCode.Forbidden); if (!isAdmin && entity.Status is ContentStatus.Published or ContentStatus.PendingReview) - return ApiResponse.Fail("Chỉ có thể chỉnh sửa thẻ ở trạng thái Draft, Rejected hoặc Unpublished.", HttpStatusCode.Conflict); + return ApiResponse.Fail("Chỉ có thể chỉnh sửa thẻ chưa duyệt hoặc cần chỉnh sửa.", HttpStatusCode.Conflict); var validation = await ResolveAndValidateTemplateFieldsAsync(request, cancellationToken); if (!validation.IsSuccess) @@ -211,13 +217,25 @@ public async Task> UpdateDraftAsync( entity.GrammarPatternId = data.GrammarPatternId; entity.NormalizedContentKey = data.NormalizedKey; if (!isAdmin) - entity.Status = ContentStatus.Draft; + { + entity.Status = request.SubmitForReview ? ContentStatus.PendingReview : ContentStatus.Draft; + if (request.SubmitForReview) + { + entity.SubmittedAtUtc = DateTime.UtcNow; + entity.ReviewNote = null; + } + } else if (entity.Status == ContentStatus.Published) entity.Version++; entity.ModifiedDate = DateTime.UtcNow; unitOfWork.SrsCardTemplates.Update(entity); await unitOfWork.SaveChangesAsync(cancellationToken); + if (!isAdmin && request.SubmitForReview && sidebarNotifier is not null) + { + await sidebarNotifier.NotifyAdminsAsync("srs_template_submitted", cancellationToken); + await sidebarNotifier.NotifyUsersAsync([authorId], "srs_template_submitted", cancellationToken); + } return ApiResponse.Success(Map(entity)); } @@ -262,8 +280,8 @@ public async Task> DeleteDraftAsync( return ApiResponse.NotFound("Không tìm thấy thẻ mẫu SRS."); if (!isAdmin && entity.SubmittedByUserId != authorId) return ApiResponse.Fail("Không có quyền xóa thẻ mẫu này.", HttpStatusCode.Forbidden); - if (!isAdmin && entity.Status is not (ContentStatus.Draft or ContentStatus.Rejected)) - return ApiResponse.Fail("Chỉ có thể xóa thẻ ở trạng thái Draft hoặc Rejected.", HttpStatusCode.Conflict); + if (!isAdmin && entity.Status is not (ContentStatus.Draft or ContentStatus.Rejected or ContentStatus.ChangesRequested)) + return ApiResponse.Fail("Chỉ có thể xóa thẻ chưa duyệt hoặc cần chỉnh sửa.", HttpStatusCode.Conflict); entity.IsDeleted = true; entity.ModifiedDate = DateTime.UtcNow; @@ -279,7 +297,7 @@ public async Task> ReviewTemplateAsync( CancellationToken cancellationToken = default) { if (!request.Approve && string.IsNullOrWhiteSpace(request.ReviewNote)) - return ApiResponse.Fail("Vui lòng nhập lý do từ chối thẻ mẫu.", HttpStatusCode.BadRequest); + return ApiResponse.Fail("Vui lòng nhập phản hồi hoặc lý do cần chỉnh sửa.", HttpStatusCode.BadRequest); SrsCardTemplate? updated = null; ApiResponse? error = null; @@ -301,7 +319,9 @@ await unitOfWork.ExecuteInTransactionAsync(async token => var utcNow = DateTime.UtcNow; var beforeJson = JsonSerializer.Serialize(new { entity.Status, entity.Version }); - entity.Status = request.Approve ? ContentStatus.Published : ContentStatus.Rejected; + entity.Status = request.Approve + ? ContentStatus.Published + : (request.RequestChanges ? ContentStatus.ChangesRequested : ContentStatus.Rejected); entity.ReviewedByAdminId = adminId; entity.ReviewedAtUtc = utcNow; entity.ReviewNote = string.IsNullOrWhiteSpace(request.ReviewNote) ? null : request.ReviewNote.Trim(); @@ -318,7 +338,7 @@ await unitOfWork.AdminAuditLogs.AddAsync(new AdminAuditLog ActorUserId = adminId, EntityType = nameof(SrsCardTemplate), EntityId = entity.Id, - Action = request.Approve ? "Approve" : "Reject", + Action = request.Approve ? "Approve" : (request.RequestChanges ? "RequestChanges" : "Reject"), BeforeJson = beforeJson, AfterJson = JsonSerializer.Serialize(new { entity.Status, entity.Version }), Reason = entity.ReviewNote, diff --git a/RikiPath.Domain/Enums/ImportEntityType.cs b/RikiPath.Domain/Enums/ImportEntityType.cs index 9e03ce5..8a61cac 100644 --- a/RikiPath.Domain/Enums/ImportEntityType.cs +++ b/RikiPath.Domain/Enums/ImportEntityType.cs @@ -12,6 +12,5 @@ public enum ImportEntityType QuestionBank, PracticeSet, Passage, - SrsCardTemplate, } } diff --git a/RikiPath.Infrastructure/AppDbContext.cs b/RikiPath.Infrastructure/AppDbContext.cs index 04b46d8..f985590 100644 --- a/RikiPath.Infrastructure/AppDbContext.cs +++ b/RikiPath.Infrastructure/AppDbContext.cs @@ -1,6 +1,5 @@ using Microsoft.EntityFrameworkCore; using RikiPath.Domain.Entities; -using RikiPath.Domain.Enums; using RikiPath.Infrastructure.Configuration; namespace RikiPath.Infrastructure @@ -288,102 +287,5 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new AdminAuditLogConfig()); modelBuilder.ApplyConfiguration(new LearnerFeedbackConfig()); } - - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - SyncLegacyMockShadowProperties(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - - public override Task SaveChangesAsync( - bool acceptAllChangesOnSuccess, - CancellationToken cancellationToken = default) - { - SyncLegacyMockShadowProperties(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - - private void SyncLegacyMockShadowProperties() - { - ChangeTracker.DetectChanges(); - - var nowUnspecified = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified); - - var trackedTests = ChangeTracker.Entries() - .Select(e => e.Entity) - .ToList(); - var testsById = trackedTests - .Where(t => t.Id > 0) - .ToDictionary(t => t.Id); - - var trackedSections = ChangeTracker.Entries() - .Select(e => e.Entity) - .ToList(); - var sectionsById = trackedSections - .Where(s => s.Id > 0) - .ToDictionary(s => s.Id); - - foreach (var entry in ChangeTracker.Entries()) - { - if (entry.State is not (EntityState.Added or EntityState.Modified)) - continue; - - var publishStatusProp = entry.Property("PublishStatus"); - if (publishStatusProp.CurrentValue == 0) - publishStatusProp.CurrentValue = (int)ContentStatus.Published; - - var publishedAtProp = entry.Property("PublishedAt"); - publishedAtProp.CurrentValue ??= nowUnspecified; - } - - foreach (var entry in ChangeTracker.Entries()) - { - if (entry.State is not (EntityState.Added or EntityState.Modified)) - continue; - - var publishStatusProp = entry.Property("PublishStatus"); - if (publishStatusProp.CurrentValue == 0) - publishStatusProp.CurrentValue = (int)ContentStatus.Published; - - var publishedAtProp = entry.Property("PublishedAt"); - publishedAtProp.CurrentValue ??= nowUnspecified; - } - - foreach (var entry in ChangeTracker.Entries()) - { - if (entry.State is not (EntityState.Added or EntityState.Modified)) - continue; - - var question = entry.Entity; - var section = question.MockTestSection - ?? (question.MockTestSectionId is int secId && sectionsById.TryGetValue(secId, out var secById) - ? secById - : null) - ?? trackedSections.FirstOrDefault(s => s.Questions?.Contains(question) == true); - - var mockTest = section?.MockTest - ?? (section is not null && section.MockTestId > 0 && testsById.TryGetValue(section.MockTestId, out var testById) - ? testById - : null) - ?? (section is not null - ? trackedTests.FirstOrDefault(t => t.Sections?.Contains(section) == true) - : null); - - var skillProp = entry.Property("LanguageSkillId"); - if (skillProp.CurrentValue <= 0 && section is not null && section.LanguageSkillId > 0) - skillProp.CurrentValue = section.LanguageSkillId; - - var levelProp = entry.Property("CertificateLevelId"); - if (levelProp.CurrentValue <= 0 && mockTest is not null && mockTest.CertificateLevelId > 0) - levelProp.CurrentValue = mockTest.CertificateLevelId; - - var publishStatusProp = entry.Property("PublishStatus"); - if (publishStatusProp.CurrentValue == 0) - publishStatusProp.CurrentValue = (int)ContentStatus.Published; - - var publishedAtProp = entry.Property("PublishedAt"); - publishedAtProp.CurrentValue ??= nowUnspecified; - } - } } } diff --git a/RikiPath.Infrastructure/Repositories/LessonRepository.cs b/RikiPath.Infrastructure/Repositories/LessonRepository.cs index 2364198..29df13a 100644 --- a/RikiPath.Infrastructure/Repositories/LessonRepository.cs +++ b/RikiPath.Infrastructure/Repositories/LessonRepository.cs @@ -108,7 +108,7 @@ private IQueryable LearnerVisibleLessons() => public async Task<(int Total, int Completed)> GetCompletionStatsAsync(int userId) { - var total = await _context.Lessons.CountAsync(); + var total = await _context.Lessons.CountAsync(l => !l.IsDeleted && l.Status == ContentStatus.Published); var completed = await _context.LessonProgresses .CountAsync(x => x.UserId == userId && x.IsCompleted); diff --git a/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs b/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs index d971180..50133d3 100644 --- a/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs +++ b/RikiPath.Infrastructure/Services/AwsAudioFileStorageService.cs @@ -94,7 +94,7 @@ public bool TryGetContentReference(string reference, out string canonicalUrl) // A filename in Excel is resolved against the selected directory, never guessed as an S3 object. if (!Uri.TryCreate(reference, UriKind.Absolute, out var uri) || uri.Scheme is not ("s3" or "https" or "http") || !TryGetObjectKey(reference, out var key) || IsPrivateKey(key) || - (!key.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) && !key.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))) return false; + !key.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) return false; var prefix = Settings.ContentPrefix.Trim('/') + "/"; if (key.StartsWith(prefix, StringComparison.Ordinal)) { diff --git a/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs b/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs index d52a464..dfb88ed 100644 --- a/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs +++ b/RikiPath.Infrastructure/Services/ContentAudioTranscriptionService.cs @@ -24,9 +24,8 @@ public async Task UploadAsync( Stream audio, string fileName, int authorId, CancellationToken ct) { if (authorId <= 0) throw new ArgumentException("Không xác định được người tải audio."); - var extension = Path.GetExtension(fileName); - if (!ListeningAudioFilePolicy.IsSupportedExtension(extension)) - throw new ArgumentException("Vui lòng chọn file MP3 hoặc WAV."); + if (!Path.GetExtension(fileName).Equals(".mp3", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Vui lòng chọn file MP3."); await using var buffered = new MemoryStream(); var buffer = new byte[81920]; @@ -34,15 +33,14 @@ public async Task UploadAsync( while ((count = await audio.ReadAsync(buffer, ct)) > 0) { if (buffered.Length + count > ListeningAudioFilePolicy.MaxBytes) - throw new ArgumentException("File âm thanh không được vượt quá 500 MB."); + throw new ArgumentException("File MP3 không được vượt quá 500 MB."); await buffered.WriteAsync(buffer.AsMemory(0, count), ct); } buffered.Position = 0; - if (!await ListeningAudioFilePolicy.HasSupportedAudioHeaderAsync(buffered, fileName, ct)) - throw new ArgumentException("File nghe không có định dạng MP3 hoặc WAV hợp lệ."); + if (!await ListeningAudioFilePolicy.HasMp3HeaderAsync(buffered, ct)) + throw new ArgumentException("File nghe không có định dạng MP3 hợp lệ."); buffered.Position = 0; - var contentType = ListeningAudioFilePolicy.GetContentType(extension); - var uploaded = await files.UploadAsync(buffered, fileName, contentType, "jlpt-listening", ct); + var uploaded = await files.UploadAsync(buffered, fileName, "audio/mpeg", "jlpt-listening", ct); try { var transcription = await QueueAsync(uploaded.Url, authorId, ct) @@ -285,7 +283,7 @@ await db.ContentAudioTranscriptions.Where(x => x.Id == item.Id && x.LeaseId == l .SetProperty(x => x.ErrorCode, code) .SetProperty(x => x.ErrorMessage, code == "AUDIO_TRANSCRIPTION_ACCESS_DENIED" ? "AWS chưa cấp đủ quyền đọc audio hoặc nhận dạng tiếng Nhật." - : "Chưa nhận dạng được audio. Kiểm tra file âm thanh (MP3/WAV) và cấu hình AWS rồi thử lại.") + : "Chưa nhận dạng được audio. Kiểm tra file MP3 và cấu hình AWS rồi thử lại.") .SetProperty(x => x.NextAttemptAtUtc, now) .SetProperty(x => x.UpdatedAtUtc, now).SetProperty(x => x.LeaseId, (Guid?)null) .SetProperty(x => x.LeaseExpiresAtUtc, (DateTime?)null), ct); @@ -314,7 +312,7 @@ private ContentAudioTranscriptionResponse Response(ContentAudioTranscription ite uri.Query.Length != 0 || uri.Fragment.Length != 0 || uri.AbsoluteUri.Length > 2048 || !uri.AbsolutePath.StartsWith("/storage/v1/object/public/" + Uri.EscapeDataString(settings.Supabase.Bucket) + "/", StringComparison.Ordinal) || - !ListeningAudioFilePolicy.IsSupportedExtension(Path.GetExtension(uri.AbsolutePath))) + !uri.AbsolutePath.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) return null; return uri.AbsoluteUri; } diff --git a/RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs b/RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs deleted file mode 100644 index 38923f1..0000000 --- a/RikiPath.Infrastructure/Services/CurriculumPackageImportService.cs +++ /dev/null @@ -1,2122 +0,0 @@ -using System.Globalization; -using System.IO.Compression; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Text.RegularExpressions; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using RikiPath.Application; -using RikiPath.Application.Helpers; -using RikiPath.Application.IServices; -using RikiPath.Application.Responses; -using RikiPath.Application.Responses.Content; -using RikiPath.Application.Services; -using RikiPath.Domain.Entities; -using RikiPath.Domain.Enums; - -namespace RikiPath.Infrastructure.Services; - -/// -/// Imports the RikiPath Unified Content V2 + N5–N2 Resource ZIP packages strictly as Draft items -/// in dependency order with deterministic identity keys, idempotent duplicate detection, and asset upload. -/// -public sealed class CurriculumPackageImportService( - IUnitOfWork unitOfWork, - IFileStorageService fileStorage, - IConfiguration configuration, - ILogger logger, - IContentAudioTranscriptionService? audioTranscriptions = null) : ICurriculumPackageImportService -{ - private const string SystemZipName = "RIKIPATH_SYSTEM_INTEGRATION.zip"; - private const string SourceTypeTag = "CurriculumV2"; - private const string PendingRightsStatus = "Pending"; - private static readonly string[] SupportedLevels = ["N5", "N4", "N3", "N2"]; - private static readonly JsonSerializerOptions PascalJson = new(); - private static readonly Regex PythonListRegex = new(@"^\[(.*)\]$", RegexOptions.Compiled | RegexOptions.Singleline); - - private static readonly (string FileName, string? LevelCode)[] ExpectedArchives = - [ - (SystemZipName, null), - ("RIKIPATH_N5_RESOURCES.zip", "N5"), - ("RIKIPATH_N4_RESOURCES.zip", "N4"), - ("RIKIPATH_N3_RESOURCES.zip", "N3"), - ("RIKIPATH_N2_RESOURCES.zip", "N2"), - ]; - - public async Task> GetInventoryAsync(CancellationToken cancellationToken) - { - var root = FindResourcesDirectory(); - var response = new CurriculumPackageInventoryResponse - { - PackageRootFound = root is not null, - PackageRootDisplay = root is null ? null : Path.GetFileName(root), - }; - - if (root is null) - { - response.Warnings.Add("Không tìm thấy thư mục resources chứa gói dữ liệu RIKIPATH_SYSTEM_INTEGRATION.zip."); - return ApiResponse.Success(response); - } - - foreach (var (fileName, levelCode) in ExpectedArchives) - { - var fullPath = Path.Combine(root, fileName); - response.Archives.Add(InspectArchive(fullPath, fileName, levelCode)); - } - - var systemZipPath = Path.Combine(root, SystemZipName); - if (!File.Exists(systemZipPath)) - { - response.Warnings.Add($"Thiếu tệp chính {SystemZipName}."); - return ApiResponse.Success(response); - } - - var dbSnapshot = await LoadDatabaseSnapshotAsync(cancellationToken); - using var systemZip = ZipFile.OpenRead(systemZipPath); - var entries = IndexSafeEntries(systemZip); - - var assetRows = LoadAssetMappings(systemZip, entries); - var srsNodes = ReadJsonArray(systemZip, entries, "01_CORE_COMPATIBLE_DATA/GLOBAL/srs_card_templates.json"); - response.TotalGlobalSrsTemplates = srsNodes.Count; - - foreach (var lvl in SupportedLevels) - { - dbSnapshot.LevelIdByCode.TryGetValue(lvl, out var levelId); - var topics = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/topics.json"); - var lessons = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/lessons.json"); - var vocabs = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/vocabulary.json"); - var kanjis = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/kanji.json"); - var grammars = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/grammar_patterns.json"); - var practices = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/practice_exercises.json"); - var mocks = ReadJsonArray(systemZip, entries, $"01_CORE_COMPATIBLE_DATA/{lvl}/mock_tests_public.json"); - - var lessonCountByTopic = lessons - .GroupBy(l => Str(l, "topicExternalId") ?? "", StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); - - var levelAssets = assetRows.Where(a => a.Level.Equals(lvl, StringComparison.OrdinalIgnoreCase)).ToList(); - var levelSrsCount = srsNodes.Count(s => string.Equals(Str(s, "firstIntroducedLevel"), lvl, StringComparison.OrdinalIgnoreCase)); - - response.Levels.Add(new CurriculumPackageLevelSummary - { - LevelCode = lvl, - CertificateLevelId = levelId > 0 ? levelId : null, - TopicCount = topics.Count, - LessonCount = lessons.Count, - VocabularyCount = vocabs.Count, - KanjiCount = kanjis.Count, - GrammarCount = grammars.Count, - PracticeExerciseCount = practices.Count, - MockTestCount = mocks.Count, - AudioCount = levelAssets.Count(a => a.AssetType.Contains("WAV", StringComparison.OrdinalIgnoreCase)), - ImageCount = levelAssets.Count(a => a.AssetType.Contains("IMAGE", StringComparison.OrdinalIgnoreCase)), - SrsTemplateCount = levelSrsCount, - }); - - foreach (var t in topics.OrderBy(x => IntVal(x, "orderIndex"))) - { - var topicCode = Str(t, "externalStableId") ?? ""; - var chapterLessons = lessonCountByTopic.GetValueOrDefault(topicCode) ?? []; - var publishedCount = 0; - var draftCount = 0; - - foreach (var cl in chapterLessons) - { - var extId = Str(cl, "externalStableId") ?? ""; - var title = Truncate(Str(cl, "titleVi") ?? extId, 300); - var prov = $"{SourceTypeTag}:{extId}"; - if (dbSnapshot.Lessons.Any(l => - l.SourceProvenance == prov || - (levelId > 0 && l.CertificateLevelId == levelId && l.Title.Equals(title, StringComparison.OrdinalIgnoreCase)))) - { - publishedCount++; - } - else if (dbSnapshot.OpenOrApprovedRowKeys.Contains((ImportEntityType.Lesson, extId))) - { - draftCount++; - } - } - - response.Chapters.Add(new CurriculumPackageChapterInfo - { - LevelCode = lvl, - TopicCode = topicCode, - OrderIndex = IntVal(t, "orderIndex"), - TitleVi = Str(t, "titleVi") ?? topicCode, - TitleJa = Str(t, "titleJa"), - Description = Str(t, "description"), - LessonCount = chapterLessons.Count, - ExistingPublishedLessonCount = publishedCount, - ExistingDraftCount = draftCount, - }); - } - } - - return ApiResponse.Success(response); - } - - public async Task> PreviewAsync( - CurriculumPackagePreviewRequest request, - CancellationToken cancellationToken) - { - var root = FindResourcesDirectory(); - if (root is null || !File.Exists(Path.Combine(root, SystemZipName))) - return ApiResponse.Fail("Không tìm thấy gói giáo trình hợp lệ trong thư mục resources."); - - var scope = NormalizeScope(request.Levels, request.TopicCodes, request.MockTestIds, - request.IncludeLessons, request.IncludeVocabKanjiGrammar, request.IncludePracticeExercises, - request.IncludeSrsTemplates, request.IncludeMockTests, request.UploadAssets); - - var built = await BuildPackageCandidatesAsync(root, scope, uploadAssets: false, actorUserId: 0, cancellationToken); - - var pageSize = Math.Clamp(request.PageSize <= 0 ? 25 : request.PageSize, 5, 200); - var totalPages = Math.Max(1, (int)Math.Ceiling(built.Items.Count / (double)pageSize)); - var page = Math.Clamp(request.Page <= 0 ? 1 : request.Page, 1, totalPages); - - var pagedItems = built.Items - .Skip((page - 1) * pageSize) - .Take(pageSize) - .Select(x => x.Preview) - .ToList(); - - var response = new CurriculumPackagePreviewResponse - { - SelectedLevels = scope.Levels, - SelectedTopicCodes = scope.TopicCodes.ToList(), - TotalItems = built.Items.Count, - NewCount = built.Items.Count(x => x.Preview.Action == "New"), - ExistingCount = built.Items.Count(x => x.Preview.Action == "Existing"), - ModifiedCount = built.Items.Count(x => x.Preview.Action == "Modified"), - WarningCount = built.Issues.Count(i => i.Severity == "Warning"), - ErrorCount = built.Issues.Count(i => i.Severity == "Error"), - AudioAssetCount = built.ReferencedAudioKeys.Count, - ImageAssetCount = built.ReferencedImageKeys.Count, - CanConfirm = built.Items.Any(x => x.CanStage && x.Preview.Action != "Existing") && built.Issues.All(i => i.Severity != "Error"), - ByEntityType = built.Items - .GroupBy(x => x.Preview.EntityType) - .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase), - DependencyOrder = - [ - "1. Chủ đề & Bài học (Topic / Lesson)", - "2. Từ vựng, Hán tự, Ngữ pháp & Liên kết bài học", - "3. Bài luyện tập nhanh & Kiểm tra cuối chặng", - "4. Thẻ mẫu SRS", - "5. Đề thi thử JLPT chuẩn (MockTest + Passage + Audio/Illustration)", - ], - Issues = built.Issues.Take(100).ToList(), - Page = page, - PageSize = pageSize, - TotalPages = totalPages, - Items = pagedItems, - }; - - return ApiResponse.Success(response); - } - - public async Task> ConfirmAsync( - CurriculumPackageConfirmRequest request, - int actorUserId, - CancellationToken cancellationToken) - { - if (actorUserId <= 0) - return ApiResponse.Fail("Không xác định được tài khoản tác giả nội dung."); - - var root = FindResourcesDirectory(); - if (root is null || !File.Exists(Path.Combine(root, SystemZipName))) - return ApiResponse.Fail("Không tìm thấy gói giáo trình hợp lệ trong thư mục resources."); - - if (!string.IsNullOrWhiteSpace(request.IdempotencyKey)) - { - var idemKey = Truncate(request.IdempotencyKey.Trim(), 100); - var existingByIdem = await unitOfWork.ContentApprovalRequests.Query() - .AsNoTracking() - .Where(x => !x.IsDeleted && x.SubmittedByUserId == actorUserId && x.IdempotencyKey == idemKey) - .ToListAsync(cancellationToken); - if (existingByIdem.Count > 0) - { - return ApiResponse.Success(new CurriculumPackageConfirmResponse - { - BatchId = existingByIdem[0].BatchId, - Status = "Draft", - PublishedReady = false, - RightsStatus = PendingRightsStatus, - DraftsCreatedCount = 0, - SkippedExistingCount = existingByIdem.Count, - CreatedRequestIds = existingByIdem.Select(x => x.Id).ToList(), - ByEntityType = existingByIdem.GroupBy(x => x.EntityType.ToString()) - .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase), - Warnings = ["Yêu cầu đã được xử lý trước đó (IdempotencyKey trùng khớp). Không tạo bản sao mới."], - }); - } - } - - var scope = NormalizeScope(request.Levels, request.TopicCodes, request.MockTestIds, - request.IncludeLessons, request.IncludeVocabKanjiGrammar, request.IncludePracticeExercises, - request.IncludeSrsTemplates, request.IncludeMockTests, request.UploadAssets); - - var built = await BuildPackageCandidatesAsync(root, scope, scope.UploadAssets, actorUserId, cancellationToken); - var fatalErrors = built.Issues.Where(i => i.Severity == "Error").ToList(); - if (fatalErrors.Count > 0) - { - return ApiResponse.Fail( - $"Phát hiện {fatalErrors.Count} lỗi cấu trúc gói dữ liệu: {fatalErrors[0].Target} — {fatalErrors[0].Message}"); - } - - var batchId = Guid.NewGuid(); - var now = DateTime.UtcNow; - var scopeLabel = scope.TopicCodes.Count > 0 - ? $"{string.Join(",", scope.Levels)}:{string.Join(",", scope.TopicCodes.Take(4))}" - : string.Join(",", scope.Levels); - var sourceFileName = Truncate($"CurriculumV2:{scopeLabel}", 260); - var trimmedIdemKey = string.IsNullOrWhiteSpace(request.IdempotencyKey) ? null : Truncate(request.IdempotencyKey.Trim(), 100); - - var drafts = new List(); - var skippedCount = 0; - - foreach (var candidate in built.Items) - { - if (!candidate.CanStage || candidate.Action == ImportRowAction.Unchanged || candidate.PayloadJson is null) - { - skippedCount++; - continue; - } - - var key = Truncate(candidate.Preview.RowKey, 500); - if (built.Snapshot.OpenOrApprovedRowKeys.Contains((candidate.EntityType, key))) - { - skippedCount++; - continue; - } - if (candidate.TargetEntityId.HasValue && - built.Snapshot.OpenTargetIds.Contains((candidate.EntityType, candidate.TargetEntityId.Value))) - { - skippedCount++; - continue; - } - - built.Snapshot.OpenOrApprovedRowKeys.Add((candidate.EntityType, key)); - if (candidate.TargetEntityId.HasValue) - built.Snapshot.OpenTargetIds.Add((candidate.EntityType, candidate.TargetEntityId.Value)); - - drafts.Add(new ContentApprovalRequest - { - BatchId = batchId, - EntityType = candidate.EntityType, - Action = candidate.Action, - TargetEntityId = candidate.Action == ImportRowAction.Modified ? candidate.TargetEntityId : null, - RowKey = key, - SourceRowNumber = drafts.Count + 1, - SourceFileName = sourceFileName, - SourceType = SourceTypeTag, - SourceReference = Truncate(candidate.Preview.ExternalId, 300), - RightsStatus = PendingRightsStatus, - RightsConfirmed = false, - IdempotencyKey = drafts.Count == 0 ? trimmedIdemKey : null, - PayloadJson = candidate.PayloadJson, - Status = ContentApprovalStatus.Draft, - SubmittedByUserId = actorUserId, - SubmittedAt = now, - }); - } - - if (drafts.Count > 0) - { - await unitOfWork.ContentApprovalRequests.AddRangeAsync(drafts, cancellationToken); - await SyncContentBankDraftsAsync(drafts, actorUserId, batchId, cancellationToken); - await unitOfWork.SaveChangesAsync(cancellationToken); - } - - return ApiResponse.Success(new CurriculumPackageConfirmResponse - { - BatchId = batchId, - Status = "Draft", - PublishedReady = false, - RightsStatus = PendingRightsStatus, - DraftsCreatedCount = drafts.Count, - SkippedExistingCount = skippedCount, - UploadedAudioCount = built.UploadedAudioCount, - UploadedImageCount = built.UploadedImageCount, - CreatedRequestIds = drafts.Select(d => d.Id).ToList(), - ByEntityType = drafts.GroupBy(d => d.EntityType.ToString()) - .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase), - Warnings = built.Issues.Where(i => i.Severity == "Warning") - .Select(i => $"{i.Target}: {i.Message}") - .Distinct() - .Take(25) - .ToList(), - }); - } - - private async Task BuildPackageCandidatesAsync( - string resourcesRoot, - PackageScope scope, - bool uploadAssets, - int actorUserId, - CancellationToken ct) - { - var result = new BuiltPackageResult(await LoadDatabaseSnapshotAsync(ct)); - using var systemZip = ZipFile.OpenRead(Path.Combine(resourcesRoot, SystemZipName)); - var sysEntries = IndexSafeEntries(systemZip); - - var pathResolver = ReadAssetMappingsResolver(systemZip, sysEntries); - var csvAssets = LoadAssetMappings(systemZip, sysEntries); - var kaiwaByLesson = LoadKaiwaByLesson(systemZip, sysEntries); - var srsNodes = scope.IncludeSrsTemplates - ? ReadJsonArray(systemZip, sysEntries, "01_CORE_COMPATIBLE_DATA/GLOBAL/srs_card_templates.json") - : []; - - // Open level resource ZIPs lazily as needed. - var resourceZips = new Dictionary Entries, Dictionary ByFileName)>(StringComparer.OrdinalIgnoreCase); - var uploadedUrlCache = new Dictionary(StringComparer.OrdinalIgnoreCase); - - try - { - foreach (var levelCode in scope.Levels) - { - if (!result.Snapshot.LevelIdByCode.TryGetValue(levelCode, out var levelId)) - { - result.Issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Error", - Code = "LEVEL_NOT_FOUND", - Target = levelCode, - Message = $"Cấp độ {levelCode} chưa được kích hoạt trong DB.", - }); - continue; - } - - var topics = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/topics.json"); - var selectedTopics = topics - .Where(t => scope.TopicCodes.Count == 0 || scope.TopicCodes.Contains(Str(t, "externalStableId") ?? "")) - .OrderBy(t => IntVal(t, "orderIndex")) - .ToList(); - var topicMap = selectedTopics.ToDictionary( - t => Str(t, "externalStableId") ?? "", - t => t, - StringComparer.OrdinalIgnoreCase); - - var allLessons = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lessons.json"); - var selectedLessons = allLessons - .Where(l => topicMap.ContainsKey(Str(l, "topicExternalId") ?? "")) - .OrderBy(l => IntVal(l, "orderIndex")) - .ToList(); - var selectedLessonIds = selectedLessons - .Select(l => Str(l, "externalStableId") ?? "") - .Where(id => id.Length > 0) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - var resTuple = OpenLevelResourceZip(resourcesRoot, levelCode, resourceZips); - var richData = ExtractRichCurriculumData(levelCode, resTuple?.Zip, resTuple?.Entries); - - var lessonTitleByExtId = selectedLessons.ToDictionary( - l => Str(l, "externalStableId") ?? "", - l => Truncate(Str(l, "titleVi") ?? Str(l, "externalStableId") ?? "", 300), - StringComparer.OrdinalIgnoreCase); - - var lvLinks = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lesson_vocabulary.json"); - var lkLinks = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lesson_kanji.json"); - var lgLinks = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/lesson_grammar.json"); - - var primaryLessonForVocab = FirstLessonLookup(lvLinks, "vocabularyExternalId", selectedLessonIds, lessonTitleByExtId); - var primaryLessonForKanji = FirstLessonLookup(lkLinks, "kanjiExternalId", selectedLessonIds, lessonTitleByExtId); - var primaryLessonForGrammar = FirstLessonLookup(lgLinks, "grammarExternalId", selectedLessonIds, lessonTitleByExtId); - - var assetByLesson = csvAssets - .Where(a => a.Level.Equals(levelCode, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(a.LinkedLessonId)) - .GroupBy(a => a.LinkedLessonId!, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); - - // Helper to resolve + optionally upload asset inside the level ZIPs. - async Task<(string? Url, string? LogicalRef)> ResolveMediaAsync(string? logicalOrRelativePath, bool isAudio) - { - if (string.IsNullOrWhiteSpace(logicalOrRelativePath)) return (null, null); - var (zipArchive, entry) = LocateZipEntry(logicalOrRelativePath, levelCode, pathResolver, resourceZips); - if (zipArchive is null || entry is null) - { - result.Issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Warning", - Code = "ASSET_NOT_FOUND", - Target = logicalOrRelativePath, - Message = "Không tìm thấy tệp tài nguyên tương ứng trong gói nén RESOURCES.", - }); - return (null, logicalOrRelativePath); - } - - var cacheKey = $"{zipArchive.GetHashCode()}:{entry.FullName}"; - if (isAudio) result.ReferencedAudioKeys.Add(entry.FullName); - else result.ReferencedImageKeys.Add(entry.FullName); - - if (!uploadAssets) - return (null, entry.FullName); - - if (uploadedUrlCache.TryGetValue(cacheKey, out var cached)) - return (cached, entry.FullName); - - var url = await UploadZipEntryAsync(entry, isAudio, actorUserId, ct); - uploadedUrlCache[cacheKey] = url; - if (isAudio) result.UploadedAudioCount++; - else result.UploadedImageCount++; - return (url, entry.FullName); - } - - // 1. Lessons (Dependency 1 — Lesson creates Topic & links Knowledge + QuickCheck in ContentApprovalService) - var globalSortOffsetByTopic = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (scope.IncludeLessons) - { - var vocabMapForPrompt = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/vocabulary.json") - .GroupBy(v => Str(v, "externalStableId") ?? "", StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - - foreach (var l in selectedLessons) - { - var extId = Str(l, "externalStableId") ?? ""; - var topicExtId = Str(l, "topicExternalId") ?? ""; - topicMap.TryGetValue(topicExtId, out var topicJson); - var topicTitle = Truncate(Str(topicJson, "titleVi") ?? topicExtId, 300); - var title = Truncate(Str(l, "titleVi") ?? extId, 300); - JsonElement? richLesson = richData.LessonsById.TryGetValue(extId, out var rl) ? rl : null; - - var audioPath = assetByLesson.GetValueOrDefault(extId)?.FirstOrDefault(a => a.AssetType.Contains("WAV", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath - ?? FirstResolvedAudio(richLesson); - var (audioUrl, audioDisplay) = await ResolveMediaAsync(audioPath, isAudio: true); - - var lessonImgPath = assetByLesson.GetValueOrDefault(extId)?.FirstOrDefault(a => a.AssetType.Contains("IMAGE", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath; - var (imageUrl, imgDisplay) = await ResolveMediaAsync(lessonImgPath, isAudio: false); - - var orderInChapter = IntVal(l, "orderIndex"); - var chapterOrder = IntVal(topicJson, "orderIndex"); - var globalSort = chapterOrder * 100 + Math.Max(1, orderInChapter); - globalSortOffsetByTopic[topicExtId] = globalSort; - - var prereqTitle = ResolvePrerequisiteTitle(richLesson, lessonTitleByExtId); - var kaiwaList = kaiwaByLesson.GetValueOrDefault(extId) ?? []; - var description = BuildLessonMarkdown(l, richLesson, kaiwaList, vocabMapForPrompt); - var objectives = BuildLearningObjectives(richLesson, l); - - var skillId = ResolveSkillId(result.Snapshot, Str(l, "primaryLanguageSkillRef") ?? Str(l, "lessonType")); - var payload = new LessonImportPayloadResponse - { - Title = title, - Description = description, - AudioUrl = audioUrl, - ImageUrl = imageUrl, - SortOrder = globalSort, - EstimatedMinutes = Math.Max(10, IntVal(richLesson, "estimatedDurationMinutes", 25)), - LearningObjectives = TruncateNullable(objectives, 1000), - PrerequisiteLessonTitle = prereqTitle, - SourceProvenance = Truncate($"{SourceTypeTag}:{extId}", 300), - CertificateLevelId = levelId, - CertificateLevelCode = levelCode, - LanguageSkillId = skillId, - TopicTitle = topicTitle, - StageCode = TruncateNullable(topicExtId, 60), - StageSortOrder = chapterOrder + 1, - StageObjectives = TruncateNullable(Str(topicJson, "description"), 1000), - }; - - var existingLesson = FindExistingLesson(result.Snapshot, payload.SourceProvenance, title, levelId); - AddCandidate( - result, - ImportEntityType.Lesson, - extId, - levelCode, - topicExtId, - extId, - title, - existingLesson?.Id, - JsonSerializer.Serialize(payload, PascalJson), - audioDisplay, - imgDisplay, - richLesson is not null && richLesson.Value.TryGetProperty("practiceQuestions", out var pq) && pq.ValueKind == JsonValueKind.Array ? pq.GetArrayLength() : 0); - } - } - - // 2. Vocabulary, Kanji, Grammar (Dependency 2 — auto-linked to Lesson via LessonTitle in ContentApprovalService) - var selectedVocabItems = new List(); - var selectedKanjiItems = new List(); - var selectedGrammarItems = new List(); - - if (scope.IncludeVocabKanjiGrammar || scope.IncludeSrsTemplates) - { - var allVocab = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/vocabulary.json"); - var allKanji = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/kanji.json"); - var allGrammar = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/grammar_patterns.json"); - - var linkedVocabIds = lvLinks.Where(x => selectedLessonIds.Contains(Str(x, "lessonExternalId") ?? "")) - .Select(x => Str(x, "vocabularyExternalId") ?? "").ToHashSet(StringComparer.OrdinalIgnoreCase); - var linkedKanjiIds = lkLinks.Where(x => selectedLessonIds.Contains(Str(x, "lessonExternalId") ?? "")) - .Select(x => Str(x, "kanjiExternalId") ?? "").ToHashSet(StringComparer.OrdinalIgnoreCase); - var linkedGrammarIds = lgLinks.Where(x => selectedLessonIds.Contains(Str(x, "lessonExternalId") ?? "")) - .Select(x => Str(x, "grammarExternalId") ?? "").ToHashSet(StringComparer.OrdinalIgnoreCase); - - selectedVocabItems = scope.TopicCodes.Count > 0 - ? allVocab.Where(x => linkedVocabIds.Contains(Str(x, "externalStableId") ?? "")).ToList() - : allVocab; - selectedKanjiItems = scope.TopicCodes.Count > 0 - ? allKanji.Where(x => linkedKanjiIds.Contains(Str(x, "externalStableId") ?? "")).ToList() - : allKanji; - selectedGrammarItems = scope.TopicCodes.Count > 0 - ? allGrammar.Where(x => linkedGrammarIds.Contains(Str(x, "externalStableId") ?? "")).ToList() - : allGrammar; - } - - if (scope.IncludeVocabKanjiGrammar) - { - var seenVocabNatural = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var v in selectedVocabItems) - { - var extId = Str(v, "externalStableId") ?? ""; - var word = Truncate(Str(v, "Word") ?? "", 200); - var reading = Truncate(string.IsNullOrWhiteSpace(Str(v, "Reading")) ? word : Str(v, "Reading")!, 200); - var meaning = Truncate(Str(v, "Meaning") ?? "", 300); - if (word.Length == 0 || meaning.Length == 0) continue; - - var natural = $"{word}\u001f{reading}"; - if (!seenVocabNatural.Add(natural)) continue; - - primaryLessonForVocab.TryGetValue(extId, out var lessonTitle); - var existingId = result.Snapshot.VocabIdByWordReading.TryGetValue(natural, out var vid) ? vid : (int?)null; - - var payload = new VocabularyImportPayloadResponse - { - Word = word, - Reading = reading, - Meaning = meaning, - ExampleSentence = TruncateNullable(Str(v, "ExampleSentence"), 1000), - ExampleSentenceMeaning = TruncateNullable(Str(v, "ExampleSentenceMeaning"), 1000), - AudioUrl = TruncateNullable(Str(v, "AudioUrl"), 1000), - ImageUrl = TruncateNullable(Str(v, "ImageUrl"), 1000), - CertificateLevelCode = levelCode, - CertificateLevelId = levelId, - LessonTitle = lessonTitle, - }; - - AddCandidate(result, ImportEntityType.Vocabulary, extId, levelCode, null, extId, - $"{word} ({reading})", existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0, - skipIfAlreadyLinkedToLesson: existingId.HasValue && lessonTitle is not null && - result.Snapshot.LessonVocabPairs.Contains((lessonTitle, levelId, existingId.Value))); - } - - var seenKanjiChars = new HashSet(StringComparer.Ordinal); - foreach (var k in selectedKanjiItems) - { - var extId = Str(k, "externalStableId") ?? ""; - var ch = Truncate(Str(k, "Character") ?? "", 10); - var meaning = Truncate(Str(k, "Meaning") ?? "", 300); - if (ch.Length == 0 || meaning.Length == 0) continue; - if (!seenKanjiChars.Add(ch)) continue; - - primaryLessonForKanji.TryGetValue(extId, out var lessonTitle); - var existingId = result.Snapshot.KanjiIdByChar.TryGetValue(ch, out var kid) ? kid : (int?)null; - - var payload = new KanjiImportPayloadResponse - { - Character = ch, - Meaning = meaning, - SinoVietnamese = TruncateNullable(Str(k, "SinoVietnamese"), 100), - OnYomi = TruncateNullable(CleanPythonList(Str(k, "OnYomi")), 200), - KunYomi = TruncateNullable(CleanPythonList(Str(k, "KunYomi")), 200), - StrokeCount = Math.Max(1, IntVal(k, "StrokeCount", 1)), - StrokeOrderImageUrl = TruncateNullable(Str(k, "StrokeOrderImageUrl"), 500), - AudioUrl = TruncateNullable(Str(k, "AudioUrl"), 500), - CertificateLevelCode = levelCode, - CertificateLevelId = levelId, - LessonTitle = lessonTitle, - }; - - AddCandidate(result, ImportEntityType.Kanji, extId, levelCode, null, extId, - $"{ch} — {meaning}", existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0, - skipIfAlreadyLinkedToLesson: existingId.HasValue && lessonTitle is not null && - result.Snapshot.LessonKanjiPairs.Contains((lessonTitle, levelId, existingId.Value))); - } - - var seenGrammarTitles = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var g in selectedGrammarItems) - { - var extId = Str(g, "externalStableId") ?? ""; - var title = Truncate(Str(g, "Title") ?? "", 300); - var structure = Truncate(string.IsNullOrWhiteSpace(Str(g, "Structure")) ? title : Str(g, "Structure")!, 300); - if (title.Length == 0) continue; - if (!seenGrammarTitles.Add(title)) continue; - - primaryLessonForGrammar.TryGetValue(extId, out var lessonTitle); - var existingId = result.Snapshot.GrammarIdByTitle.TryGetValue(title, out var gid) ? gid : (int?)null; - - var payload = new GrammarImportPayloadResponse - { - Title = title, - Structure = structure, - UsageNotes = TruncateNullable(Str(g, "UsageNotes"), 2000), - ExampleSentence = TruncateNullable(Str(g, "ExampleSentence"), 1000), - ExampleSentenceMeaning = TruncateNullable(Str(g, "ExampleSentenceMeaning"), 1000), - CertificateLevelCode = levelCode, - CertificateLevelId = levelId, - LessonTitle = lessonTitle, - }; - - AddCandidate(result, ImportEntityType.Grammar, extId, levelCode, null, extId, - title, existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0, - skipIfAlreadyLinkedToLesson: existingId.HasValue && lessonTitle is not null && - result.Snapshot.LessonGrammarPairs.Contains((lessonTitle, levelId, existingId.Value))); - } - } - - // 3. Practice Exercises (LessonQuickCheck + GroupQuiz) - if (scope.IncludePracticeExercises) - { - foreach (var l in selectedLessons) - { - var extId = Str(l, "externalStableId") ?? ""; - var topicExtId = Str(l, "topicExternalId") ?? ""; - if (!richData.LessonsById.TryGetValue(extId, out var richLesson)) continue; - var parsedQuestions = ExtractPracticeQuestions(richLesson, extId, result.Issues); - if (parsedQuestions.Count == 0) continue; - - lessonTitleByExtId.TryGetValue(extId, out var lessonTitle); - var exRowKey = $"{extId}-PRACTICE"; - var exTitle = Truncate($"Luyện tập nhanh: {lessonTitle}", 300); - var existingId = result.Snapshot.ExerciseIdByLevelTitle.TryGetValue((levelId, exTitle), out var peId) ? peId : (int?)null; - var skillId = ResolveSkillId(result.Snapshot, Str(l, "primaryLanguageSkillRef") ?? Str(l, "lessonType")); - - var payload = new PracticeExerciseImportPayloadResponse - { - Title = exTitle, - Description = TruncateNullable($"Bài luyện tập củng cố kiến thức cho {lessonTitle}.", 1000), - SortOrder = Math.Max(1, IntVal(l, "orderIndex")), - Scope = PracticeExerciseScopes.LessonQuickCheck, - PassingScorePercent = 70, - LessonTitle = lessonTitle ?? "", - CertificateLevelId = levelId, - CertificateLevelCode = levelCode, - LanguageSkillId = skillId, - LanguageSkillName = result.Snapshot.SkillNameById.GetValueOrDefault(skillId, "Vocabulary"), - Questions = parsedQuestions, - }; - - AddCandidate(result, ImportEntityType.PracticeExercise, exRowKey, levelCode, topicExtId, exRowKey, - exTitle, existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, parsedQuestions.Count); - } - - foreach (var t in selectedTopics) - { - var topicCode = Str(t, "externalStableId") ?? ""; - if (!richData.ChapterAssessmentsById.TryGetValue(topicCode, out var assessJson)) continue; - var assessQuestions = ExtractPracticeQuestions(assessJson, topicCode, result.Issues); - if (assessQuestions.Count == 0) continue; - - var assessId = Str(assessJson, "assessmentId") ?? $"{topicCode}-ASSESS"; - var topicTitle = Truncate(Str(t, "titleVi") ?? topicCode, 300); - var exTitle = Truncate(Str(assessJson, "titleVi") ?? $"Kiểm tra cuối chương {topicCode}: {topicTitle}", 300); - var existingId = result.Snapshot.ExerciseIdByLevelTitle.TryGetValue((levelId, exTitle), out var peId) ? peId : (int?)null; - var grammarSkillId = ResolveSkillId(result.Snapshot, "Grammar"); - - var payload = new PracticeExerciseImportPayloadResponse - { - Title = exTitle, - Description = TruncateNullable($"Đánh giá tổng hợp chặng {topicCode} ({topicTitle}).", 1000), - SortOrder = (IntVal(t, "orderIndex") + 1) * 100, - Scope = PracticeExerciseScopes.GroupQuiz, - PassingScorePercent = Math.Max(50, IntVal(assessJson, "passingScorePercent", 75)), - LessonTitle = string.Empty, - TopicTitle = topicTitle, - CertificateLevelId = levelId, - CertificateLevelCode = levelCode, - LanguageSkillId = grammarSkillId, - LanguageSkillName = result.Snapshot.SkillNameById.GetValueOrDefault(grammarSkillId, "Grammar"), - Questions = assessQuestions, - }; - - AddCandidate(result, ImportEntityType.PracticeExercise, assessId, levelCode, topicCode, assessId, - exTitle, existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, assessQuestions.Count); - } - } - - // 4. SRS Card Templates - if (scope.IncludeSrsTemplates && srsNodes.Count > 0) - { - var matchGlobalIds = selectedVocabItems.Select(x => Str(x, "externalStableId") ?? "") - .Concat(selectedKanjiItems.Select(x => Str(x, "externalStableId") ?? "")) - .Concat(selectedGrammarItems.Select(x => Str(x, "externalStableId") ?? "")) - .Where(x => x.Length > 0) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - var matchFrontTexts = selectedVocabItems.Select(x => Str(x, "Word") ?? "") - .Concat(selectedKanjiItems.Select(x => Str(x, "Character") ?? "")) - .Concat(selectedGrammarItems.Select(x => Str(x, "Title") ?? "")) - .Where(x => x.Length > 0) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - var seenNormKeys = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var s in srsNodes) - { - if (!string.Equals(Str(s, "firstIntroducedLevel"), levelCode, StringComparison.OrdinalIgnoreCase)) continue; - var canonicalId = Str(s, "canonicalGlobalId") ?? ""; - var frontJa = Str(s, "frontTextJa") ?? ""; - if (scope.TopicCodes.Count > 0 && !matchGlobalIds.Contains(canonicalId) && !matchFrontTexts.Contains(frontJa)) - continue; - - var extId = Str(s, "externalStableId") ?? ""; - var rawType = (Str(s, "knowledgeType") ?? "VOCABULARY").ToUpperInvariant(); - var cardType = rawType switch - { - "KANJI" => "Kanji", - "GRAMMAR" => "Grammar", - _ => "Vocabulary", - }; - var front = Truncate(frontJa, 500); - var back = Truncate(Str(s, "backMeaningVi") ?? "", 1000); - if (front.Length == 0 || back.Length == 0) continue; - - var normKey = Truncate($"{levelCode}:{cardType}:{front}", 300); - if (!seenNormKeys.Add(normKey)) continue; - - var reading = cardType == "Kanji" - ? CleanPythonList(Str(s, "frontReadingKana")) - : Str(s, "frontReadingKana"); - - var payload = new SrsCardTemplateImportPayloadResponse - { - CardType = cardType, - FrontText = front, - BackText = back, - Reading = TruncateNullable(reading, 300), - Meaning = TruncateNullable(back, 500), - CertificateLevelId = levelId, - CertificateLevelCode = levelCode, - NormalizedContentKey = normKey, - ExternalStableId = extId, - }; - - var existingId = result.Snapshot.SrsIdByNormalizedKey.TryGetValue(normKey, out var sid) ? sid : (int?)null; - AddCandidate(result, ImportEntityType.SrsCardTemplate, extId, levelCode, null, extId, - $"{cardType}: {front}", existingId, JsonSerializer.Serialize(payload, PascalJson), null, null, 0); - } - } - - // 5. Mock Tests (Server-side private answers combined securely; 4 JLPT skills split across active DB CertificateSections) - if (scope.IncludeMockTests) - { - var mocksPublic = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/mock_tests_public.json"); - var mocksPrivate = ReadJsonArray(systemZip, sysEntries, $"01_CORE_COMPATIBLE_DATA/{levelCode}/mock_tests_private_answers.json") - .GroupBy(m => Str(m, "mockExternalId") ?? "", StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - - foreach (var m in mocksPublic) - { - var extId = Str(m, "externalStableId") ?? ""; - if (scope.MockTestIds.Count > 0 && !scope.MockTestIds.Contains(extId)) - continue; - - mocksPrivate.TryGetValue(extId, out var privJson); - var candidate = await BuildMockTestCandidateAsync( - m, privJson, levelId, levelCode, csvAssets, ResolveMediaAsync, result.Snapshot, result.Issues); - if (candidate is not null) - result.Items.Add(candidate); - } - } - } - } - finally - { - foreach (var entry in resourceZips.Values) - entry.Zip.Dispose(); - } - - return result; - } - - private async Task BuildMockTestCandidateAsync( - JsonElement mockPublic, - JsonElement? mockPrivate, - int levelId, - string levelCode, - List csvAssets, - Func> resolveMediaAsync, - DbSnapshot snapshot, - List issues) - { - var extId = Str(mockPublic, "externalStableId") ?? ""; - var title = Truncate(Str(mockPublic, "titleVi") ?? extId, 300); - if (!mockPublic.TryGetProperty("publicLearnerPayload", out var pubPayload) || pubPayload.ValueKind != JsonValueKind.Object) - { - issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Error", - Code = "MOCK_PAYLOAD_MISSING", - Target = extId, - Message = "Đề thi thiếu publicLearnerPayload.", - }); - return null; - } - - // Answer key map: N5 uses "answers", N4-N2 uses "answerKeyAndExplanations". - var answerMap = new Dictionary(StringComparer.OrdinalIgnoreCase); - var audioPlanByRefOrQ = new Dictionary(StringComparer.OrdinalIgnoreCase); - - if (mockPrivate is { ValueKind: JsonValueKind.Object } priv) - { - var ansArrayName = priv.TryGetProperty("answers", out _) ? "answers" : "answerKeyAndExplanations"; - if (priv.TryGetProperty(ansArrayName, out var ansArr) && ansArr.ValueKind == JsonValueKind.Array) - { - foreach (var a in ansArr.EnumerateArray()) - { - var qid = Str(a, "questionId"); - if (string.IsNullOrWhiteSpace(qid)) continue; - answerMap[qid] = (IntVal(a, "correctOptionIndex", 0), Str(a, "explanationVi")); - } - } - - if (priv.TryGetProperty("listeningScriptsAndAudioPlan", out var audioArr) && audioArr.ValueKind == JsonValueKind.Array) - { - foreach (var a in audioArr.EnumerateArray()) - { - var script = CombineScriptAndTranslation(Str(a, "scriptJa"), Str(a, "translationVi")); - var fileName = Str(a, "fileName"); - var refId = Str(a, "audioRefId") ?? Str(a, "audioId"); - var linkedQ = Str(a, "linkedQuestionId"); - if (!string.IsNullOrWhiteSpace(refId)) audioPlanByRefOrQ[refId] = (fileName, script, Str(a, "translationVi")); - if (!string.IsNullOrWhiteSpace(linkedQ)) audioPlanByRefOrQ[linkedQ] = (fileName, script, Str(a, "translationVi")); - } - } - } - - // Map assets from CSV linked to this mock (match e.g. N5-FULL-MOCK-01 inside N5-FULL-MOCK-01-COMPLETE). - var mockCsvAssets = csvAssets.Where(a => - a.Level.Equals(levelCode, StringComparison.OrdinalIgnoreCase) && - !string.IsNullOrWhiteSpace(a.LinkedChapterOrExam) && - (extId.StartsWith(a.LinkedChapterOrExam, StringComparison.OrdinalIgnoreCase) || - a.LinkedChapterOrExam.StartsWith(extId, StringComparison.OrdinalIgnoreCase))).ToList(); - - var assetByQuestionId = mockCsvAssets - .Where(a => !string.IsNullOrWhiteSpace(a.LinkedQuestionId)) - .GroupBy(a => a.LinkedQuestionId!, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); - - var assetByExtId = mockCsvAssets - .Where(a => !string.IsNullOrWhiteSpace(a.AssetExternalId)) - .GroupBy(a => a.AssetExternalId!, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); - - // Passages indexed by passageId. - var passagesById = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (pubPayload.TryGetProperty("passages", out var passagesArr) && passagesArr.ValueKind == JsonValueKind.Array) - { - var sortIdx = 0; - foreach (var psg in passagesArr.EnumerateArray()) - { - var pid = Str(psg, "passageId") ?? Str(psg, "code") ?? $"P-{++sortIdx}"; - var pText = Str(psg, "passageJa") ?? Str(psg, "passageText") ?? Str(psg, "contentJa") ?? string.Empty; - var pTitle = Truncate(Str(psg, "titleVi") ?? Str(psg, "titleJa") ?? pid, 300); - passagesById[pid] = new MockPassageImportPayloadResponse - { - PassageCode = Truncate(pid, 80), - Title = pTitle, - PassageText = pText, - SortOrder = ++sortIdx, - SourceReference = Truncate($"{SourceTypeTag}:{extId}", 300), - }; - } - } - - // Resolve DB sections for the 4 required JLPT study skills. - var certSections = snapshot.CertSectionsByLevelId.GetValueOrDefault(levelId) ?? []; - if (certSections.Count == 0) - { - issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Error", - Code = "MISSING_CERT_SECTION", - Target = extId, - Message = $"Cấp độ {levelCode} chưa có CertificateSection trong DB để gắn đề thi thử.", - }); - return null; - } - - var bucketVocab = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); - var bucketGrammar = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); - var bucketReading = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); - var bucketListening = new List<(MockQuestionPayloadResponse Q, string? PassageId)>(); - - var audioCount = 0; - var imageCount = 0; - var globalOrder = 0; - - if (pubPayload.TryGetProperty("questions", out var qArr) && qArr.ValueKind == JsonValueKind.Array) - { - foreach (var q in qArr.EnumerateArray()) - { - var qid = Str(q, "questionId") ?? $"Q{globalOrder + 1}"; - var prompt = SanitizeQuestionText(Str(q, "prompt") ?? Str(q, "promptJa") ?? Str(q, "questionText") ?? ""); - if (string.IsNullOrWhiteSpace(prompt)) continue; - - var rawOptions = new List(); - if (q.TryGetProperty("options", out var optEl) && optEl.ValueKind == JsonValueKind.Array) - foreach (var o in optEl.EnumerateArray()) - rawOptions.Add(SanitizeOptionText(o.GetString() ?? "")); - - if (rawOptions.Count < 2) continue; - - // Ensure option texts are unique & non-empty. - rawOptions = DeduplicateOptions(rawOptions); - var ansInfo = answerMap.GetValueOrDefault(qid); - var correctIdx = Math.Clamp(ansInfo.CorrectIndex, 0, rawOptions.Count - 1); - - var options = rawOptions.Select((optText, idx) => new ImportOptionPayloadResponse - { - SortOrder = idx + 1, - OptionText = optText, - IsCorrect = idx == correctIdx, - }).ToList(); - - var skillBucket = ClassifyMockQuestionSkill(q); - var audioRefId = Str(q, "audioRefId"); - var qAssetList = assetByQuestionId.GetValueOrDefault(qid) - ?? (!string.IsNullOrWhiteSpace(audioRefId) ? assetByExtId.GetValueOrDefault(audioRefId) : null) - ?? []; - - var wavLogical = qAssetList.FirstOrDefault(a => a.AssetType.Contains("WAV", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath - ?? Str(q, "linkedAudioFile") - ?? (audioPlanByRefOrQ.TryGetValue(qid, out var planByQ) ? planByQ.FileName : null) - ?? (!string.IsNullOrWhiteSpace(audioRefId) && audioPlanByRefOrQ.TryGetValue(audioRefId, out var planByRef) ? planByRef.FileName : null); - - var imgLogical = qAssetList.FirstOrDefault(a => a.AssetType.Contains("IMAGE", StringComparison.OrdinalIgnoreCase))?.LogicalAssetPath - ?? Str(q, "linkedIllustrationFile"); - - var (audioUrl, _) = skillBucket == JlptStudySkill.Listening - ? await resolveMediaAsync(wavLogical, true) - : (null, null); - var (imgUrl, _) = !string.IsNullOrWhiteSpace(imgLogical) - ? await resolveMediaAsync(imgLogical, false) - : (null, null); - - if (audioUrl is not null) audioCount++; - if (imgUrl is not null) imageCount++; - - if (skillBucket == JlptStudySkill.Listening && string.IsNullOrWhiteSpace(audioUrl) && wavLogical is null) - { - issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Warning", - Code = "MOCK_LISTENING_NO_AUDIO", - Target = $"{extId}/{qid}", - Message = "Câu nghe thiếu tệp WAV tương ứng trong asset_mapping.csv.", - }); - } - - string? transcript = null; - if (audioPlanByRefOrQ.TryGetValue(qid, out var p1)) transcript = p1.Script; - else if (!string.IsNullOrWhiteSpace(audioRefId) && audioPlanByRefOrQ.TryGetValue(audioRefId, out var p2)) transcript = p2.Script; - - var passageRef = Str(q, "passageRefId") ?? Str(q, "passageId"); - var qPayload = new MockQuestionPayloadResponse - { - SortOrder = ++globalOrder, - GroupSortOrder = globalOrder, - QuestionText = prompt, - QuestionType = imgUrl is not null && skillBucket == JlptStudySkill.Listening - ? JlptMockQuestionFormats.VisualMultipleChoice - : "SingleChoice", - AudioUrl = audioUrl, - AudioTranscript = transcript, - ImageUrl = imgUrl, - Explanation = ansInfo.Explanation, - PassageCode = passageRef is not null && passagesById.ContainsKey(passageRef) ? Truncate(passageRef, 80) : null, - Options = options, - }; - - switch (skillBucket) - { - case JlptStudySkill.Vocabulary: bucketVocab.Add((qPayload, qPayload.PassageCode)); break; - case JlptStudySkill.Grammar: bucketGrammar.Add((qPayload, qPayload.PassageCode)); break; - case JlptStudySkill.Reading: bucketReading.Add((qPayload, qPayload.PassageCode)); break; - case JlptStudySkill.Listening: bucketListening.Add((qPayload, qPayload.PassageCode)); break; - } - } - } - - // Guarantee ValidateMockTestCoverage passes if a mock omitted one of the 4 splits slightly or rebalances cleanly. - var sections = new List(); - void AddMockSection(string secTitle, JlptStudySkill skill, List<(MockQuestionPayloadResponse Q, string? PassageId)> items, int duration) - { - if (items.Count == 0) return; - var skillId = ResolveSkillId(snapshot, skill.ToString()); - var certSection = MatchCertificateSection(certSections, skill); - var passageCodesNeeded = items.Select(x => x.PassageId).Where(c => !string.IsNullOrWhiteSpace(c)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .Select(c => passagesById[c!]) - .ToList(); - - sections.Add(new MockTestSectionPayloadResponse - { - Title = Truncate(secTitle, 200), - SortOrder = sections.Count + 1, - LanguageSkillId = skillId, - LanguageSkillName = snapshot.SkillNameById.GetValueOrDefault(skillId, skill.ToString()), - CertificateSectionCode = certSection.Code, - DurationMinutes = duration, - Passages = passageCodesNeeded, - Questions = items.Select(x => x.Q).ToList(), - }); - } - - AddMockSection($"Kiến thức ngôn ngữ — Từ vựng ({levelCode})", JlptStudySkill.Vocabulary, bucketVocab, 20); - AddMockSection($"Kiến thức ngôn ngữ — Ngữ pháp ({levelCode})", JlptStudySkill.Grammar, bucketGrammar, 25); - AddMockSection($"Đọc hiểu ({levelCode})", JlptStudySkill.Reading, bucketReading, 30); - AddMockSection($"Nghe hiểu ({levelCode})", JlptStudySkill.Listening, bucketListening, 30); - - if (sections.Count < 4) - { - issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Warning", - Code = "MOCK_INCOMPLETE_SECTIONS", - Target = extId, - Message = $"Đề thi chỉ phân tách được {sections.Count}/4 phần kỹ năng.", - }); - } - - var payload = new MockTestImportPayloadResponse - { - Title = title, - Description = TruncateNullable($"Đề thi thử JLPT {levelCode} nhập chuẩn từ gói giáo trình ({globalOrder} câu, đáp án bảo mật phía máy chủ).", 1000), - TimeLimitMinutes = Math.Max(30, sections.Sum(s => s.DurationMinutes ?? 20)), - IsPlacementAssessment = false, - CertificateLevelCode = levelCode, - CertificateLevelId = levelId, - Sections = sections, - }; - - var existingId = snapshot.MockIdBySourceOrTitle.TryGetValue(extId, out var m1) - ? m1 - : snapshot.MockIdByLevelTitle.TryGetValue((levelId, title), out var m2) ? m2 : (int?)null; - - var rowKey = extId; - var existsOpen = snapshot.OpenOrApprovedRowKeys.Contains((ImportEntityType.MockTest, rowKey)); - var action = (existingId.HasValue || existsOpen) ? ImportRowAction.Unchanged : ImportRowAction.New; - - return new StagedCandidate - { - EntityType = ImportEntityType.MockTest, - Action = action, - TargetEntityId = existingId, - PayloadJson = JsonSerializer.Serialize(payload, PascalJson), - CanStage = action != ImportRowAction.Unchanged, - Preview = new CurriculumPackagePreviewItemResponse - { - ExternalId = extId, - EntityType = nameof(ImportEntityType.MockTest), - LevelCode = levelCode, - RowKey = rowKey, - Title = title, - Action = existingId.HasValue ? "Existing" : existsOpen ? "Existing" : "New", - Status = "Draft", - PublishedReady = false, - AudioAsset = audioCount > 0 ? $"{audioCount} WAV" : null, - ImageAsset = imageCount > 0 ? $"{imageCount} Ảnh" : null, - ChildCount = globalOrder, - }, - }; - } - - private async Task UploadZipEntryAsync( - ZipArchiveEntry entry, - bool isAudio, - int actorUserId, - CancellationToken ct) - { - await using var entryStream = entry.Open(); - await using var ms = new MemoryStream(); - await entryStream.CopyToAsync(ms, ct); - ms.Position = 0; - - var fileName = Path.GetFileName(entry.FullName); - var ext = Path.GetExtension(fileName).ToLowerInvariant(); - if (isAudio) - { - var contentType = ListeningAudioFilePolicy.GetContentType(ext); - var storedAudio = await fileStorage.UploadAsync(ms, fileName, contentType, "jlpt-curriculum-audio", ct); - if (audioTranscriptions is not null && actorUserId > 0) - { - try { await audioTranscriptions.QueueAsync(storedAudio.Url, actorUserId, ct); } - catch (Exception ex) { logger.LogDebug(ex, "Queueing curriculum WAV transcription skipped for {Url}", storedAudio.Url); } - } - return storedAudio.Url; - } - - var imgMime = ext switch - { - ".png" => "image/png", - ".webp" => "image/webp", - ".gif" => "image/gif", - _ => "image/jpeg", - }; - var storedImg = await fileStorage.UploadAsync(ms, fileName, imgMime, "jlpt-curriculum-images", ct); - return storedImg.Url; - } - - private async Task SyncContentBankDraftsAsync( - List drafts, - int actorUserId, - Guid batchId, - CancellationToken ct) - { - var keys = drafts.Select(d => ComputeContentBankKey(d.EntityType, d.RowKey, d.PayloadJson)).Distinct().ToArray(); - var existing = await unitOfWork.ContentBankItems.Query() - .Where(x => !x.IsDeleted && x.OwnerUserId == actorUserId && keys.Contains(x.NaturalKey)) - .ToListAsync(ct); - - foreach (var draft in drafts) - { - var nk = ComputeContentBankKey(draft.EntityType, draft.RowKey, draft.PayloadJson); - var item = existing.FirstOrDefault(x => x.EntityType == draft.EntityType && x.NaturalKey == nk); - if (item is null) - { - item = new ContentBankItem - { - OwnerUserId = actorUserId, - EntityType = draft.EntityType, - NaturalKey = nk, - }; - await unitOfWork.ContentBankItems.AddAsync(item, ct); - existing.Add(item); - } - item.PayloadJson = draft.PayloadJson; - item.TargetEntityId = draft.TargetEntityId; - item.Status = ContentApprovalStatus.Draft; - item.LatestBatchId = batchId; - } - } - - private static string ComputeContentBankKey(ImportEntityType type, string rowKey, string payloadJson) - { - if (type != ImportEntityType.PracticeExercise) return Truncate(rowKey, 490); - try - { - using var doc = JsonDocument.Parse(payloadJson); - if (doc.RootElement.TryGetProperty("CertificateLevelId", out var lvl) && lvl.ValueKind == JsonValueKind.Number) - return $"{Truncate(rowKey, 460)} / level:{lvl.GetInt32()}"; - } - catch (JsonException) { } - return Truncate(rowKey, 490); - } - - private static void AddCandidate( - BuiltPackageResult result, - ImportEntityType entityType, - string externalId, - string levelCode, - string? topicCode, - string rowKey, - string title, - int? existingTargetId, - string payloadJson, - string? audioAsset, - string? imageAsset, - int childCount, - bool skipIfAlreadyLinkedToLesson = false) - { - var alreadyOpenOrApproved = result.Snapshot.OpenOrApprovedRowKeys.Contains((entityType, rowKey)); - var isLessonOrExerciseOrSrs = entityType is ImportEntityType.Lesson or ImportEntityType.PracticeExercise or ImportEntityType.SrsCardTemplate or ImportEntityType.MockTest; - - ImportRowAction action; - string previewAction; - if (alreadyOpenOrApproved || skipIfAlreadyLinkedToLesson || (isLessonOrExerciseOrSrs && existingTargetId.HasValue)) - { - action = ImportRowAction.Unchanged; - previewAction = "Existing"; - } - else if (existingTargetId.HasValue) - { - action = ImportRowAction.Modified; - previewAction = "Modified"; - } - else - { - action = ImportRowAction.New; - previewAction = "New"; - } - - result.Items.Add(new StagedCandidate - { - EntityType = entityType, - Action = action, - TargetEntityId = existingTargetId, - PayloadJson = payloadJson, - CanStage = action != ImportRowAction.Unchanged, - Preview = new CurriculumPackagePreviewItemResponse - { - ExternalId = externalId, - EntityType = entityType.ToString(), - LevelCode = levelCode, - TopicCode = topicCode, - RowKey = rowKey, - Title = title, - Action = previewAction, - Status = "Draft", - PublishedReady = false, - AudioAsset = audioAsset, - ImageAsset = imageAsset, - ChildCount = childCount, - }, - }); - } - - private async Task LoadDatabaseSnapshotAsync(CancellationToken ct) - { - var levels = await unitOfWork.CertificateLevels.Query() - .AsNoTracking() - .Where(l => !l.IsDeleted && !l.CertificateType.IsDeleted && l.CertificateType.Name == "JLPT") - .Select(l => new { l.Id, l.Code }) - .ToListAsync(ct); - - var skills = await unitOfWork.LanguageSkills.Query() - .AsNoTracking() - .Where(s => !s.IsDeleted) - .Select(s => new { s.Id, s.Name }) - .ToListAsync(ct); - - var certSections = await unitOfWork.CertificateSections.Query() - .AsNoTracking() - .Where(s => !s.IsDeleted) - .ToListAsync(ct); - - var lessons = await unitOfWork.Lessons.Query() - .AsNoTracking() - .Where(l => !l.IsDeleted) - .Select(l => new LessonSnap(l.Id, l.Title, l.CertificateLevelId, l.SourceProvenance)) - .ToListAsync(ct); - - var vocabs = await unitOfWork.Vocabularies.Query() - .AsNoTracking() - .Where(v => !v.IsDeleted) - .Select(v => new { v.Id, v.Word, v.Reading }) - .ToListAsync(ct); - - var kanjis = await unitOfWork.Kanjis.Query() - .AsNoTracking() - .Where(k => !k.IsDeleted) - .Select(k => new { k.Id, k.Character }) - .ToListAsync(ct); - - var grammars = await unitOfWork.GrammarPatterns.Query() - .AsNoTracking() - .Where(g => !g.IsDeleted) - .Select(g => new { g.Id, g.Title }) - .ToListAsync(ct); - - var exercises = await unitOfWork.PracticeExercises.Query() - .AsNoTracking() - .Where(e => !e.IsDeleted) - .Select(e => new { e.Id, e.Title, e.CertificateLevelId }) - .ToListAsync(ct); - - var mocks = await unitOfWork.MockTests.Query() - .AsNoTracking() - .Where(m => !m.IsDeleted && !m.IsArchivedVersion) - .Select(m => new { m.Id, m.Title, m.CertificateLevelId, m.SourceReference }) - .ToListAsync(ct); - - var srs = await unitOfWork.SrsCardTemplates.Query() - .AsNoTracking() - .Where(s => !s.IsDeleted) - .Select(s => new { s.Id, s.NormalizedContentKey }) - .ToListAsync(ct); - - var requests = await unitOfWork.ContentApprovalRequests.Query() - .AsNoTracking() - .Where(r => !r.IsDeleted && r.Status != ContentApprovalStatus.Rejected) - .Select(r => new { r.EntityType, r.RowKey, r.TargetEntityId, r.Status }) - .ToListAsync(ct); - - var lvLinks = await unitOfWork.LessonVocabularies.Query() - .AsNoTracking() - .Where(lv => !lv.Lesson.IsDeleted) - .Select(lv => new { lv.Lesson.Title, lv.Lesson.CertificateLevelId, lv.VocabularyId }) - .ToListAsync(ct); - - var lkLinks = await unitOfWork.LessonKanjis.Query() - .AsNoTracking() - .Where(lk => !lk.Lesson.IsDeleted) - .Select(lk => new { lk.Lesson.Title, lk.Lesson.CertificateLevelId, lk.KanjiId }) - .ToListAsync(ct); - - var lgLinks = await unitOfWork.LessonGrammars.Query() - .AsNoTracking() - .Where(lg => !lg.Lesson.IsDeleted) - .Select(lg => new { lg.Lesson.Title, lg.Lesson.CertificateLevelId, lg.GrammarPatternId }) - .ToListAsync(ct); - - return new DbSnapshot - { - LevelIdByCode = levels.ToDictionary(l => l.Code, l => l.Id, StringComparer.OrdinalIgnoreCase), - SkillIdByName = skills.ToDictionary(s => s.Name, s => s.Id, StringComparer.OrdinalIgnoreCase), - SkillNameById = skills.ToDictionary(s => s.Id, s => s.Name), - CertSectionsByLevelId = certSections.GroupBy(s => s.CertificateLevelId).ToDictionary(g => g.Key, g => g.ToList()), - Lessons = lessons, - VocabIdByWordReading = vocabs.GroupBy(v => $"{v.Word}\u001f{v.Reading}", StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), - KanjiIdByChar = kanjis.GroupBy(k => k.Character, StringComparer.Ordinal) - .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal), - GrammarIdByTitle = grammars.GroupBy(g => g.Title, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), - ExerciseIdByLevelTitle = exercises.Where(e => e.CertificateLevelId.HasValue) - .GroupBy(e => (e.CertificateLevelId!.Value, e.Title)) - .ToDictionary(g => g.Key, g => g.First().Id), - MockIdBySourceOrTitle = mocks.Where(m => !string.IsNullOrWhiteSpace(m.SourceReference)) - .GroupBy(m => m.SourceReference!, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), - MockIdByLevelTitle = mocks.GroupBy(m => (m.CertificateLevelId, m.Title)) - .ToDictionary(g => g.Key, g => g.First().Id), - SrsIdByNormalizedKey = srs.GroupBy(s => s.NormalizedContentKey, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First().Id, StringComparer.OrdinalIgnoreCase), - OpenOrApprovedRowKeys = requests.Select(r => (r.EntityType, r.RowKey)).ToHashSet(), - OpenTargetIds = requests - .Where(r => r.TargetEntityId.HasValue && (r.Status == ContentApprovalStatus.Draft || r.Status == ContentApprovalStatus.PendingReview)) - .Select(r => (r.EntityType, r.TargetEntityId!.Value)) - .ToHashSet(), - LessonVocabPairs = lvLinks.Select(x => (x.Title, x.CertificateLevelId, x.VocabularyId)).ToHashSet(), - LessonKanjiPairs = lkLinks.Select(x => (x.Title, x.CertificateLevelId, x.KanjiId)).ToHashSet(), - LessonGrammarPairs = lgLinks.Select(x => (x.Title, x.CertificateLevelId, x.GrammarPatternId)).ToHashSet(), - }; - } - - private string? FindResourcesDirectory() - { - var configured = configuration["CurriculumPackage:RootPath"]; - if (!string.IsNullOrWhiteSpace(configured) && File.Exists(Path.Combine(configured, SystemZipName))) - return Path.GetFullPath(configured); - - foreach (var start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) - { - var dir = new DirectoryInfo(start); - for (var i = 0; i < 8 && dir is not null; i++) - { - var candidate = Path.Combine(dir.FullName, "resources"); - if (File.Exists(Path.Combine(candidate, SystemZipName))) - return candidate; - if (File.Exists(Path.Combine(dir.FullName, SystemZipName))) - return dir.FullName; - dir = dir.Parent; - } - } - return null; - } - - private static CurriculumPackageArchiveInfo InspectArchive(string fullPath, string fileName, string? levelCode) - { - var info = new CurriculumPackageArchiveInfo { FileName = fileName, LevelCode = levelCode }; - if (!File.Exists(fullPath)) return info; - - var fi = new FileInfo(fullPath); - info.Exists = true; - info.SizeBytes = fi.Length; - - try - { - using var zip = ZipFile.OpenRead(fullPath); - info.EntryCount = zip.Entries.Count; - info.UnsafeEntryCount = zip.Entries.Count(e => IsUnsafeZipEntry(e.FullName)); - using var sha = SHA256.Create(); - using var fs = File.OpenRead(fullPath); - info.Sha256Short = Convert.ToHexString(sha.ComputeHash(fs))[..12].ToLowerInvariant(); - } - catch (InvalidDataException) - { - info.UnsafeEntryCount = -1; - } - return info; - } - - private static bool IsUnsafeZipEntry(string entryName) => - string.IsNullOrEmpty(entryName) || - entryName.StartsWith('/') || - entryName.StartsWith('\\') || - entryName.Contains("..", StringComparison.Ordinal) || - entryName.Contains(':'); - - private static Dictionary IndexSafeEntries(ZipArchive zip) - { - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var entry in zip.Entries) - { - if (IsUnsafeZipEntry(entry.FullName)) continue; - var norm = entry.FullName.Replace('\\', '/').TrimStart('/'); - if (norm.EndsWith('/')) continue; - dict.TryAdd(norm, entry); - } - return dict; - } - - private static (ZipArchive Zip, Dictionary Entries, Dictionary ByFileName)? OpenLevelResourceZip( - string root, - string levelCode, - Dictionary Entries, Dictionary ByFileName)> cache) - { - if (cache.TryGetValue(levelCode, out var existing)) return existing; - var zipName = $"RIKIPATH_{levelCode.ToUpperInvariant()}_RESOURCES.zip"; - var full = Path.Combine(root, zipName); - if (!File.Exists(full)) return null; - - var zip = ZipFile.OpenRead(full); - var entries = IndexSafeEntries(zip); - var byFile = entries.Values - .GroupBy(e => Path.GetFileName(e.FullName), StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - var tuple = (zip, entries, byFile); - cache[levelCode] = tuple; - return tuple; - } - - private (ZipArchive? Zip, ZipArchiveEntry? Entry) LocateZipEntry( - string logicalPath, - string levelCode, - Dictionary resolver, - Dictionary Entries, Dictionary ByFileName)> resourceZips) - { - if (!resourceZips.TryGetValue(levelCode, out var res)) return (null, null); - - var target = resolver.TryGetValue(logicalPath, out var mapped) ? mapped : logicalPath; - if (target.Contains("::", StringComparison.Ordinal)) - { - var idx = target.IndexOf("::", StringComparison.Ordinal); - target = target[(idx + 2)..]; - } - target = target.Replace('\\', '/').TrimStart('/'); - - if (res.Entries.TryGetValue(target, out var exact)) - return (res.Zip, exact); - - var bySuffix = res.Entries.FirstOrDefault(kv => kv.Key.EndsWith("/" + target, StringComparison.OrdinalIgnoreCase)).Value; - if (bySuffix is not null) - return (res.Zip, bySuffix); - - var fileName = Path.GetFileName(target); - if (!string.IsNullOrEmpty(fileName) && res.ByFileName.TryGetValue(fileName, out var byName)) - return (res.Zip, byName); - - return (null, null); - } - - private static List ReadJsonArray(ZipArchive zip, Dictionary entries, string pathSuffix) - { - var entry = entries.TryGetValue(pathSuffix, out var e) - ? e - : entries.FirstOrDefault(kv => kv.Key.EndsWith("/" + pathSuffix, StringComparison.OrdinalIgnoreCase)).Value; - if (entry is null) return []; - - using var stream = entry.Open(); - using var doc = JsonDocument.Parse(stream); - if (doc.RootElement.ValueKind != JsonValueKind.Array) return []; - return doc.RootElement.EnumerateArray().Select(x => x.Clone()).ToList(); - } - - private static Dictionary ReadAssetMappingsResolver(ZipArchive zip, Dictionary entries) - { - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); - var entry = entries.FirstOrDefault(kv => kv.Key.EndsWith("consolidated_path_resolver.json", StringComparison.OrdinalIgnoreCase)).Value; - if (entry is null) return dict; - - using var stream = entry.Open(); - using var doc = JsonDocument.Parse(stream); - if (doc.RootElement.TryGetProperty("assetMappings", out var am) && am.ValueKind == JsonValueKind.Object) - foreach (var p in am.EnumerateObject()) - if (p.Value.ValueKind == JsonValueKind.String && p.Value.GetString() is { } s) - dict[p.Name] = s; - if (doc.RootElement.TryGetProperty("fileMappings", out var fm) && fm.ValueKind == JsonValueKind.Object) - foreach (var p in fm.EnumerateObject()) - if (p.Value.ValueKind == JsonValueKind.String && p.Value.GetString() is { } s) - dict.TryAdd(p.Name, s); - return dict; - } - - private static List LoadAssetMappings(ZipArchive zip, Dictionary entries) - { - var rows = new List(); - var entry = entries.FirstOrDefault(kv => kv.Key.EndsWith("04_ASSET_REFERENCES/asset_mapping.csv", StringComparison.OrdinalIgnoreCase)).Value; - if (entry is null) return rows; - - using var reader = new StreamReader(entry.Open(), Encoding.UTF8); - var headerLine = reader.ReadLine(); - if (headerLine is null) return rows; - var headers = ParseCsvLine(headerLine); - var col = headers.Select((h, i) => (h, i)).ToDictionary(x => x.h.Trim(), x => x.i, StringComparer.OrdinalIgnoreCase); - - while (reader.ReadLine() is { } line) - { - if (string.IsNullOrWhiteSpace(line)) continue; - var cols = ParseCsvLine(line); - string GetCol(string name) => col.TryGetValue(name, out var idx) && idx < cols.Count ? cols[idx].Trim() : ""; - rows.Add(new CsvAssetRow( - GetCol("assetType"), - GetCol("level"), - GetCol("assetExternalId"), - GetCol("linkedChapterOrExam"), - GetCol("linkedLessonId"), - GetCol("linkedQuestionId"), - GetCol("logicalAssetPath"))); - } - return rows; - } - - private static List ParseCsvLine(string line) - { - var result = new List(); - var sb = new StringBuilder(); - var inQuotes = false; - for (var i = 0; i < line.Length; i++) - { - var c = line[i]; - if (c == '"') - { - if (inQuotes && i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; } - else inQuotes = !inQuotes; - } - else if (c == ',' && !inQuotes) - { - result.Add(sb.ToString()); - sb.Clear(); - } - else sb.Append(c); - } - result.Add(sb.ToString()); - return result; - } - - private static Dictionary> LoadKaiwaByLesson(ZipArchive zip, Dictionary entries) - { - var dict = new Dictionary>(StringComparer.OrdinalIgnoreCase); - var list = ReadJsonArray(zip, entries, "02_EXTENDED_LEARNING_DATA/KAIWA/n4_n2_kaiwa_dialogues.json"); - foreach (var item in list) - { - var lid = Str(item, "lessonExternalId"); - if (string.IsNullOrWhiteSpace(lid)) continue; - if (!dict.TryGetValue(lid, out var bucket)) dict[lid] = bucket = []; - bucket.Add(item); - } - return dict; - } - - private static RichCurriculumData ExtractRichCurriculumData( - string levelCode, - ZipArchive? resZip, - Dictionary? entries) - { - var data = new RichCurriculumData(); - if (resZip is null || entries is null) return data; - - foreach (var kv in entries) - { - if (!kv.Key.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) continue; - if (kv.Key.Contains("/Lessons/", StringComparison.OrdinalIgnoreCase)) - { - using var doc = JsonDocument.Parse(kv.Value.Open()); - if (doc.RootElement.ValueKind == JsonValueKind.Object) - { - var lid = Str(doc.RootElement, "lessonId") ?? Path.GetFileNameWithoutExtension(kv.Key); - data.LessonsById[lid] = doc.RootElement.Clone(); - } - } - else if (kv.Key.EndsWith("Chapter_Content.json", StringComparison.OrdinalIgnoreCase) || - Regex.IsMatch(Path.GetFileName(kv.Key), @"^N[2-4]_CH\d+_CONTENT\.json$", RegexOptions.IgnoreCase)) - { - using var doc = JsonDocument.Parse(kv.Value.Open()); - var root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) continue; - var chId = Str(root, "chapterId"); - if (!string.IsNullOrWhiteSpace(chId) && root.TryGetProperty("chapterAssessment", out var ca) && ca.ValueKind == JsonValueKind.Object) - data.ChapterAssessmentsById[chId] = ca.Clone(); - if (root.TryGetProperty("lessons", out var arr) && arr.ValueKind == JsonValueKind.Array) - { - foreach (var l in arr.EnumerateArray()) - { - var lid = Str(l, "lessonId"); - if (!string.IsNullOrWhiteSpace(lid) && !data.LessonsById.ContainsKey(lid)) - data.LessonsById[lid] = l.Clone(); - } - } - } - } - return data; - } - - private List ExtractPracticeQuestions( - JsonElement container, - string sourceTag, - List issues) - { - var list = new List(); - var prop = container.TryGetProperty("practiceQuestions", out var pq) ? pq - : container.TryGetProperty("questions", out var qs) ? qs - : default; - if (prop.ValueKind != JsonValueKind.Array) return list; - - var order = 0; - foreach (var q in prop.EnumerateArray()) - { - var prompt = SanitizeQuestionText(Str(q, "prompt") ?? Str(q, "questionText") ?? ""); - if (string.IsNullOrWhiteSpace(prompt)) continue; - - var rawOpts = new List(); - if (q.TryGetProperty("options", out var optsEl) && optsEl.ValueKind == JsonValueKind.Array) - foreach (var o in optsEl.EnumerateArray()) - if (o.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(o.GetString())) - rawOpts.Add(SanitizeOptionText(o.GetString()!)); - - if (rawOpts.Count < 2) - { - issues.Add(new CurriculumPackageIssueResponse - { - Severity = "Warning", - Code = "PRACTICE_SKIPPED_FEW_OPTIONS", - Target = sourceTag, - Message = $"Bỏ qua câu luyện tập '{Truncate(prompt, 40)}' vì không có đủ 2 lựa chọn (dạng tự luận/không tương thích MCQ).", - }); - continue; - } - - rawOpts = DeduplicateOptions(rawOpts); - var correctIdx = Math.Clamp(IntVal(q, "correctOptionIndex", 0), 0, rawOpts.Count - 1); - - list.Add(new PracticeQuestionPayloadResponse - { - SortOrder = ++order, - QuestionText = prompt, - Explanation = Str(q, "explanationVi") ?? Str(q, "explanation"), - Options = rawOpts.Select((optText, i) => new ImportOptionPayloadResponse - { - SortOrder = i + 1, - OptionText = optText, - IsCorrect = i == correctIdx, - }).ToList(), - }); - } - return list; - } - - private static string BuildLessonMarkdown( - JsonElement indexLesson, - JsonElement? richLesson, - List kaiwaList, - Dictionary vocabByExtId) - { - _ = vocabByExtId; - var sb = new StringBuilder(); - var note = Str(indexLesson, "multiSkillNote"); - var focus = richLesson is { ValueKind: JsonValueKind.Object } rl ? Str(rl, "focus") : null; - if (!string.IsNullOrWhiteSpace(focus)) - sb.AppendLine($"**Trọng tâm bài học:** {focus}").AppendLine(); - else if (!string.IsNullOrWhiteSpace(note) && !note.Contains("Extended_Learning_Data", StringComparison.OrdinalIgnoreCase)) - sb.AppendLine(note).AppendLine(); - - if (richLesson is { ValueKind: JsonValueKind.Object } r) - { - if (r.TryGetProperty("contentSections", out var sections) && sections.ValueKind == JsonValueKind.Array) - { - foreach (var sec in sections.EnumerateArray()) - { - var h = Str(sec, "headingVi") ?? Str(sec, "title"); - var body = Str(sec, "bodyMarkdown") ?? Str(sec, "content"); - if (!string.IsNullOrWhiteSpace(h)) sb.AppendLine($"### {h}"); - if (!string.IsNullOrWhiteSpace(body)) sb.AppendLine(body); - sb.AppendLine(); - } - } - - if (r.TryGetProperty("grammarPoints", out var gp) && gp.ValueKind == JsonValueKind.Array && gp.GetArrayLength() > 0) - { - sb.AppendLine("### Điểm ngữ pháp trọng tâm"); - foreach (var g in gp.EnumerateArray()) - { - var pattern = Str(g, "pattern") ?? Str(g, "title") ?? ""; - var structure = Str(g, "structure") ?? ""; - var meaning = Str(g, "meaningVi") ?? Str(g, "explanationVi") ?? Str(g, "usageNotes") ?? ""; - if (!string.IsNullOrWhiteSpace(pattern)) sb.AppendLine($"- **{pattern}**: {meaning}"); - if (!string.IsNullOrWhiteSpace(structure)) sb.AppendLine($" - Cấu trúc: `{structure}`"); - if (g.TryGetProperty("examples", out var exs) && exs.ValueKind == JsonValueKind.Array) - { - foreach (var ex in exs.EnumerateArray().Take(3)) - { - var ja = Str(ex, "sentenceJa") ?? Str(ex, "japanese") ?? ""; - var vi = Str(ex, "meaningVi") ?? Str(ex, "vietnamese") ?? ""; - if (!string.IsNullOrWhiteSpace(ja)) sb.AppendLine($" - Ví dụ: {ja} — {vi}"); - } - } - } - sb.AppendLine(); - } - - if (r.TryGetProperty("grammarItems", out var gi) && gi.ValueKind == JsonValueKind.Array && gi.GetArrayLength() > 0) - { - sb.AppendLine("### Mẫu ngữ pháp trong bài"); - foreach (var g in gi.EnumerateArray()) - { - var title = Str(g, "title") ?? Str(g, "pattern") ?? ""; - var meaning = Str(g, "meaningVi") ?? Str(g, "explanationVi") ?? Str(g, "usageNotes") ?? ""; - if (!string.IsNullOrWhiteSpace(title)) sb.AppendLine($"- **{title}**: {meaning}"); - } - sb.AppendLine(); - } - - if (r.TryGetProperty("readingPassages", out var rp) && rp.ValueKind == JsonValueKind.Array && rp.GetArrayLength() > 0) - { - foreach (var p in rp.EnumerateArray()) - { - var t = Str(p, "titleVi") ?? Str(p, "titleJa") ?? "Bài đọc"; - var tJa = Str(p, "titleJa"); - var text = Str(p, "passageJa") ?? Str(p, "passageText") ?? ""; - var trans = Str(p, "translationVi"); - sb.AppendLine($"### Bài đọc: {t}" + (!string.IsNullOrWhiteSpace(tJa) && tJa != t ? $" ({tJa})" : "")); - if (!string.IsNullOrWhiteSpace(text)) sb.AppendLine(text); - if (!string.IsNullOrWhiteSpace(trans)) sb.AppendLine().AppendLine($"*Dịch tham khảo:* {trans}"); - sb.AppendLine(); - } - } - - if (r.TryGetProperty("listeningItems", out var li) && li.ValueKind == JsonValueKind.Array && li.GetArrayLength() > 0) - { - foreach (var item in li.EnumerateArray()) - { - var topic = Str(item, "topic") ?? Str(item, "title") ?? "Bài nghe"; - var ctx = Str(item, "context") ?? ""; - var script = Str(item, "scriptJa") ?? Str(item, "transcript") ?? ""; - var trans = Str(item, "translationVi") ?? ""; - sb.AppendLine($"### Nghe hiểu: {topic}"); - if (!string.IsNullOrWhiteSpace(ctx)) sb.AppendLine($"**Ngữ cảnh:** {ctx}"); - if (!string.IsNullOrWhiteSpace(script)) sb.AppendLine().AppendLine("**Lời thoại (Transcript):**").AppendLine(script); - if (!string.IsNullOrWhiteSpace(trans)) sb.AppendLine().AppendLine("**Bản dịch:**").AppendLine(trans); - sb.AppendLine(); - } - } - } - - if (kaiwaList.Count > 0) - { - sb.AppendLine("### Hội thoại thực hành (Kaiwa)"); - foreach (var kw in kaiwaList) - { - var ped = Str(kw, "pedagogicalNoteVi"); - if (!string.IsNullOrWhiteSpace(ped)) sb.AppendLine($"*{ped}*"); - if (kw.TryGetProperty("turns", out var turns) && turns.ValueKind == JsonValueKind.Array) - { - foreach (var turn in turns.EnumerateArray()) - { - var sp = Str(turn, "speaker") ?? ""; - var textJa = Str(turn, "textJa") ?? Str(turn, "lineJa") ?? ""; - var textVi = Str(turn, "translationVi") ?? Str(turn, "meaningVi") ?? ""; - if (!string.IsNullOrWhiteSpace(textJa)) - sb.AppendLine($"- **{sp}:** {textJa}" + (!string.IsNullOrWhiteSpace(textVi) ? $" ({textVi})" : "")); - } - } - sb.AppendLine(); - } - } - - var output = sb.ToString().Trim(); - return string.IsNullOrWhiteSpace(output) ? Str(indexLesson, "titleVi") ?? "Nội dung bài học JLPT." : output; - } - - private static string? BuildLearningObjectives(JsonElement? richLesson, JsonElement indexLesson) - { - if (richLesson is { ValueKind: JsonValueKind.Object } r && - r.TryGetProperty("learningObjectives", out var objEl) && - objEl.ValueKind == JsonValueKind.Array) - { - var items = objEl.EnumerateArray() - .Where(x => x.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(x.GetString())) - .Select(x => "• " + x.GetString()!.Trim()) - .ToList(); - if (items.Count > 0) return string.Join("\n", items); - } - return Str(indexLesson, "multiSkillNote"); - } - - private static string? ResolvePrerequisiteTitle(JsonElement? richLesson, Dictionary lessonTitleByExtId) - { - if (richLesson is not { ValueKind: JsonValueKind.Object } r) return null; - if (!r.TryGetProperty("prerequisites", out var pr) || pr.ValueKind != JsonValueKind.Array) return null; - foreach (var item in pr.EnumerateArray()) - { - if (item.ValueKind != JsonValueKind.String || item.GetString() is not { } id) continue; - if (lessonTitleByExtId.TryGetValue(id, out var title)) return title; - } - return null; - } - - private static string? FirstResolvedAudio(JsonElement? richLesson) - { - if (richLesson is not { ValueKind: JsonValueKind.Object } r) return null; - if (!r.TryGetProperty("resolvedAudioReferences", out var arr) || arr.ValueKind != JsonValueKind.Array) return null; - return arr.EnumerateArray() - .Select(x => x.ValueKind == JsonValueKind.String ? x.GetString() : null) - .FirstOrDefault(s => !string.IsNullOrWhiteSpace(s) && s!.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)); - } - - private static LessonSnap? FindExistingLesson(DbSnapshot snap, string provenance, string title, int levelId) => - snap.Lessons.FirstOrDefault(l => - (!string.IsNullOrWhiteSpace(l.SourceProvenance) && l.SourceProvenance.Equals(provenance, StringComparison.OrdinalIgnoreCase)) || - (l.CertificateLevelId == levelId && l.Title.Equals(title, StringComparison.OrdinalIgnoreCase))); - - private static Dictionary FirstLessonLookup( - List links, - string itemKeyName, - HashSet selectedLessonIds, - Dictionary lessonTitleByExtId) - { - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var row in links) - { - var lid = Str(row, "lessonExternalId") ?? ""; - var iid = Str(row, itemKeyName) ?? ""; - if (!selectedLessonIds.Contains(lid) || string.IsNullOrWhiteSpace(iid)) continue; - if (lessonTitleByExtId.TryGetValue(lid, out var title)) - dict.TryAdd(iid, title); - } - return dict; - } - - private static int ResolveSkillId(DbSnapshot snap, string? raw) - { - var s = (raw ?? string.Empty).Trim().ToUpperInvariant(); - var candidates = s switch - { - "GRAMMAR" => new[] { "Grammar", "Ngữ pháp" }, - "READING" => new[] { "Reading", "Đọc hiểu" }, - "LISTENING" => new[] { "Listening", "Nghe hiểu" }, - "KANJI" => new[] { "Kanji", "Vocabulary", "Từ vựng" }, - "KAIWA" => new[] { "Listening", "Speaking", "Kaiwa" }, - _ => new[] { "Vocabulary", "Từ vựng" }, - }; - foreach (var name in candidates) - { - var hit = snap.SkillIdByName.FirstOrDefault(kv => kv.Key.Contains(name, StringComparison.OrdinalIgnoreCase)); - if (hit.Value > 0) return hit.Value; - } - return snap.SkillIdByName.Values.FirstOrDefault(1); - } - - private static CertificateSection MatchCertificateSection(List sections, JlptStudySkill skill) - { - bool Has(CertificateSection s, params string[] words) => - words.Any(w => s.Code.Contains(w, StringComparison.OrdinalIgnoreCase) || s.Name.Contains(w, StringComparison.OrdinalIgnoreCase)); - - var exact = skill switch - { - JlptStudySkill.Vocabulary => sections.FirstOrDefault(s => Has(s, "vocab", "goi", "moji", "từ")), - JlptStudySkill.Grammar => sections.FirstOrDefault(s => Has(s, "grammar", "bunpo") && !Has(s, "read", "dokkai")) - ?? sections.FirstOrDefault(s => Has(s, "gram", "language", "ngữ")), - JlptStudySkill.Reading => sections.FirstOrDefault(s => Has(s, "read", "dokkai") && !Has(s, "gram", "bunpo")) - ?? sections.FirstOrDefault(s => Has(s, "read", "gram", "language", "đọc")), - JlptStudySkill.Listening => sections.FirstOrDefault(s => Has(s, "listen", "chok", "chouk", "nghe")), - _ => null, - }; - return exact ?? sections[0]; - } - - private static JlptStudySkill ClassifyMockQuestionSkill(JsonElement q) - { - var sec = Str(q, "sectionCode") ?? Str(q, "section") ?? Str(q, "session") ?? ""; - var mondai = Str(q, "jlptMondai") ?? Str(q, "mondai") ?? ""; - var qtype = Str(q, "questionType") ?? ""; - - if (sec.Contains("LISTEN", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Listen", StringComparison.OrdinalIgnoreCase) || - mondai.StartsWith("Mondai 1", StringComparison.OrdinalIgnoreCase) && sec.Contains("Session2", StringComparison.OrdinalIgnoreCase) || - qtype.StartsWith("LISTEN", StringComparison.OrdinalIgnoreCase)) - return JlptStudySkill.Listening; - - if (mondai.Contains("Reading", StringComparison.OrdinalIgnoreCase) || - Str(q, "passageRefId") is not null || - Str(q, "passageId") is not null) - return JlptStudySkill.Reading; - - if (sec.Equals("VOCAB", StringComparison.OrdinalIgnoreCase) || - sec.Contains("Vocab", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Vocab", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Kanji", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Orthography", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Paraphrase", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Context", StringComparison.OrdinalIgnoreCase)) - return JlptStudySkill.Vocabulary; - - if (sec.Contains("GRAM", StringComparison.OrdinalIgnoreCase) || - mondai.Contains("Grammar", StringComparison.OrdinalIgnoreCase) || - qtype.Contains("STAR", StringComparison.OrdinalIgnoreCase)) - return JlptStudySkill.Grammar; - - return JlptStudySkill.Vocabulary; - } - - private static string CleanPythonList(string? raw) - { - if (string.IsNullOrWhiteSpace(raw)) return string.Empty; - var trimmed = raw.Trim(); - var m = PythonListRegex.Match(trimmed); - if (!m.Success) return trimmed; - var parts = m.Groups[1].Value - .Split(',', StringSplitOptions.RemoveEmptyEntries) - .Select(p => p.Trim().Trim('\'', '"', ' ')) - .Where(p => p.Length > 0); - return string.Join("、", parts); - } - - private static string SanitizeQuestionText(string raw) => - raw.Replace("Câu hỏi mẫu #", "Câu hỏi #", StringComparison.OrdinalIgnoreCase) - .Replace("(Chính xác)", "", StringComparison.OrdinalIgnoreCase) - .Trim(); - - private static string SanitizeOptionText(string raw) => - raw.Replace("(Chính xác)", "", StringComparison.OrdinalIgnoreCase) - .Replace("(Correct)", "", StringComparison.OrdinalIgnoreCase) - .Trim(); - - private static List DeduplicateOptions(List options) - { - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var result = new List(options.Count); - foreach (var opt in options) - { - var val = string.IsNullOrWhiteSpace(opt) ? "—" : opt; - var unique = val; - var suffix = 2; - while (!seen.Add(unique)) - unique = $"{val} ({suffix++})"; - result.Add(unique); - } - return result; - } - - private static string? CombineScriptAndTranslation(string? script, string? trans) - { - if (string.IsNullOrWhiteSpace(script) && string.IsNullOrWhiteSpace(trans)) return null; - if (string.IsNullOrWhiteSpace(trans)) return script?.Trim(); - if (string.IsNullOrWhiteSpace(script)) return trans.Trim(); - return $"{script.Trim()}\n\n[Dịch] {trans.Trim()}"; - } - - private static PackageScope NormalizeScope( - List? levels, - List? topicCodes, - List? mockTestIds, - bool includeLessons, - bool includeVocabKanjiGrammar, - bool includePracticeExercises, - bool includeSrsTemplates, - bool includeMockTests, - bool uploadAssets) - { - var cleanLevels = (levels ?? []) - .Select(x => x?.Trim().ToUpperInvariant() ?? "") - .Where(x => SupportedLevels.Contains(x)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - if (cleanLevels.Count == 0) cleanLevels = [.. SupportedLevels]; - - var cleanTopics = (topicCodes ?? []) - .Select(x => x?.Trim().ToUpperInvariant() ?? "") - .Where(x => x.Length > 0) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - var cleanMocks = (mockTestIds ?? []) - .Select(x => x?.Trim().ToUpperInvariant() ?? "") - .Where(x => x.Length > 0) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - return new PackageScope( - cleanLevels, cleanTopics, cleanMocks, - includeLessons, includeVocabKanjiGrammar, includePracticeExercises, - includeSrsTemplates, includeMockTests, uploadAssets); - } - - private static string? Str(JsonElement? el, string name) => - el is { ValueKind: JsonValueKind.Object } obj && obj.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String - ? v.GetString()?.Trim() - : null; - - private static int IntVal(JsonElement? el, string name, int fallback = 0) - { - if (el is not { ValueKind: JsonValueKind.Object } obj || !obj.TryGetProperty(name, out var v)) - return fallback; - if (v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var i)) return i; - if (v.ValueKind == JsonValueKind.String && int.TryParse(v.GetString(), out var parsed)) return parsed; - return fallback; - } - - private static string Truncate(string value, int maxLen) => - value.Length <= maxLen ? value : value[..maxLen]; - - private static string? TruncateNullable(string? value, int maxLen) => - string.IsNullOrWhiteSpace(value) ? null : (value.Trim().Length <= maxLen ? value.Trim() : value.Trim()[..maxLen]); - - private sealed record PackageScope( - List Levels, - HashSet TopicCodes, - HashSet MockTestIds, - bool IncludeLessons, - bool IncludeVocabKanjiGrammar, - bool IncludePracticeExercises, - bool IncludeSrsTemplates, - bool IncludeMockTests, - bool UploadAssets); - - private sealed record CsvAssetRow( - string AssetType, - string Level, - string AssetExternalId, - string LinkedChapterOrExam, - string LinkedLessonId, - string LinkedQuestionId, - string LogicalAssetPath); - - private sealed record LessonSnap(int Id, string Title, int CertificateLevelId, string? SourceProvenance); - - private sealed class RichCurriculumData - { - public Dictionary LessonsById { get; } = new(StringComparer.OrdinalIgnoreCase); - public Dictionary ChapterAssessmentsById { get; } = new(StringComparer.OrdinalIgnoreCase); - } - - private sealed class StagedCandidate - { - public ImportEntityType EntityType { get; init; } - public ImportRowAction Action { get; init; } - public int? TargetEntityId { get; init; } - public string? PayloadJson { get; init; } - public bool CanStage { get; init; } - public CurriculumPackagePreviewItemResponse Preview { get; init; } = new(); - } - - private sealed class BuiltPackageResult(DbSnapshot snapshot) - { - public DbSnapshot Snapshot { get; } = snapshot; - public List Items { get; } = []; - public List Issues { get; } = []; - public HashSet ReferencedAudioKeys { get; } = new(StringComparer.OrdinalIgnoreCase); - public HashSet ReferencedImageKeys { get; } = new(StringComparer.OrdinalIgnoreCase); - public int UploadedAudioCount { get; set; } - public int UploadedImageCount { get; set; } - } - - private sealed class DbSnapshot - { - public Dictionary LevelIdByCode { get; init; } = new(StringComparer.OrdinalIgnoreCase); - public Dictionary SkillIdByName { get; init; } = new(StringComparer.OrdinalIgnoreCase); - public Dictionary SkillNameById { get; init; } = []; - public Dictionary> CertSectionsByLevelId { get; init; } = []; - public List Lessons { get; init; } = []; - public Dictionary VocabIdByWordReading { get; init; } = new(StringComparer.OrdinalIgnoreCase); - public Dictionary KanjiIdByChar { get; init; } = new(StringComparer.Ordinal); - public Dictionary GrammarIdByTitle { get; init; } = new(StringComparer.OrdinalIgnoreCase); - public Dictionary<(int LevelId, string Title), int> ExerciseIdByLevelTitle { get; init; } = []; - public Dictionary MockIdBySourceOrTitle { get; init; } = new(StringComparer.OrdinalIgnoreCase); - public Dictionary<(int LevelId, string Title), int> MockIdByLevelTitle { get; init; } = []; - public Dictionary SrsIdByNormalizedKey { get; init; } = new(StringComparer.OrdinalIgnoreCase); - public HashSet<(ImportEntityType, string)> OpenOrApprovedRowKeys { get; init; } = []; - public HashSet<(ImportEntityType, int)> OpenTargetIds { get; init; } = []; - public HashSet<(string LessonTitle, int LevelId, int VocabId)> LessonVocabPairs { get; init; } = []; - public HashSet<(string LessonTitle, int LevelId, int KanjiId)> LessonKanjiPairs { get; init; } = []; - public HashSet<(string LessonTitle, int LevelId, int GrammarId)> LessonGrammarPairs { get; init; } = []; - } -} diff --git a/RikiPath.WebApi/Controllers/ContentApprovalController.cs b/RikiPath.WebApi/Controllers/ContentApprovalController.cs index 41c71e3..9b8a414 100644 --- a/RikiPath.WebApi/Controllers/ContentApprovalController.cs +++ b/RikiPath.WebApi/Controllers/ContentApprovalController.cs @@ -149,5 +149,18 @@ public async Task UnpublishV2( var result = await moderationV2.UnpublishAsync(request, claimService.GetUserClaim().Id, cancellationToken); return StatusCode(result.StatusCode, result); } + + [HttpPost("v2/republish")] + [Authorize(Roles = "Admin")] + public async Task RepublishV2( + [FromBody] UnpublishContentRequest request, + CancellationToken cancellationToken) + { + var user = claimService.GetUserClaim(); + var adminEmail = User.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value; + var adminName = string.IsNullOrWhiteSpace(adminEmail) ? (User.Identity?.Name ?? $"Admin #{user.Id}") : adminEmail; + var result = await moderationV2.RepublishAsync(request, user.Id, adminName, cancellationToken); + return StatusCode(result.StatusCode, result); + } } } diff --git a/RikiPath.WebApi/Controllers/ContentImportController.cs b/RikiPath.WebApi/Controllers/ContentImportController.cs index fb0dfe1..29a6f33 100644 --- a/RikiPath.WebApi/Controllers/ContentImportController.cs +++ b/RikiPath.WebApi/Controllers/ContentImportController.cs @@ -17,7 +17,6 @@ namespace RikiPath.Api.Controllers [Route("api/content-import")] [Authorize(Roles = "ContentAuthor,Admin")] public class ContentImportController(IExcelContentImportService importService, IFileStorageService fileStorage, - ICurriculumPackageImportService? curriculumImport = null, IContentAudioTranscriptionService? transcriptions = null, ILogger? logger = null, IAwsAudioFileStorageService? awsAudio = null) : ControllerBase @@ -32,16 +31,15 @@ public class ContentImportController(IExcelContentImportService importService, I [RequestFormLimits(MultipartBodyLengthLimit = ListeningAudioFilePolicy.MaxBytes + 4L * 1024 * 1024)] public async Task UploadListeningAudio(IFormFile? file, CancellationToken cancellationToken) { - var extension = file is null ? null : Path.GetExtension(file.FileName); - if (file is null || file.Length < 12 || !ListeningAudioFilePolicy.IsSupportedExtension(extension)) - return BadRequest(ApiResponse.Fail("Vui lòng chọn file nghe .mp3 hoặc .wav.")); + if (file is null || file.Length < 4 || !string.Equals(Path.GetExtension(file.FileName), ".mp3", StringComparison.OrdinalIgnoreCase)) + return BadRequest(ApiResponse.Fail("Vui lòng chọn file nghe .mp3.")); await using var stream = file.OpenReadStream(); - if (!await ListeningAudioFilePolicy.HasSupportedAudioHeaderAsync(stream, file.FileName, cancellationToken)) - return BadRequest(ApiResponse.Fail("File nghe không có định dạng MP3 hoặc WAV hợp lệ.")); + if (!await HasMp3HeaderAsync(stream, cancellationToken)) + return BadRequest(ApiResponse.Fail("File nghe không có định dạng MP3 hợp lệ.")); if (file.Length > ListeningAudioFilePolicy.MaxBytes) - return BadRequest(ApiResponse.Fail("File âm thanh không được vượt quá 500 MB.")); + return BadRequest(ApiResponse.Fail("File MP3 không được vượt quá 500 MB.")); await using var audio = file.OpenReadStream(); if (transcriptions is not null) @@ -74,8 +72,7 @@ public async Task UploadListeningAudio(IFormFile? file, Cancellat return StatusCode(failure.StatusCode, failure); } } - var contentType = ListeningAudioFilePolicy.GetContentType(extension); - var uploaded = await fileStorage.UploadAsync(audio, file.FileName, contentType, "jlpt-listening", cancellationToken); + var uploaded = await fileStorage.UploadAsync(audio, file.FileName, "audio/mpeg", "jlpt-listening", cancellationToken); uploaded = uploaded with { Url = NormalizeLocalMediaUrl(uploaded.Url) }; return Ok(ApiResponse.Success(uploaded)); } @@ -241,10 +238,10 @@ private async Task UploadLocalMediaAsync(string path, bool isAudio, Canc throw new InvalidDataException("Đường dẫn file phải nằm trong thư mục import được phép."); var extension = Path.GetExtension(fullPath).ToLowerInvariant(); var contentType = isAudio - ? (ListeningAudioFilePolicy.IsSupportedExtension(extension) ? ListeningAudioFilePolicy.GetContentType(extension) : null) + ? (extension == ".mp3" ? "audio/mpeg" : null) : extension switch { ".jpg" or ".jpeg" => "image/jpeg", ".png" => "image/png", ".webp" => "image/webp", ".gif" => "image/gif", _ => null }; if (contentType is null) - throw new InvalidDataException(isAudio ? "Đường dẫn audio phải trỏ tới file .mp3 hoặc .wav." : "Ảnh phải là JPG, PNG, WebP hoặc GIF."); + throw new InvalidDataException(isAudio ? "Đường dẫn audio phải trỏ tới file .mp3." : "Ảnh phải là JPG, PNG, WebP hoặc GIF."); for (string? entry = fullPath; entry is not null; entry = Path.GetDirectoryName(entry)) { @@ -254,9 +251,9 @@ private async Task UploadLocalMediaAsync(string path, bool isAudio, Canc await using var audio = System.IO.File.OpenRead(fullPath); if (audio.Length > (isAudio ? 25 * 1024 * 1024 : ImportImageFiles.MaxImageBytes)) - throw new InvalidDataException(isAudio ? "File âm thanh tối đa 25 MB." : "Ảnh tối đa 10 MB."); - if (isAudio && !await ListeningAudioFilePolicy.HasSupportedAudioHeaderAsync(audio, fullPath, cancellationToken)) - throw new InvalidDataException("File nghe không có định dạng MP3 hoặc WAV hợp lệ."); + throw new InvalidDataException(isAudio ? "MP3 tối đa 25 MB." : "Ảnh tối đa 10 MB."); + if (isAudio && !await HasMp3HeaderAsync(audio, cancellationToken)) + throw new InvalidDataException("File nghe không có định dạng MP3 hợp lệ."); audio.Position = 0; if (!isAudio) { @@ -293,6 +290,18 @@ private async Task UploadLocalMediaAsync(string path, bool isAudio, Canc } } + private static async Task HasMp3HeaderAsync(Stream audio, CancellationToken cancellationToken) + { + var header = new byte[4]; + if (await audio.ReadAtLeastAsync(header, header.Length, false, cancellationToken) < header.Length) + return false; + + var hasId3 = header[0] == 'I' && header[1] == 'D' && header[2] == '3' && header[3] is >= 2 and <= 4; + var hasMp3Frame = header[0] == 0xff && (header[1] & 0xe6) == 0xe2 && + (header[1] & 0x18) != 0x08 && (header[2] & 0xf0) != 0xf0 && (header[2] & 0x0c) != 0x0c; + return hasId3 || hasMp3Frame; + } + /// /// Lưu các dòng hợp lệ từ bản xem trước thành bản nháp của tác giả. Với file lớn, /// gửi các nhóm dòng tuần tự cùng BatchId; chỉ gửi duyệt khi mọi nhóm đã lưu xong. @@ -324,52 +333,6 @@ public async Task Confirm( return Ok(result); } - [HttpGet("curriculum-package/inventory")] - [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] - public async Task GetCurriculumPackageInventory(CancellationToken cancellationToken) - { - if (curriculumImport is null) - return StatusCode(503, ApiResponse.Fail("Dịch vụ nhập gói giáo trình chưa được kích hoạt.")); - - var result = await curriculumImport.GetInventoryAsync(cancellationToken); - return result.IsSuccess ? Ok(result) : BadRequest(result); - } - - [HttpPost("curriculum-package/preview")] - [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status400BadRequest)] - public async Task PreviewCurriculumPackage( - [FromBody] CurriculumPackagePreviewRequest request, - CancellationToken cancellationToken) - { - if (curriculumImport is null) - return StatusCode(503, ApiResponse.Fail("Dịch vụ nhập gói giáo trình chưa được kích hoạt.")); - - var result = await curriculumImport.PreviewAsync(request ?? new CurriculumPackagePreviewRequest(), cancellationToken); - return result.IsSuccess ? Ok(result) : BadRequest(result); - } - - [HttpPost("curriculum-package/confirm")] - [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status400BadRequest)] - public async Task ConfirmCurriculumPackage( - [FromBody] CurriculumPackageConfirmRequest request, - CancellationToken cancellationToken) - { - if (curriculumImport is null) - return StatusCode(503, ApiResponse.Fail("Dịch vụ nhập gói giáo trình chưa được kích hoạt.")); - - var actorUserId = GetCurrentUserId(); - if (actorUserId is null) - return Unauthorized(ApiResponse.Fail("Không xác định được thông tin người dùng.")); - - var result = await curriculumImport.ConfirmAsync( - request ?? new CurriculumPackageConfirmRequest(), - actorUserId.Value, - cancellationToken); - return result.IsSuccess ? Ok(result) : BadRequest(result); - } - /// /// Trích xuất UserId của người dùng hiện tại từ Claims/Token JWT /// diff --git a/RikiPath.WebApi/Controllers/ContentTemplatesAndExportController.cs b/RikiPath.WebApi/Controllers/ContentTemplatesAndExportController.cs index 7d73e37..dfb9a50 100644 --- a/RikiPath.WebApi/Controllers/ContentTemplatesAndExportController.cs +++ b/RikiPath.WebApi/Controllers/ContentTemplatesAndExportController.cs @@ -62,6 +62,7 @@ public async Task ConfirmUnifiedArchive( IFormFile? file, [FromQuery] UnifiedImportKind expectedKind = UnifiedImportKind.Auto, [FromQuery] string? idempotencyKey = null, + [FromQuery] bool submitForReview = false, CancellationToken ct = default) { if (file is null || file.Length == 0) @@ -69,7 +70,7 @@ public async Task ConfirmUnifiedArchive( await using var stream = file.OpenReadStream(); var res = await unifiedImportService.ConfirmFromArchiveAsync( - stream, file.FileName, expectedKind, idempotencyKey, claimService.GetUserClaim().Id, ct); + stream, file.FileName, expectedKind, idempotencyKey, claimService.GetUserClaim().Id, ct, submitForReview); return StatusCode(res.StatusCode, res); } diff --git a/RikiPath.WebApi/Controllers/ExamBuilderController.cs b/RikiPath.WebApi/Controllers/ExamBuilderController.cs index eee7f6e..a1b1870 100644 --- a/RikiPath.WebApi/Controllers/ExamBuilderController.cs +++ b/RikiPath.WebApi/Controllers/ExamBuilderController.cs @@ -43,6 +43,13 @@ public async Task SaveDraft([FromBody] ExamBuilderDto request, Ca return StatusCode(res.StatusCode, res); } + [HttpPost("submit")] + public async Task SaveAndSubmit([FromBody] ExamBuilderDto request, CancellationToken ct) + { + var res = await examBuilderService.SaveAndSubmitAsync(request, claimService.GetUserClaim().Id, ct); + return StatusCode(res.StatusCode, res); + } + [HttpPost("{examId:int}/new-version")] public async Task CreateNewVersion(int examId, CancellationToken ct) { diff --git a/RikiPath.WebApi/Controllers/FileStorageController.cs b/RikiPath.WebApi/Controllers/FileStorageController.cs index 06ff8aa..40555d3 100644 --- a/RikiPath.WebApi/Controllers/FileStorageController.cs +++ b/RikiPath.WebApi/Controllers/FileStorageController.cs @@ -62,7 +62,7 @@ public async Task Upload(IFormFile file, [FromQuery] string folde if (transcriptions is not null && claims is not null && fileStorageService is not LocalDevMediaStorageService && (User.IsInRole("ContentAuthor") || User.IsInRole("Admin")) && - RikiPath.Application.Services.ListeningAudioFilePolicy.IsSupportedExtension(ext)) + ext.Equals(".mp3", StringComparison.OrdinalIgnoreCase)) { try { diff --git a/RikiPath.WebApi/Controllers/ManualContentController.cs b/RikiPath.WebApi/Controllers/ManualContentController.cs index 12f92e1..b5fb32d 100644 --- a/RikiPath.WebApi/Controllers/ManualContentController.cs +++ b/RikiPath.WebApi/Controllers/ManualContentController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using RikiPath.Application; +using RikiPath.Application.Responses.Content; using RikiPath.Application.Services; using RikiPath.Domain.Enums; @@ -35,6 +36,16 @@ public async Task Lessons(int levelId, CancellationToken ct) => O await uow.Lessons.Query().Where(x => !x.IsDeleted && x.CertificateLevelId == levelId) .OrderBy(x => x.Title).Select(x => new { x.Id, x.Title }).ToListAsync(ct)); + [HttpPost("unified/{type}/search")] + public async Task SearchUnified( + ImportEntityType type, + [FromBody] UnifiedAuthorContentSearchRequest? filter, + CancellationToken ct) + { + var result = await service.SearchUnifiedAsync(type, filter ?? new(), ct); + return StatusCode(result.StatusCode, result); + } + [HttpGet("items/{type}")] public async Task List(ImportEntityType type, [FromQuery] ContentApprovalStatus? status, CancellationToken ct) => Ok(await service.ListAsync(type, status, ct)); @@ -83,9 +94,15 @@ public async Task Detail(int id, CancellationToken ct) [HttpPost("items/{type}")] [HttpPut("items/{type}/{id:int}")] - public async Task Save(ImportEntityType type, int? id, [FromBody] JsonElement input, CancellationToken ct) + public async Task Save( + ImportEntityType type, + int? id, + [FromBody] JsonElement input, + [FromQuery] bool submitForReview = false, + [FromQuery] int? targetEntityId = null, + CancellationToken ct = default) { - var result = await service.SaveAsync(type, id, input, ct); + var result = await service.SaveAsync(type, id, input, ct, submitForReview, targetEntityId); return StatusCode(result.StatusCode, result); } diff --git a/RikiPath.WebApi/Controllers/SharedBankController.cs b/RikiPath.WebApi/Controllers/SharedBankController.cs index 043ad37..550814d 100644 --- a/RikiPath.WebApi/Controllers/SharedBankController.cs +++ b/RikiPath.WebApi/Controllers/SharedBankController.cs @@ -144,5 +144,21 @@ public async Task GetQuestionDetail(int id, CancellationToken can var result = await sharedBankSearchService.GetQuestionDetailAsync(id, cancellationToken); return StatusCode((int)result.StatusCode, result); } + + [HttpPost("lessons/search")] + [Authorize(Roles = "ContentAuthor,Admin")] + public async Task SearchLessons([FromBody] LessonSearchFilter filter, CancellationToken cancellationToken) + { + var result = await sharedBankSearchService.SearchLessonsAsync(filter, cancellationToken); + return StatusCode((int)result.StatusCode, result); + } + + [HttpGet("lessons/{id:int}")] + [Authorize(Roles = "ContentAuthor,Admin")] + public async Task GetLessonDetail(int id, CancellationToken cancellationToken) + { + var result = await sharedBankSearchService.GetLessonDetailAsync(id, cancellationToken); + return StatusCode((int)result.StatusCode, result); + } } } diff --git a/RikiPath.WebApi/Services/ImportAudioFiles.cs b/RikiPath.WebApi/Services/ImportAudioFiles.cs index ff5eb3d..13d9692 100644 --- a/RikiPath.WebApi/Services/ImportAudioFiles.cs +++ b/RikiPath.WebApi/Services/ImportAudioFiles.cs @@ -16,11 +16,11 @@ public ImportAudioFiles(IEnumerable? files, IAwsAudioFileStorageServi IContentAudioTranscriptionService? transcripts, int authorId, Func> readServerFile) { - selected = (files ?? []).Where(file => ListeningAudioFilePolicy.IsSupportedExtension(Path.GetExtension(file.FileName))).ToList(); + selected = (files ?? []).Where(file => file.FileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)).ToList(); if (selected.Count > 1) - throw new InvalidDataException("Mỗi lần chỉ được tải lên một file âm thanh (MP3/WAV)."); - if (selected.Any(file => file.Length < 12 || file.Length > ListeningAudioFilePolicy.MaxBytes)) - throw new InvalidDataException("File âm thanh phải có dữ liệu và không vượt quá 500 MB."); + throw new InvalidDataException("Mỗi lần chỉ được tải lên một file MP3."); + if (selected.Any(file => file.Length < 4 || file.Length > ListeningAudioFilePolicy.MaxBytes)) + throw new InvalidDataException("File MP3 phải có dữ liệu và không vượt quá 500 MB."); this.aws = aws; this.transcripts = transcripts; this.authorId = authorId; @@ -39,7 +39,7 @@ public async Task ResolveAsync(string source, CancellationToken ct) } var previous = transcripts is null ? null : await transcripts.QueueAsync(source, authorId, ct); if (previous is not null) return previous.AudioUrl; - throw new InvalidDataException("AudioUrl phải là file MP3/WAV trong bucket S3 đã cấu hình hoặc audio đã lưu trên hệ thống."); + throw new InvalidDataException("AudioUrl phải là MP3 trong bucket S3 đã cấu hình hoặc audio đã lưu trên hệ thống."); } var path = Normalize(source); var matches = selected.Where(file => path.Equals(Normalize(file.FileName), StringComparison.OrdinalIgnoreCase) || @@ -52,7 +52,7 @@ public async Task ResolveAsync(string source, CancellationToken ct) .Equals(name, StringComparison.OrdinalIgnoreCase)).ToList(); } if (matches.Count > 1) - throw new InvalidDataException("Có nhiều file âm thanh trùng tên. Điền đường dẫn thư mục tương đối đầy đủ trong Excel."); + throw new InvalidDataException("Có nhiều MP3 trùng tên. Điền đường dẫn thư mục tương đối đầy đủ trong Excel."); if (matches.Count == 1) { if (uploaded.TryGetValue(matches[0], out var existing)) return existing;