diff --git a/RikiPath.Application/Common/LearningPathTestFixture.cs b/RikiPath.Application/Common/LearningPathTestFixture.cs
new file mode 100644
index 0000000..a166752
--- /dev/null
+++ b/RikiPath.Application/Common/LearningPathTestFixture.cs
@@ -0,0 +1,14 @@
+namespace RikiPath.Application.Common;
+
+///
+/// Marks learning paths written by the deterministic M4E2E test stub (no AI model involved).
+/// Such rows are only valid in a disposable test database; the API flags them so they are never
+/// presented to a learner as a real AI recommendation.
+///
+public static class LearningPathTestFixture
+{
+ public const string SummaryMarker = "[M4E2E TEST STUB — NOT REAL AI OUTPUT]";
+
+ public static bool IsTestFixture(string? summary)
+ => summary?.StartsWith(SummaryMarker, StringComparison.Ordinal) == true;
+}
diff --git a/RikiPath.Application/Responses/LearningPaths/LearningPathGenerationStatusResponse.cs b/RikiPath.Application/Responses/LearningPaths/LearningPathGenerationStatusResponse.cs
new file mode 100644
index 0000000..b00bccd
--- /dev/null
+++ b/RikiPath.Application/Responses/LearningPaths/LearningPathGenerationStatusResponse.cs
@@ -0,0 +1,65 @@
+namespace RikiPath.Application.Responses.LearningPaths
+{
+ ///
+ /// Real server-side state of the learner's latest AI learning-path generation.
+ /// Every field reflects work the server has actually done; nothing is simulated.
+ /// The state lives in this API process only: a server restart resets it to "idle".
+ ///
+ public class LearningPathGenerationStatusResponse
+ {
+ /// idle | running | succeeded | failed
+ public string State { get; set; } = LearningPathGenerationStates.Idle;
+
+ /// generate (first ACTIVE path) | preview (DRAFT for a level change).
+ public string? Kind { get; set; }
+
+ /// preparing | analyzing | designing | saving — the step the server is executing now.
+ public string? Stage { get; set; }
+
+ /// Number of 30-day AI batches already accepted.
+ public int? CompletedBatches { get; set; }
+
+ /// Total number of 30-day AI batches the plan needs (known once the plan length is computed).
+ public int? TotalBatches { get; set; }
+
+ public int? PlanDurationDays { get; set; }
+
+ ///
+ /// True when the work keeps running on the server if the learner leaves the page
+ /// (generate). False when closing the request cancels it (preview).
+ ///
+ public bool ContinuesWhenClientLeaves { get; set; }
+
+ public DateTime? StartedAt { get; set; }
+ public DateTime? UpdatedAt { get; set; }
+ public DateTime? FinishedAt { get; set; }
+
+ /// Saved path id when State = succeeded.
+ public int? PathId { get; set; }
+
+ public string? ErrorCode { get; set; }
+ public string? ErrorMessage { get; set; }
+
+ ///
+ /// True only when the server confirmed no AI credit was consumed by this failed run
+ /// (credit was never reserved, or the reservation was refunded). Null when unknown.
+ ///
+ public bool? CreditsPreserved { get; set; }
+ }
+
+ public static class LearningPathGenerationStates
+ {
+ public const string Idle = "idle";
+ public const string Running = "running";
+ public const string Succeeded = "succeeded";
+ public const string Failed = "failed";
+ }
+
+ public static class LearningPathGenerationStages
+ {
+ public const string Preparing = "preparing";
+ public const string Analyzing = "analyzing";
+ public const string Designing = "designing";
+ public const string Saving = "saving";
+ }
+}
diff --git a/RikiPath.Application/Responses/LearningPaths/LearningPathResponse.cs b/RikiPath.Application/Responses/LearningPaths/LearningPathResponse.cs
index 4abdab5..a5227f3 100644
--- a/RikiPath.Application/Responses/LearningPaths/LearningPathResponse.cs
+++ b/RikiPath.Application/Responses/LearningPaths/LearningPathResponse.cs
@@ -61,6 +61,9 @@ public class LearningPathResponse
public DateTime? SuggestedExamDate { get; set; }
public List FocusTopics { get; set; } = new();
+
+ /// true = lộ trình do stub kiểm thử M4E2E sinh ra, không phải đề xuất AI thật.
+ public bool IsTestFixture { get; set; }
public List DailySchedules { get; set; } = new();
}
}
diff --git a/RikiPath.Application/Services/AdminBusinessConfigService.cs b/RikiPath.Application/Services/AdminBusinessConfigService.cs
index 5b9c771..cb9625b 100644
--- a/RikiPath.Application/Services/AdminBusinessConfigService.cs
+++ b/RikiPath.Application/Services/AdminBusinessConfigService.cs
@@ -103,12 +103,19 @@ public async Task> SaveSubscriptionPlanAsy
"SUBSCRIPTION_PLAN_DESCRIPTION_TOO_LONG");
var category = request.PlanCategory?.Trim().ToLowerInvariant() ?? string.Empty;
- if (!SubscriptionAccessService.SellableCategories.Contains(category))
+ var isLegacyCategory = SubscriptionAccessService.IsLegacyAiCategory(category);
+ if (!SubscriptionAccessService.SellableCategories.Contains(category) && !(id.HasValue && isLegacyCategory))
return ApiResponse.Fail(
- "Loại gói học không hợp lệ. Chỉ chấp nhận: self_study, speaking, writing, ai_grading, learning_path, combo.",
+ "Loại gói học không hợp lệ. Chỉ chấp nhận: Gói tự học (self_study), Gói AI (ai_pack), Gói kết hợp toàn diện (combo).",
HttpStatusCode.BadRequest,
"PLAN_CATEGORY_INVALID");
+ if (isLegacyCategory && request.IsActive)
+ return ApiResponse.Fail(
+ "Nhóm gói AI cũ đã ngừng mở bán theo mô hình mới. Chỉ cho phép ngừng bán hoặc tạo lựa chọn mới trong Gói AI.",
+ HttpStatusCode.BadRequest,
+ "PLAN_CATEGORY_RETIRED");
+
if (request.Price < 0 || request.Price != decimal.Truncate(request.Price) || request.Price > int.MaxValue)
return ApiResponse.Fail(
"Giá gói phải là số nguyên VND không âm.",
@@ -121,18 +128,30 @@ public async Task> SaveSubscriptionPlanAsy
HttpStatusCode.BadRequest,
"SUBSCRIPTION_PLAN_PRICE_REQUIRED");
- var isCredit = SubscriptionAccessService.IsCreditCategory(category);
- if (isCredit && request.DurationDays != 0)
- return ApiResponse.Fail(
- "Gói mua theo lượt AI phải có thời hạn bằng 0 ngày.",
- HttpStatusCode.BadRequest,
- "SUBSCRIPTION_PLAN_DURATION_INVALID");
-
- if (!isCredit && request.DurationDays is < 1 or > 1095)
- return ApiResponse.Fail(
- "Thời hạn gói học phải từ 1 đến 1095 ngày.",
- HttpStatusCode.BadRequest,
- "SUBSCRIPTION_PLAN_DURATION_INVALID");
+ if (string.Equals(category, SubscriptionAccessService.CategoryAiPack, StringComparison.OrdinalIgnoreCase))
+ {
+ if (request.DurationDays is < 0 or > 1095)
+ return ApiResponse.Fail(
+ "Thời hạn sử dụng lượt AI phải từ 0 đến 1095 ngày (0 = không giới hạn ngày).",
+ HttpStatusCode.BadRequest,
+ "SUBSCRIPTION_PLAN_DURATION_INVALID");
+ }
+ else if (isLegacyCategory)
+ {
+ if (request.DurationDays is < 0 or > 1095)
+ return ApiResponse.Fail(
+ "Thời hạn gói học phải từ 0 đến 1095 ngày.",
+ HttpStatusCode.BadRequest,
+ "SUBSCRIPTION_PLAN_DURATION_INVALID");
+ }
+ else
+ {
+ if (request.DurationDays is < 1 or > 1095)
+ return ApiResponse.Fail(
+ "Thời hạn gói học phải từ 1 đến 1095 ngày.",
+ HttpStatusCode.BadRequest,
+ "SUBSCRIPTION_PLAN_DURATION_INVALID");
+ }
if (request.AiGradingQuota is < 0 or > 5000)
return ApiResponse.Fail(
@@ -142,7 +161,7 @@ public async Task> SaveSubscriptionPlanAsy
if (category != SubscriptionAccessService.CategorySelfStudy && request.AiGradingQuota < 1)
return ApiResponse.Fail(
- "Gói kỹ năng hoặc lượt AI cần tối thiểu 1 lượt sử dụng AI.",
+ "Gói AI hoặc gói kết hợp cần tối thiểu 1 lượt sử dụng AI.",
HttpStatusCode.BadRequest,
"SUBSCRIPTION_PLAN_QUOTA_INVALID");
@@ -196,6 +215,22 @@ await uow.ExecuteInTransactionAsync(async token =>
return;
}
+ var existingCategory = SubscriptionAccessService.ResolveCategory(existing, existing.Id);
+ if (!string.Equals(existingCategory, category, StringComparison.OrdinalIgnoreCase))
+ {
+ var hasPaidPurchases = await uow.UserSubscriptions.Query()
+ .AsNoTracking()
+ .AnyAsync(s => !s.IsDeleted && s.SubscriptionPlanId == existing.Id && s.PaymentStatus == PaymentStatus.Paid, token);
+ if (hasPaidPurchases)
+ {
+ failure = ApiResponse.Fail(
+ "Không thể đổi nhóm của gói đã có đơn thanh toán để bảo toàn quyền lợi lịch sử.",
+ HttpStatusCode.Conflict,
+ "PLAN_CATEGORY_LOCKED_BY_ORDERS");
+ return;
+ }
+ }
+
beforeJson = JsonSerializer.Serialize(new
{
existing.Id,
diff --git a/RikiPath.Application/Services/LearningMomentService.cs b/RikiPath.Application/Services/LearningMomentService.cs
index 64314a9..f598329 100644
--- a/RikiPath.Application/Services/LearningMomentService.cs
+++ b/RikiPath.Application/Services/LearningMomentService.cs
@@ -498,6 +498,7 @@ private async Task> BuildCandidatesAsync(int userId, DateT
var ctaHref = category switch
{
SubscriptionAccessService.CategorySelfStudy or SubscriptionAccessService.CategoryCombo => "/lessons/",
+ SubscriptionAccessService.CategoryAiPack => activePath is null ? "/roadmap/" : "/riki/speaking/",
SubscriptionAccessService.CategoryLearningPath => "/roadmap/",
SubscriptionAccessService.CategorySpeaking => "/riki/speaking/",
SubscriptionAccessService.CategoryWriting => "/riki/essay/",
diff --git a/RikiPath.Application/Services/LearningPathGenerationTracker.cs b/RikiPath.Application/Services/LearningPathGenerationTracker.cs
new file mode 100644
index 0000000..194441b
--- /dev/null
+++ b/RikiPath.Application/Services/LearningPathGenerationTracker.cs
@@ -0,0 +1,130 @@
+using System.Collections.Concurrent;
+using RikiPath.Application.Responses.LearningPaths;
+
+namespace RikiPath.Application.Services
+{
+ ///
+ /// Process-local, per-learner record of the AI learning-path generation the server is executing.
+ /// Registered as a singleton. Only the request that owns the generation writes to it, so the
+ /// status endpoint reports real stages and real batch counts, never a simulated progress.
+ ///
+ public sealed class LearningPathGenerationTracker
+ {
+ /// Finished results stay readable this long so a reloaded page can still recover them.
+ private static readonly TimeSpan FinishedRetention = TimeSpan.FromMinutes(30);
+
+ /// A running entry with no update for this long can no longer be trusted (owner vanished).
+ private static readonly TimeSpan StaleRunning = TimeSpan.FromMinutes(15);
+
+ private readonly ConcurrentDictionary states = new();
+
+ public Func UtcNowProvider { get; init; } = static () => DateTime.UtcNow;
+
+ public LearningPathGenerationStatusResponse Get(int userId)
+ {
+ if (!states.TryGetValue(userId, out var current))
+ return new LearningPathGenerationStatusResponse();
+
+ var now = UtcNowProvider();
+ var expired = current.State == LearningPathGenerationStates.Running
+ ? now - (current.UpdatedAt ?? now) > StaleRunning
+ : now - (current.FinishedAt ?? now) > FinishedRetention;
+ if (!expired)
+ return Clone(current);
+
+ states.TryRemove(new KeyValuePair(userId, current));
+ return new LearningPathGenerationStatusResponse();
+ }
+
+ public void Start(int userId, string kind, bool continuesWhenClientLeaves)
+ {
+ var now = UtcNowProvider();
+ states[userId] = new LearningPathGenerationStatusResponse
+ {
+ State = LearningPathGenerationStates.Running,
+ Kind = kind,
+ Stage = LearningPathGenerationStages.Preparing,
+ ContinuesWhenClientLeaves = continuesWhenClientLeaves,
+ StartedAt = now,
+ UpdatedAt = now,
+ };
+ }
+
+ /// Records the stage the server just entered. Ignored when no run is active for the learner.
+ public void ReportStage(int userId, string stage, int? completedBatches = null, int? totalBatches = null,
+ int? planDurationDays = null)
+ {
+ Update(userId, current =>
+ {
+ if (current.State != LearningPathGenerationStates.Running) return null;
+ var next = Clone(current);
+ next.Stage = stage;
+ next.CompletedBatches = completedBatches ?? current.CompletedBatches;
+ next.TotalBatches = totalBatches ?? current.TotalBatches;
+ next.PlanDurationDays = planDurationDays ?? current.PlanDurationDays;
+ next.UpdatedAt = UtcNowProvider();
+ return next;
+ });
+ }
+
+ public void Succeed(int userId, int? pathId)
+ {
+ Update(userId, current =>
+ {
+ var next = Clone(current);
+ var now = UtcNowProvider();
+ next.State = LearningPathGenerationStates.Succeeded;
+ next.Stage = null;
+ next.PathId = pathId;
+ if (next.TotalBatches.HasValue) next.CompletedBatches = next.TotalBatches;
+ next.UpdatedAt = now;
+ next.FinishedAt = now;
+ return next;
+ });
+ }
+
+ public void Fail(int userId, string? errorCode, string? errorMessage, bool? creditsPreserved)
+ {
+ Update(userId, current =>
+ {
+ var next = Clone(current);
+ var now = UtcNowProvider();
+ next.State = LearningPathGenerationStates.Failed;
+ next.Stage = null;
+ next.ErrorCode = errorCode;
+ next.ErrorMessage = errorMessage;
+ next.CreditsPreserved = creditsPreserved;
+ next.UpdatedAt = now;
+ next.FinishedAt = now;
+ return next;
+ });
+ }
+
+ private void Update(int userId, Func change)
+ {
+ while (states.TryGetValue(userId, out var current))
+ {
+ var next = change(current);
+ if (next is null || states.TryUpdate(userId, next, current)) return;
+ }
+ }
+
+ private static LearningPathGenerationStatusResponse Clone(LearningPathGenerationStatusResponse source) => new()
+ {
+ State = source.State,
+ Kind = source.Kind,
+ Stage = source.Stage,
+ CompletedBatches = source.CompletedBatches,
+ TotalBatches = source.TotalBatches,
+ PlanDurationDays = source.PlanDurationDays,
+ ContinuesWhenClientLeaves = source.ContinuesWhenClientLeaves,
+ StartedAt = source.StartedAt,
+ UpdatedAt = source.UpdatedAt,
+ FinishedAt = source.FinishedAt,
+ PathId = source.PathId,
+ ErrorCode = source.ErrorCode,
+ ErrorMessage = source.ErrorMessage,
+ CreditsPreserved = source.CreditsPreserved,
+ };
+ }
+}
diff --git a/RikiPath.Application/Services/LearningPathService.cs b/RikiPath.Application/Services/LearningPathService.cs
index dd7cd03..aa637da 100644
--- a/RikiPath.Application/Services/LearningPathService.cs
+++ b/RikiPath.Application/Services/LearningPathService.cs
@@ -24,7 +24,8 @@ public partial class LearningPathService(
IAiLearningPathClient aiClient,
IClaimService claimService,
ILogger logger,
- ILearnerSetupStateService? setupStateService = null) : ILearningPathService
+ ILearnerSetupStateService? setupStateService = null,
+ LearningPathGenerationTracker? generationTracker = null) : ILearningPathService
{
// ===== Constants =====
private const int MaxPlanDays = 730; // Giới hạn vận hành cho khoảng ôn trước ngày thi.
@@ -238,6 +239,7 @@ private async Task> GenerateInternalAsync(
HttpStatusCode.BadRequest, errorCode: "LEARNING_PATH_PLACEMENT_REQUIRED");
// ---------- 3. Đánh giá riêng từ vựng / ngữ pháp / đọc hiểu / nghe hiểu ----------
+ generationTracker?.ReportStage(userId, LearningPathGenerationStages.Analyzing);
var targetRank = JlptCurriculum.Rank(target.Code);
var sectionAssessments = JlptSkillAssessmentPolicy.Assess(placementForPlan, target.Code);
var assessments = ComputeSkillAssessments(sectionAssessments, targetRank);
@@ -271,11 +273,14 @@ private async Task> GenerateInternalAsync(
var totalStudyDays = studyDeadline.HasValue ? (studyDeadline.Value - today).Days : recommendedStudyDays;
if (totalStudyDays <= 0)
return ApiResponse.Fail(
- "Không còn ngày ôn trước ba ngày nghỉ sát kỳ thi. Vui lòng chọn kỳ thi sau.", HttpStatusCode.BadRequest);
+ "Không còn ngày ôn trước ba ngày nghỉ sát kỳ thi. Vui lòng chọn kỳ thi sau.", HttpStatusCode.BadRequest,
+ errorCode: "LEARNING_PATH_EXAM_TOO_SOON");
if (totalStudyDays > MaxPlanDays)
return ApiResponse.Fail(
- "Chỉ hỗ trợ khoảng ôn tới ngày thi tối đa 730 ngày. Vui lòng chọn ngày thi gần hơn.", HttpStatusCode.BadRequest);
+ "Chỉ hỗ trợ khoảng ôn tới ngày thi tối đa 730 ngày. Vui lòng chọn ngày thi gần hơn.", HttpStatusCode.BadRequest,
+ errorCode: "LEARNING_PATH_PLAN_TOO_LONG");
var planDays = Math.Min(totalStudyDays, ShortPlanDays);
+ var totalBatches = (planDays + ShortPlanDays - 1) / ShortPlanDays;
var horizon = LearningPathPlanningPolicy.ClassifyHorizon(assessments.Max(a => a.GapLevels), recommendedStudyDays,
assessments.All(a => a.HasData));
@@ -360,6 +365,8 @@ private async Task> GenerateInternalAsync(
{
for (var offset = 0; offset < planDays; offset += ShortPlanDays)
{
+ generationTracker?.ReportStage(userId, LearningPathGenerationStages.Designing,
+ completedBatches: offset / ShortPlanDays, totalBatches: totalBatches, planDurationDays: planDays);
var batchDays = Math.Min(ShortPlanDays, planDays - offset);
var batchPrompt = promptText
.Replace($"Lập đúng {Math.Min(planDays, ShortPlanDays)} ngày", $"Lập đúng {batchDays} ngày")
@@ -417,7 +424,8 @@ private async Task> GenerateInternalAsync(
}
if (batch is null)
return ApiResponse.Fail(
- $"AI trả về lịch không hợp lệ ({lastError}). Chưa lưu lộ trình dở dang.", HttpStatusCode.BadGateway);
+ $"AI trả về lịch không hợp lệ ({lastError}). Chưa lưu lộ trình dở dang.", HttpStatusCode.BadGateway,
+ errorCode: "LEARNING_PATH_AI_INVALID_OUTPUT");
skillFeedback ??= batch.SkillFeedback;
summaries.Add(batch.Summary);
focusTopics.AddRange(batch.FocusTopics);
@@ -478,6 +486,8 @@ private async Task> GenerateInternalAsync(
feasibility += $" Lộ trình AI chỉ xếp {planDays} ngày ôn trước mắt; sau chặng này, hãy làm đề thi thử JLPT chung của hệ thống để đánh giá và tiếp tục ôn luyện.";
// ---------- 7. Save DRAFT or first ACTIVE in a learner-row-locked transaction ----------
+ generationTracker?.ReportStage(userId, LearningPathGenerationStages.Saving,
+ completedBatches: totalBatches, totalBatches: totalBatches, planDurationDays: planDays);
try
{
var generatedAt = BusinessDateHelper.EnsureUtc(UtcNowProvider());
@@ -523,6 +533,7 @@ private async Task> GenerateInternalAsync(
ContentCoverageWarnings = coverageWarnings,
Phases = BuildPhases(today, planDays),
Summary = aiResult.Summary,
+ IsTestFixture = RikiPath.Application.Common.LearningPathTestFixture.IsTestFixture(aiResult.Summary),
Strengths = strengths,
Weaknesses = weaknesses,
Feasibility = feasibility,
@@ -926,6 +937,7 @@ private async Task RestoreStoredPathAsync(
response.BaseActivePathId = stored.BaseActivePathId;
response.PreviewExpiresAt = stored.PreviewExpiresAt;
response.ConfirmedAt = stored.ConfirmedAt;
+ response.IsTestFixture = RikiPath.Application.Common.LearningPathTestFixture.IsTestFixture(response.Summary);
RefreshDayAvailability(response);
return response;
}
diff --git a/RikiPath.Application/Services/SubscriptionAccessService.cs b/RikiPath.Application/Services/SubscriptionAccessService.cs
index e684da9..34cf216 100644
--- a/RikiPath.Application/Services/SubscriptionAccessService.cs
+++ b/RikiPath.Application/Services/SubscriptionAccessService.cs
@@ -23,6 +23,7 @@ public sealed class SubscriptionAccessService(
public const int OrderPrefix = 900_000_000;
public const string CategorySelfStudy = "self_study";
+ public const string CategoryAiPack = "ai_pack";
public const string CategorySpeaking = "speaking";
public const string CategoryWriting = "writing";
public const string CategoryAiGrading = "ai_grading";
@@ -33,13 +34,31 @@ public sealed class SubscriptionAccessService(
public static readonly IReadOnlySet SellableCategories = new HashSet(StringComparer.OrdinalIgnoreCase)
{
CategorySelfStudy,
+ CategoryAiPack,
+ CategoryCombo,
+ };
+
+ public static readonly IReadOnlySet LegacyAiCategories = new HashSet(StringComparer.OrdinalIgnoreCase)
+ {
CategorySpeaking,
CategoryWriting,
CategoryAiGrading,
CategoryLearningPath,
+ };
+
+ public static readonly IReadOnlySet UnifiedAiCategories = new HashSet(StringComparer.OrdinalIgnoreCase)
+ {
+ CategorySelfStudy,
+ CategoryAiPack,
CategoryCombo,
};
+ public static bool IsLegacyAiCategory(string? category)
+ => !string.IsNullOrWhiteSpace(category) && LegacyAiCategories.Contains(category.Trim());
+
+ public static bool IsUnifiedAiCategory(string? category)
+ => !string.IsNullOrWhiteSpace(category) && UnifiedAiCategories.Contains(category.Trim());
+
public static bool IsUnlimitedExpiry(DateTime? endDate)
=> !endDate.HasValue || endDate.Value.Year >= 2099;
@@ -51,7 +70,8 @@ public static string ResolveCategory(SubscriptionPlan? plan, int planId)
return CategoryMentorLegacy;
var normalized = plan.PlanCategory?.Trim().ToLowerInvariant();
- if (!string.IsNullOrEmpty(normalized) && SellableCategories.Contains(normalized))
+ if (!string.IsNullOrEmpty(normalized) &&
+ (SellableCategories.Contains(normalized) || LegacyAiCategories.Contains(normalized)))
{
if (normalized == CategorySelfStudy && planId is SpeakingPlan or WritingPlan or GradingCredit or LearningPathCredit)
{
@@ -80,7 +100,8 @@ public static string ResolveCategory(SubscriptionPlan? plan, int planId)
}
public static bool IsCreditCategory(string? category)
- => string.Equals(category, CategoryAiGrading, StringComparison.OrdinalIgnoreCase)
+ => string.Equals(category, CategoryAiPack, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(category, CategoryAiGrading, StringComparison.OrdinalIgnoreCase)
|| string.Equals(category, CategoryLearningPath, StringComparison.OrdinalIgnoreCase);
public static bool IsCredit(int planId) => planId is GradingCredit or LearningPathCredit;
@@ -90,7 +111,7 @@ public static bool IsSellable(SubscriptionPlan? plan)
&& plan.IsActive
&& !plan.IsDeleted
&& plan.MeetingSessionCount == 0
- && ResolveCategory(plan, plan.Id) != CategoryMentorLegacy;
+ && SellableCategories.Contains(ResolveCategory(plan, plan.Id));
private static string OrderCategory(UserSubscription order)
=> !string.IsNullOrWhiteSpace(order.PlanCategorySnapshot)
@@ -149,11 +170,13 @@ public async Task GetAccessAsync(CancellationToken ct)
: IsUnlimitedExpiry(studyExpiresAt)
? null
: (int)Math.Ceiling((studyExpiresAt!.Value - now).TotalDays);
- var grading = active.Where(s => OrderCategory(s) is CategoryAiGrading or CategorySelfStudy or CategoryCombo)
- .Sum(RemainingAi);
- // TEMPORARY AI TEST ACCESS: restore the purchase-based Speaking/Writing checks when testing ends.
- // var speaking = active.Any(s => OrderCategory(s) is CategorySpeaking or CategoryCombo) || study is not null || grading > 0;
- // var writing = active.Any(s => OrderCategory(s) is CategoryWriting or CategoryCombo) || study is not null || grading > 0;
+ var unifiedAi = SaturatingSumRemainingAi(active.Where(s => IsUnifiedAiCategory(OrderCategory(s))));
+ var aiGradingLegacy = SaturatingSumRemainingAi(active.Where(s => OrderCategory(s) == CategoryAiGrading));
+ var speakingLegacy = SaturatingSumRemainingAi(active.Where(s => OrderCategory(s) == CategorySpeaking));
+ var writingLegacy = SaturatingSumRemainingAi(active.Where(s => OrderCategory(s) == CategoryWriting));
+ var learningPathLegacy = SaturatingSumRemainingAi(active.Where(s => OrderCategory(s) == CategoryLearningPath));
+
+ var grading = SaturatingSum([unifiedAi, aiGradingLegacy]);
var allFeatures = await unitOfWork.Features.Query().AsNoTracking()
.Where(f => !f.IsDeleted && f.Category != CategoryMentorLegacy)
.OrderBy(f => f.SortOrder).ThenBy(f => f.Id)
@@ -168,25 +191,34 @@ public async Task GetAccessAsync(CancellationToken ct)
LockReason = null, UnlockPath = null }
: entitlement;
}).ToList();
- var speaking = evaluatedFeatures.FirstOrDefault(f => f.Code == FeatureCodes.AiSpeaking)?.Allowed
- ?? (active.Any(s => OrderCategory(s) is CategorySpeaking or CategoryCombo) || study is not null || grading > 0);
- var writing = evaluatedFeatures.FirstOrDefault(f => f.Code == FeatureCodes.AiWriting)?.Allowed
- ?? (active.Any(s => OrderCategory(s) is CategoryWriting or CategoryCombo) || study is not null || grading > 0);
+ var speakingAllowed = evaluatedFeatures.FirstOrDefault(f => f.Code == FeatureCodes.AiSpeaking)?.Allowed ?? false;
+ var writingAllowed = evaluatedFeatures.FirstOrDefault(f => f.Code == FeatureCodes.AiWriting)?.Allowed ?? false;
+ var legacyBalances = BuildLegacyAiBalances(active);
+ var aiFeatureCosts = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ {
+ ["speaking"] = GetCreditCost("speaking"),
+ ["writing"] = GetCreditCost("writing"),
+ ["learning_path"] = GetCreditCost("learning_path"),
+ [MockTestExplanationService.CreditFeature] = GetCreditCost(MockTestExplanationService.CreditFeature),
+ };
return new StudyAccessResponse(
study is not null,
study is null ? null : (study.PlanNameSnapshot ?? study.SubscriptionPlan?.Name),
- speaking,
- writing,
+ speakingAllowed,
+ writingAllowed,
grading,
- active.Where(s => OrderCategory(s) == CategorySpeaking).Sum(RemainingAi),
- active.Where(s => OrderCategory(s) == CategoryWriting).Sum(RemainingAi),
- active.Where(s => OrderCategory(s) == CategoryLearningPath).Sum(RemainingAi),
+ speakingLegacy,
+ writingLegacy,
+ learningPathLegacy,
0,
purchases.Select(s => ToPurchasedStudyPlan(s, now)).ToList(),
studyExpiresAt,
studyDaysRemaining,
- evaluatedFeatures);
+ evaluatedFeatures,
+ unifiedAi,
+ legacyBalances,
+ aiFeatureCosts);
}
public async Task GetPurchaseHistoryAsync(
@@ -338,7 +370,7 @@ public async Task EvaluateFeatureAsync(string featureCode
var errCode = evaluated.AccessSource == "LOCKED" && evaluated.Code == FeatureCodes.LessonsContent && mode == FeatureAccessModes.PlanRequired
? "SELF_STUDY_PACKAGE_REQUIRED"
- : evaluated.RequiresCredit && evaluated.CreditsRemaining <= 0 &&
+ : evaluated.RequiresCredit && evaluated.CreditsRemaining < evaluated.CreditCost &&
(mode == FeatureAccessModes.CreditRequired || (mode == FeatureAccessModes.PlanAndCredit && evaluated.GrantedByPlanName is not null))
? "AI_CREDIT_REQUIRED"
: "FEATURE_PLAN_REQUIRED";
@@ -392,14 +424,14 @@ internal static FeatureEntitlementDto EvaluateFeaturePolicy(
return new FeatureEntitlementDto(
feature.Id, feature.Code, feature.Name, feature.Description, feature.Category,
mode, feature.IsCoreFree, false, "DISABLED", null, false, 0,
- SuspendedMessage, null, routes);
+ SuspendedMessage, null, routes, 0);
}
if (mode == FeatureAccessModes.Free)
{
return new FeatureEntitlementDto(
feature.Id, feature.Code, feature.Name, feature.Description, feature.Category,
- mode, feature.IsCoreFree, true, "FREE", null, false, 0, null, null, routes);
+ mode, feature.IsCoreFree, true, "FREE", null, false, 0, null, null, routes, 0);
}
var matchingPlan = activeGrants.FirstOrDefault(grant =>
@@ -412,6 +444,7 @@ internal static FeatureEntitlementDto EvaluateFeaturePolicy(
: SaturatingSum(activeGrants
.Where(grant => SupportsCredit(grant.Category, creditKey))
.Select(grant => grant.AiQuotaRemaining));
+ var creditCost = string.IsNullOrWhiteSpace(creditKey) ? 0 : GetCreditCost(creditKey);
return mode switch
{
@@ -425,30 +458,30 @@ matchingPlan is not null
? "Bạn cần gói tự học đang hiệu lực."
: $"Tính năng {feature.Name} yêu cầu gói học phù hợp."),
matchingPlan is not null ? null : "/plans/",
- routes),
+ routes, 0),
FeatureAccessModes.CreditRequired => new FeatureEntitlementDto(
feature.Id, feature.Code, feature.Name, feature.Description, feature.Category,
- mode, false, creditsRemaining > 0, creditsRemaining > 0 ? "CREDIT" : "LOCKED",
+ mode, false, creditsRemaining >= creditCost, creditsRemaining >= creditCost ? "CREDIT" : "LOCKED",
null, true, creditsRemaining,
- creditsRemaining > 0 ? null : "Bạn chưa có lượt AI cho tính năng này. Vào Mua gói để mua thêm lượt.",
- creditsRemaining > 0 ? null : "/plans/",
- routes),
+ creditsRemaining >= creditCost ? null : "Bạn không đủ lượt AI để thực hiện thao tác này.",
+ creditsRemaining >= creditCost ? null : "/plans/",
+ routes, creditCost),
FeatureAccessModes.PlanAndCredit => new FeatureEntitlementDto(
feature.Id, feature.Code, feature.Name, feature.Description, feature.Category,
- mode, false, matchingPlan is not null && creditsRemaining > 0,
- matchingPlan is not null && creditsRemaining > 0 ? "PLAN_AND_CREDIT" : "LOCKED",
+ mode, false, matchingPlan is not null && creditsRemaining >= creditCost,
+ matchingPlan is not null && creditsRemaining >= creditCost ? "PLAN_AND_CREDIT" : "LOCKED",
matchingPlan?.PlanName, true, creditsRemaining,
matchingPlan is null
? $"Tính năng {feature.Name} yêu cầu gói học phù hợp và lượt AI."
- : (creditsRemaining > 0 ? null : "Bạn đã hết lượt AI khả dụng cho tính năng này."),
- matchingPlan is not null && creditsRemaining > 0 ? null : "/plans/",
- routes),
+ : (creditsRemaining >= creditCost ? null : "Bạn không đủ lượt AI để thực hiện thao tác này."),
+ matchingPlan is not null && creditsRemaining >= creditCost ? null : "/plans/",
+ routes, creditCost),
_ => new FeatureEntitlementDto(
feature.Id, feature.Code, feature.Name, feature.Description, feature.Category,
- FeatureAccessModes.Free, feature.IsCoreFree, true, "FREE", null, false, 0, null, null, routes),
+ FeatureAccessModes.Free, feature.IsCoreFree, true, "FREE", null, false, 0, null, null, routes, 0),
};
}
@@ -482,15 +515,70 @@ public static string EffectiveState(FeatureEntitlementDto evaluated)
};
}
- private static bool SupportsCredit(string category, string feature) => feature switch
+ private static bool SupportsCredit(string category, string feature)
{
- "learning_path" => category is CategoryLearningPath or CategoryCombo,
- "speaking" => category is CategorySpeaking or CategoryAiGrading or CategorySelfStudy or CategoryCombo,
- "writing" => category is CategoryWriting or CategoryAiGrading or CategorySelfStudy or CategoryCombo,
- MockTestExplanationService.CreditFeature => category is CategoryAiGrading or CategorySelfStudy or CategoryCombo,
- _ => false
+ if (IsUnifiedAiCategory(category))
+ return feature is "speaking" or "writing" or "learning_path" or MockTestExplanationService.CreditFeature;
+
+ return feature switch
+ {
+ "learning_path" => string.Equals(category, CategoryLearningPath, StringComparison.OrdinalIgnoreCase),
+ "speaking" => string.Equals(category, CategorySpeaking, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(category, CategoryAiGrading, StringComparison.OrdinalIgnoreCase),
+ "writing" => string.Equals(category, CategoryWriting, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(category, CategoryAiGrading, StringComparison.OrdinalIgnoreCase),
+ MockTestExplanationService.CreditFeature => string.Equals(category, CategoryAiGrading, StringComparison.OrdinalIgnoreCase),
+ _ => false,
+ };
+ }
+
+ public static string? FeatureCodeForCreditKey(string? feature) => feature?.Trim().ToLowerInvariant() switch
+ {
+ "speaking" => FeatureCodes.AiSpeaking,
+ "writing" => FeatureCodes.AiWriting,
+ "learning_path" => FeatureCodes.AiLearningPath,
+ MockTestExplanationService.CreditFeature => FeatureCodes.AiMockExplanation,
+ _ => null,
+ };
+
+ public static int GetCreditCost(string? feature) => feature?.Trim().ToLowerInvariant() switch
+ {
+ "speaking" => 1,
+ "writing" => 1,
+ "learning_path" => 1,
+ MockTestExplanationService.CreditFeature => 1,
+ _ => 1,
};
+ private static List BuildLegacyAiBalances(IReadOnlyList activeOrders)
+ {
+ var orderPriority = new Dictionary(StringComparer.OrdinalIgnoreCase)
+ {
+ [CategorySpeaking] = ("Luyện nói AI (gói cũ)", 0),
+ [CategoryWriting] = ("Luyện viết AI (gói cũ)", 1),
+ [CategoryAiGrading] = ("Chấm AI nói/viết (gói cũ)", 2),
+ [CategoryLearningPath] = ("Tạo lộ trình AI (gói cũ)", 3),
+ };
+
+ return activeOrders
+ .Where(s => IsLegacyAiCategory(OrderCategory(s)) && RemainingAi(s) > 0)
+ .GroupBy(OrderCategory, StringComparer.OrdinalIgnoreCase)
+ .Select(g =>
+ {
+ var remaining = SaturatingSumRemainingAi(g);
+ var earliest = g
+ .Where(s => s.EndDate.HasValue && !IsUnlimitedExpiry(s.EndDate))
+ .Select(s => (DateTime?)DateTime.SpecifyKind(s.EndDate!.Value, DateTimeKind.Utc))
+ .OrderBy(d => d)
+ .FirstOrDefault();
+ var label = orderPriority.TryGetValue(g.Key, out var meta) ? meta.Label : g.Key;
+ return (Sort: meta.Order, Item: new LegacyAiBalanceDto(g.Key, label, remaining, earliest));
+ })
+ .OrderBy(x => x.Sort)
+ .Select(x => x.Item)
+ .ToList();
+ }
+
/// PayOS hosted-checkout link lifetime for a self-study order; the order is held Pending for the same window.
public static readonly TimeSpan PaymentLinkLifetime = TimeSpan.FromMinutes(15);
private static readonly TimeSpan LinkCreationGrace = TimeSpan.FromSeconds(45);
@@ -777,10 +865,14 @@ internal static void Activate(UserSubscription order, string? reference, DateTim
order.PaymentStatus = PaymentStatus.Paid;
order.PaymentTransactionId = reference;
order.StartDate = now;
- if (IsCreditCategory(category) || IsCredit(order.SubscriptionPlanId))
+ if (durationDays <= 0 || IsCredit(order.SubscriptionPlanId))
{
order.EndDate = null;
}
+ else if (string.Equals(category, CategoryAiPack, StringComparison.OrdinalIgnoreCase))
+ {
+ order.EndDate = now.AddDays(durationDays);
+ }
else
{
var effectiveStart = stackFromUtc.HasValue && stackFromUtc.Value > now ? stackFromUtc.Value : now;
@@ -799,7 +891,7 @@ public async Task> UseAiAsync(string feature, Func FeatureCodes.AiLearningPath,
"speaking" => FeatureCodes.AiSpeaking,
@@ -807,9 +899,9 @@ public async Task> UseAiAsync(string feature, Func FeatureCodes.AiMockExplanation,
_ => null,
};
- if (featureCode is not null)
+ if (testFeatureCode is not null)
{
- var decision = await EvaluateFeatureAsync(featureCode, ct);
+ var decision = await EvaluateFeatureAsync(testFeatureCode, ct);
if (!decision.Allowed)
return ApiResponse.Fail(decision.Message ?? SuspendedMessage, decision.StatusCode,
errorCode: decision.ErrorCode ?? "FEATURE_DISABLED");
@@ -817,26 +909,109 @@ public async Task> UseAiAsync(string feature, Func !f.IsDeleted && f.Code == featureCode, ct);
+ if (featureEntity is not null)
+ mode = EffectiveMode(featureEntity);
+ }
+
+ if (mode == FeatureAccessModes.Disabled)
+ return ApiResponse.Fail(SuspendedMessage, HttpStatusCode.Forbidden, errorCode: "FEATURE_DISABLED");
+
+ if (mode == FeatureAccessModes.Free)
+ return await operation();
+
+ if (mode == FeatureAccessModes.PlanRequired)
+ {
+ var planCheck = await EvaluateFeatureAsync(featureCode!, ct);
+ if (!planCheck.Allowed)
+ return ApiResponse.Fail(
+ planCheck.Message ?? "Bạn cần gói học đang hiệu lực.",
+ planCheck.StatusCode,
+ errorCode: planCheck.ErrorCode ?? "FEATURE_PLAN_REQUIRED");
+ return await operation();
+ }
+
+ var cost = GetCreditCost(feature);
var userId = actor.Id;
- int? reservationId = null;
+ List<(int OrderId, int Taken)> reservations = [];
+ var missingRequiredPlan = false;
+ string? planRequiredMessage = null;
+
await unitOfWork.ExecuteInTransactionAsync(async token =>
{
+ reservations.Clear();
+ missingRequiredPlan = false;
if (await unitOfWork.UserAccounts.GetByIdForUpdateAsync(userId, token) is null) return;
var now = DateTime.UtcNow;
- var orders = await unitOfWork.UserSubscriptions.Query()
- .Include(s => s.SubscriptionPlan)
- .Where(s => s.UserId == userId && !s.IsDeleted && s.PaymentStatus == PaymentStatus.Paid &&
- s.AiGradingUsedCount < s.AiGradingQuota)
- .OrderBy(s => s.EndDate == null).ThenBy(s => s.EndDate).ThenBy(s => s.Id).ToListAsync(token);
- var credit = orders.FirstOrDefault(s => IsActive(s, now) && Supports(s, feature));
- if (credit is null) return;
- credit.AiGradingUsedCount++;
- await unitOfWork.SaveChangesAsync(token);
- reservationId = credit.Id;
+ var query = unitOfWork.UserSubscriptions.Query();
+ query = mode == FeatureAccessModes.PlanAndCredit
+ ? query.Include(s => s.SubscriptionPlan).ThenInclude(p => p!.Features)
+ : query.Include(s => s.SubscriptionPlan);
+
+ var activePaid = (await query
+ .Where(s => s.UserId == userId && !s.IsDeleted && s.PaymentStatus == PaymentStatus.Paid)
+ .ToListAsync(token))
+ .Where(s => IsActive(s, now))
+ .ToList();
+
+ if (mode == FeatureAccessModes.PlanAndCredit && featureEntity is not null)
+ {
+ var grants = ToGrantSnapshots(activePaid);
+ var hasPlan = grants.Any(grant =>
+ grant.FeatureIds.Contains(featureEntity.Id) ||
+ (featureEntity.Code == FeatureCodes.LessonsContent && grant.Category is CategorySelfStudy or CategoryCombo));
+ if (!hasPlan)
+ {
+ missingRequiredPlan = true;
+ planRequiredMessage = $"Tính năng {featureEntity.Name} yêu cầu gói học phù hợp và lượt AI.";
+ return;
+ }
+ }
+
+ // Draw narrow legacy scoped credits before versatile unified credits, and expiring credits before non-expiring credits.
+ var eligible = activePaid
+ .Where(s => RemainingAi(s) > 0 && Supports(s, feature))
+ .OrderBy(s => IsUnifiedAiCategory(OrderCategory(s)) ? 1 : 0)
+ .ThenBy(s => s.EndDate == null ? 1 : 0)
+ .ThenBy(s => s.EndDate)
+ .ThenBy(s => s.Id)
+ .ToList();
+
+ if (SaturatingSumRemainingAi(eligible) < cost)
+ return;
+
+ var remainingCost = cost;
+ foreach (var order in eligible)
+ {
+ if (remainingCost <= 0) break;
+ var available = RemainingAi(order);
+ var take = Math.Min(available, remainingCost);
+ if (take <= 0) continue;
+ order.AiGradingUsedCount += take;
+ remainingCost -= take;
+ reservations.Add((order.Id, take));
+ }
+
+ if (remainingCost == 0)
+ await unitOfWork.SaveChangesAsync(token);
+ else
+ reservations.Clear();
}, ct);
- if (reservationId is null)
- return ApiResponse.Fail("Bạn chưa có lượt AI cho tính năng này. Vào Mua gói để mua thêm lượt.",
+ if (missingRequiredPlan)
+ return ApiResponse.Fail(
+ planRequiredMessage ?? "Tính năng này yêu cầu gói học phù hợp.",
+ HttpStatusCode.Forbidden,
+ errorCode: "FEATURE_PLAN_REQUIRED");
+
+ if (reservations.Count == 0)
+ return ApiResponse.Fail("Bạn không đủ lượt AI để thực hiện thao tác này.",
HttpStatusCode.Forbidden, errorCode: "AI_CREDIT_REQUIRED");
var succeeded = false;
@@ -845,21 +1020,24 @@ await unitOfWork.ExecuteInTransactionAsync(async token =>
var result = await operation();
succeeded = result.IsSuccess && (delivered is null || delivered(result.Result));
if (succeeded)
- logger?.LogInformation("AI credit consumed. UserId={UserId} Feature={Feature} PurchaseId={PurchaseId} Credits={Credits}",
- userId, feature, reservationId.Value, 1);
+ logger?.LogInformation("AI credit consumed. UserId={UserId} Feature={Feature} Orders={Orders} Credits={Credits}",
+ userId, feature, string.Join(',', reservations.Select(r => $"{r.OrderId}:{r.Taken}")), cost);
return result;
}
finally
{
- if (!succeeded)
+ if (!succeeded && reservations.Count > 0)
await unitOfWork.ExecuteInTransactionAsync(async token =>
{
await unitOfWork.UserAccounts.GetByIdForUpdateAsync(userId, token);
- // An atomic update avoids overwriting usage from another request.
- await unitOfWork.UserSubscriptions.Query()
- .Where(s => s.Id == reservationId.Value && s.AiGradingUsedCount > 0)
- .ExecuteUpdateAsync(setters => setters.SetProperty(s => s.AiGradingUsedCount,
- s => s.AiGradingUsedCount - 1), token);
+ foreach (var (orderId, taken) in reservations)
+ {
+ // An atomic update avoids overwriting usage from another request.
+ await unitOfWork.UserSubscriptions.Query()
+ .Where(s => s.Id == orderId && s.AiGradingUsedCount >= taken)
+ .ExecuteUpdateAsync(setters => setters.SetProperty(s => s.AiGradingUsedCount,
+ s => s.AiGradingUsedCount - taken), token);
+ }
}, CancellationToken.None);
}
}
@@ -903,6 +1081,12 @@ public sealed record StudyPlanFeatureDto(
string Category,
string AccessMode);
+public sealed record LegacyAiBalanceDto(
+ string Category,
+ string Label,
+ int Remaining,
+ DateTime? EarliestExpiryUtc = null);
+
public sealed record FeatureEntitlementDto(
int FeatureId,
string Code,
@@ -918,7 +1102,8 @@ public sealed record FeatureEntitlementDto(
int CreditsRemaining,
string? LockReason,
string? UnlockPath,
- IReadOnlyList Routes);
+ IReadOnlyList Routes,
+ int CreditCost = 0);
public sealed record FeatureAccessDecision(
bool Allowed,
@@ -960,4 +1145,7 @@ public sealed record StudyAccessResponse(bool Active, string? PlanName, bool Spe
int AiGradingUsesRemaining, int SpeakingUsesRemaining, int WritingUsesRemaining, int LearningPathUsesRemaining,
int MentorSessionsRemaining, IReadOnlyList Purchases,
DateTime? SelfStudyExpiresAt, int? SelfStudyDaysRemaining,
- IReadOnlyList? Features = null);
+ IReadOnlyList? Features = null,
+ int UnifiedAiUsesRemaining = 0,
+ IReadOnlyList? LegacyAiBalances = null,
+ IReadOnlyDictionary? AiFeatureCosts = null);
diff --git a/RikiPath.Infrastructure/Clients/M4E2eAiLearningPathClient.cs b/RikiPath.Infrastructure/Clients/M4E2eAiLearningPathClient.cs
index 7e15e94..119e5ea 100644
--- a/RikiPath.Infrastructure/Clients/M4E2eAiLearningPathClient.cs
+++ b/RikiPath.Infrastructure/Clients/M4E2eAiLearningPathClient.cs
@@ -57,7 +57,7 @@ public Task GenerateLearningPathJsonAsync(
var response = new
{
- summary = "[M4E2E TEST STUB — NOT REAL AI OUTPUT] Deterministic integration-test response.",
+ summary = $"{RikiPath.Application.Common.LearningPathTestFixture.SummaryMarker} Deterministic integration-test response.",
skillFeedback = new[] { "vocabulary", "grammar", "reading", "listening" }.Select(skill => new
{ skillCode = skill, comment = "Dữ liệu mô phỏng, không phải nhận xét AI thật.", recommendation = "Chỉ dùng để kiểm thử." }),
strengths = new[] { "M4E2E test data" },
diff --git a/RikiPath.Infrastructure/Migrations/20261203073836_RemoveLegacyMockPublishMetadata.Designer.cs b/RikiPath.Infrastructure/Migrations/20261203073836_RemoveLegacyMockPublishMetadata.Designer.cs
new file mode 100644
index 0000000..261ad71
--- /dev/null
+++ b/RikiPath.Infrastructure/Migrations/20261203073836_RemoveLegacyMockPublishMetadata.Designer.cs
@@ -0,0 +1,14703 @@
+//
+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("20261203073836_RemoveLegacyMockPublishMetadata")]
+ partial class RemoveLegacyMockPublishMetadata
+ {
+ ///
+ 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.AiRuntimeConfiguration", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("ProtectedSecretsJson")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("Revision")
+ .IsConcurrencyToken()
+ .HasColumnType("integer");
+
+ b.Property("SettingsJson")
+ .IsRequired()
+ .HasColumnType("jsonb");
+
+ b.Property("UpdatedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("UpdatedByAdminId")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.ToTable("AiRuntimeConfigurations", null, t =>
+ {
+ t.HasCheckConstraint("CK_AiRuntimeConfiguration_Singleton", "\"Id\" = 1 AND \"Revision\" > 0");
+ });
+ });
+
+ 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