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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions RikiPath.Application/Common/LearningPathTestFixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace RikiPath.Application.Common;

/// <summary>
/// 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.
/// </summary>
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;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
namespace RikiPath.Application.Responses.LearningPaths
{
/// <summary>
/// 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".
/// </summary>
public class LearningPathGenerationStatusResponse
{
/// <summary>idle | running | succeeded | failed</summary>
public string State { get; set; } = LearningPathGenerationStates.Idle;

/// <summary>generate (first ACTIVE path) | preview (DRAFT for a level change).</summary>
public string? Kind { get; set; }

/// <summary>preparing | analyzing | designing | saving — the step the server is executing now.</summary>
public string? Stage { get; set; }

/// <summary>Number of 30-day AI batches already accepted.</summary>
public int? CompletedBatches { get; set; }

/// <summary>Total number of 30-day AI batches the plan needs (known once the plan length is computed).</summary>
public int? TotalBatches { get; set; }

public int? PlanDurationDays { get; set; }

/// <summary>
/// True when the work keeps running on the server if the learner leaves the page
/// (generate). False when closing the request cancels it (preview).
/// </summary>
public bool ContinuesWhenClientLeaves { get; set; }

public DateTime? StartedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public DateTime? FinishedAt { get; set; }

/// <summary>Saved path id when State = succeeded.</summary>
public int? PathId { get; set; }

public string? ErrorCode { get; set; }
public string? ErrorMessage { get; set; }

/// <summary>
/// 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.
/// </summary>
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";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ public class LearningPathResponse
public DateTime? SuggestedExamDate { get; set; }

public List<string> FocusTopics { get; set; } = new();

/// <summary>true = lộ trình do stub kiểm thử M4E2E sinh ra, không phải đề xuất AI thật.</summary>
public bool IsTestFixture { get; set; }
public List<DailyScheduleResponse> DailySchedules { get; set; } = new();
}
}
65 changes: 50 additions & 15 deletions RikiPath.Application/Services/AdminBusinessConfigService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,19 @@ public async Task<ApiResponse<AdminSubscriptionPlanDto>> 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<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.Fail(
"Giá gói phải là số nguyên VND không âm.",
Expand All @@ -121,18 +128,30 @@ public async Task<ApiResponse<AdminSubscriptionPlanDto>> SaveSubscriptionPlanAsy
HttpStatusCode.BadRequest,
"SUBSCRIPTION_PLAN_PRICE_REQUIRED");

var isCredit = SubscriptionAccessService.IsCreditCategory(category);
if (isCredit && request.DurationDays != 0)
return ApiResponse<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.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<AdminSubscriptionPlanDto>.Fail(
Expand All @@ -142,7 +161,7 @@ public async Task<ApiResponse<AdminSubscriptionPlanDto>> SaveSubscriptionPlanAsy

if (category != SubscriptionAccessService.CategorySelfStudy && request.AiGradingQuota < 1)
return ApiResponse<AdminSubscriptionPlanDto>.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");

Expand Down Expand Up @@ -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<AdminSubscriptionPlanDto>.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,
Expand Down
1 change: 1 addition & 0 deletions RikiPath.Application/Services/LearningMomentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,7 @@ private async Task<List<MomentCandidate>> 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/",
Expand Down
130 changes: 130 additions & 0 deletions RikiPath.Application/Services/LearningPathGenerationTracker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
using System.Collections.Concurrent;
using RikiPath.Application.Responses.LearningPaths;

namespace RikiPath.Application.Services
{
/// <summary>
/// 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.
/// </summary>
public sealed class LearningPathGenerationTracker
{
/// <summary>Finished results stay readable this long so a reloaded page can still recover them.</summary>
private static readonly TimeSpan FinishedRetention = TimeSpan.FromMinutes(30);

/// <summary>A running entry with no update for this long can no longer be trusted (owner vanished).</summary>
private static readonly TimeSpan StaleRunning = TimeSpan.FromMinutes(15);

private readonly ConcurrentDictionary<int, LearningPathGenerationStatusResponse> states = new();

public Func<DateTime> 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<int, LearningPathGenerationStatusResponse>(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,
};
}

/// <summary>Records the stage the server just entered. Ignored when no run is active for the learner.</summary>
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<LearningPathGenerationStatusResponse, LearningPathGenerationStatusResponse?> 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,
};
}
}
Loading
Loading