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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,25 @@ Legacy minimum-enrollment/preparation fields remain in stored policy revisions f
- When the Mentor explicitly ends the final required valid session, the class lock protects automatic class/enrollment completion and review eligibility. All required sessions and roster attendance must be completed; no Admin confirmation, homework completion, feedback, review or complaint is required. No background time-skip operation writes attendance or completes classes.
- Direct attendance does not require Meeting joins. A started class session permits early room access, direct attendance and homework. Absent and ExcusedAbsent are valid final attendance; no attendance/grade is generated automatically. Homework due dates and submission policies remain independent.
- Before release, verify build/analyzers and offline model parity; rehearse this migration on clean and representative isolated QA databases with a verified backup. No migration is applied by startup. Server migration, restart and deployment each require separate approval. Export lifecycle evidence before any approved rollback because Down removes the new fields.

## Admin-created cohorts and mentor invitations

- Admin creates a draft class and its future session times through `POST /api/study-courses/cohorts`; `POST /api/study-courses/cohorts/mentor-candidates` returns verified mentors qualified for the plan level and free in every selected slot. The database stores each mentor offer in `StudyCohortMentorInvitations`, preserving decline, acceptance and reassignment history. `POST /api/study-courses/cohorts/{cohortId}/mentor-invitations` can invite the next eligible mentor after a decline.
- The invited mentor can list their offers at `GET /api/study-courses/cohort-mentor-invitations`, then accept or decline. Decline requires a reason. Acceptance rechecks teaching level and schedule conflicts, approves the cohort session slots and changes the cohort from `Draft` to `Published`; learners can discover and enroll only after that transition. Admin receives outbox notifications for acceptance, decline and mentor change requests.
- FE flow: call `POST /api/study-courses/cohorts/mentor-candidates` with `{ "planId": 1, "sessions": [{ "startsAtUtc": "2027-01-01T02:00:00Z", "endsAtUtc": "2027-01-01T03:00:00Z" }] }` (provide every session required by the plan). Then call `POST /api/study-courses/cohorts` with the same `planId` and `sessions`, plus `name`, chosen `mentorId` and a new `idempotencyKey` UUID. The response gives `cohortId` and `invitationId`. Mentor lists invitations and calls `POST /api/study-courses/cohort-mentor-invitations/{invitationId}/accept` or `/decline` with `{ "reason": "..." }`. The invitation response includes its status, session times and `cohortRevisionAtInvite`; after a decline, Admin selects another mentor and calls `POST /api/study-courses/cohorts/{cohortId}/mentor-invitations` with `mentorId`, `reason`, a new UUID and the current `expectedCohortRevision`. A changed class schedule invalidates an outstanding invitation; Admin must cancel and resend it.
- For an active cohort, mentor schedule changes go to `POST /api/study-courses/cohorts/{cohortId}/mentor-change-requests`; Admin invites a replacement and the new mentor must accept before future sessions move. Learners request a class transfer through the existing `/{courseId}/transfer-requests` workflow; Admin chooses/approves the destination and the learner's enrollment is moved in one transaction. Per-session learner/mentor changes to group classes are rejected.
- Mentor-authored teaching proposal submission/open-enrollment and Admin proposal approval endpoints return `409 MENTOR_SELF_SCHEDULING_CLOSED`. `StudyCohortMentorInvitations` is added by migration `20261201081546_AddAdminCohortMentorInvitations`; it is additive and its Down refuses to discard invitation history. Do not apply it to Shared Supabase from a feature branch; follow the isolated QA and release preflight above.
- Migration `20261201132000_MakeCohortsPlanless` stores the learner-facing `StudyCohort.Level`, backfills level and missing class tuition from historical plans, removes `StudyCohorts.PlanId`, and makes `StudyCourses.PlanId` nullable for direct class enrollment. Historical course orders retain their existing plan references and payment snapshots. Its Down refuses rollback because a new class cannot be mapped back to a plan. The Admin sets class tuition directly; learner enrollment pays that exact class price through PayOS. Review the generated SQL and rehearse on an isolated database before deployment; startup never applies this migration.
- Migration `20261201135156_RepairCohortInvitationRevision` repairs a database where the invitation migration is recorded as applied but `StudyCohortMentorInvitations.CohortRevisionAtInvite` is absent. It adds the required integer column only when the invitation table is empty, verifies its type and nullability, and leaves correct databases unchanged. A populated incomplete table requires manual review because the original invite-time revision cannot be reconstructed safely. The read-only preflight checks this column when the original migration is marked applied. Rehearse and obtain the normal shared database approval before applying the repair; the migration is never applied at startup.
- The operator will review each Stage through the UI after deployment. Full automated end-to-end acceptance is not a prerequisite for this handoff. Migration rehearsal already succeeded on a clean isolated database (25 migrations, including idempotent replay) and a restored local-data clone (76 to 77 history rows); existing class, enrollment, schedule and attendance fingerprints were preserved. The clone's 22 unresolved historical sessions retained null lifecycle status and actual timestamps. Server identity/history and backup/restore still require preflight before an approved server migration.

## Admin AI configuration

- `GET /api/admin/ai-configuration` returns the active models, provider endpoints, timeouts, token limits and per-user quotas. It reports whether each provider key is set, but never returns a key.
- `PUT /api/admin/ai-configuration` saves the complete editable configuration. Send the `revision` returned by GET as `expectedRevision`; the OpenAI key can be supplied in `settings.OpenAI.ApiKey` alongside `BaseUrl`, all six feature models, timeout and token limits, as in the server configuration shape. OpenRouter accepts `openRouterApiKey` and Gemini accepts up to two `geminiApiKeys`. Empty key fields keep existing keys. Use the matching `clear...ApiKey` flag to remove one. The API accepts Admin only, validates provider URLs and limits, rejects stale revisions with `409`, protects keys with ASP.NET Data Protection and records non-secret before/after values in `AdminAuditLogs`.
- AI clients read the live configuration from an in-process cache and refresh it from the database every 15 seconds. The instance that saves a change applies it immediately. Until the first database configuration exists, settings fall back to appsettings/environment values.
- Migration `20261201143534_AddAdminAiRuntimeConfiguration` creates the singleton `AiRuntimeConfigurations` row store on the first Admin save. Startup never applies this migration. Back up and retain the ASP.NET Data Protection key ring across restarts (and share it between API instances); configure `AiConfiguration:DataProtectionKeysPath` to a persistent path when the deployment does not retain the default key directory. Losing the key ring prevents decryption of saved provider keys.

## Core Safety Rules

1. **Never run migrations against an unverified database target.**
Expand Down
38 changes: 38 additions & 0 deletions RikiPath.Application/Helpers/NotificationSemanticResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ private sealed class LiveEntitySnapshot
public Dictionary<int, (string Status, bool MentorResponded, bool IsPaymentCategory)> ComplaintStates { get; } = [];
public Dictionary<int, string> TransferStatuses { get; } = [];
public Dictionary<int, (string Status, string Kind)> CohortScheduleStatuses { get; } = [];
public Dictionary<int, string> CohortMentorInvitationStatuses { get; } = [];
public Dictionary<int, int> PendingCourseScheduleRequestsByCourse { get; } = [];
public int PendingPaymentReviewsCount { get; set; }
public int PendingContentApprovalsCount { get; set; }
Expand All @@ -74,6 +75,8 @@ private sealed class LiveEntitySnapshot
"LearningFeedbackPending",
"CohortTransfer",
"CohortScheduleRequest",
"CohortMentorInvitation",
"CohortMentorChange",
"CohortPaymentReconciliation",
"CourseScheduleRequest",
"PaymentReview",
Expand Down Expand Up @@ -678,6 +681,27 @@ private static SemanticResolution ResolveCore(
return new SemanticResolution(CategoryInfo, false, null);
}

if (string.Equals(type, "CohortMentorInvitation", StringComparison.OrdinalIgnoreCase)
|| string.Equals(type, "CohortMentorChange", StringComparison.OrdinalIgnoreCase))
{
var invitationId = ExtractQueryInt(link, "invitationId");
var status = invitationId.HasValue && snapshot is not null
? snapshot.CohortMentorInvitationStatuses.GetValueOrDefault(invitationId.Value)
: null;
var actionable = recipientRole == Role.Mentor
? snapshot is null ? status is null or StudyCohortMentorInvitation.Pending : status == StudyCohortMentorInvitation.Pending
: status is StudyCohortMentorInvitation.Declined or StudyCohortMentorInvitation.ChangeRequested
|| (snapshot is null && (string.Equals(type, "CohortMentorChange", StringComparison.OrdinalIgnoreCase)
|| titleLower.Contains("từ chối", StringComparison.Ordinal)));
if (status is StudyCohortMentorInvitation.Accepted or StudyCohortMentorInvitation.Replaced
or StudyCohortMentorInvitation.Cancelled)
actionable = false;
var exists = status is not null || snapshot is null;
return new SemanticResolution(actionable ? CategoryWarning : CategoryInfo, actionable,
actionable ? ActionPending : ActionResolved, "CohortMentorInvitation", invitationId,
status, actionable ? "Chờ xử lý" : "Đã xử lý", exists);
}

// 10. Cohort Schedule Request & Payment Reconciliation
if (string.Equals(type, "CohortScheduleRequest", StringComparison.OrdinalIgnoreCase))
{
Expand Down Expand Up @@ -1042,6 +1066,7 @@ private static async Task<LiveEntitySnapshot> LoadLiveSnapshotAsync(
var feedbackIds = new HashSet<int>();
var transferIds = new HashSet<int>();
var cohortScheduleIds = new HashSet<int>();
var cohortMentorInvitationIds = new HashSet<int>();
var homeworkAssignmentIds = new HashSet<int>();
var homeworkGroupKeys = new HashSet<Guid>();

Expand All @@ -1067,6 +1092,9 @@ private static async Task<LiveEntitySnapshot> LoadLiveSnapshotAsync(
if (type == "LearningFeedbackPending") TryAdd(feedbackIds, ExtractQueryInt(link, "feedbackId"));
TryAdd(transferIds, ExtractQueryInt(link, "transferRequestId"));
TryAdd(cohortScheduleIds, ExtractQueryInt(link, "cohortScheduleRequestId"));
if (string.Equals(type, "CohortMentorInvitation", StringComparison.OrdinalIgnoreCase)
|| string.Equals(type, "CohortMentorChange", StringComparison.OrdinalIgnoreCase))
TryAdd(cohortMentorInvitationIds, ExtractQueryInt(link, "invitationId"));
TryAdd(mentorIds, ExtractQueryInt(link, "mentorId"));

if (linkLower.StartsWith("/admin/payments", StringComparison.Ordinal)
Expand Down Expand Up @@ -1251,6 +1279,16 @@ private static async Task<LiveEntitySnapshot> LoadLiveSnapshotAsync(
snapshot.CohortScheduleStatuses[r.Id] = (r.Status, r.Kind);
}

if (cohortMentorInvitationIds.Count > 0)
{
var rows = await unitOfWork.StudyCohortMentorInvitations.Query().AsNoTracking()
.Where(x => cohortMentorInvitationIds.Contains(x.Id)
&& (snapshot.RecipientRole == Role.Admin || x.MentorId == userId))
.Select(x => new { x.Id, x.Status }).ToListAsync(ct);
foreach (var row in rows)
snapshot.CohortMentorInvitationStatuses[row.Id] = row.Status;
}

if (checkPendingContent)
{
var pendingReq = await unitOfWork.ContentApprovalRequests.Query().AsNoTracking()
Expand Down
17 changes: 16 additions & 1 deletion RikiPath.Application/Hubs/NotificationHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
using Microsoft.EntityFrameworkCore;
using RikiPath.Application.Common;
using RikiPath.Application.Helpers;
using RikiPath.Application.IServices;
using RikiPath.Domain.Enums;

namespace RikiPath.Application.Hubs;

[Authorize]
public class NotificationHub(IUnitOfWork? unitOfWork = null) : Hub
public class NotificationHub(IUnitOfWork? unitOfWork = null, ISidebarCounterService? sidebarCounters = null) : Hub
{
public override async Task OnConnectedAsync()
{
Expand Down Expand Up @@ -40,6 +42,19 @@ public async Task RequestSync()
}
}

public async Task RequestSidebarCounters()
{
var userId = TryGetUserId();
var rawRole = Context.User?.FindFirst(ClaimTypes.Role)?.Value;
if (userId is not int id || !Enum.TryParse<Role>(rawRole, true, out var role) || sidebarCounters is null)
return;

var result = await sidebarCounters.GetForUserAsync(id, role, Context.ConnectionAborted);
if (result.IsSuccess && result.Result is not null)
await Clients.Caller.SendAsync("SidebarCountersChanged",
new { Reason = "sync", Snapshot = result.Result }, Context.ConnectionAborted);
}

private async Task PushCountsToCallerAsync(int userId)
{
if (unitOfWork is null) return;
Expand Down
5 changes: 5 additions & 0 deletions RikiPath.Application/IRepositories/ILessonRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ Task<IReadOnlyList<AssessmentRoadmapLesson>> GetAssessmentRoadmapLessonsAsync(
Task<Lesson?> GetLearnerVisibleByIdAsync(
int lessonId,
CancellationToken cancellationToken = default);
Task<IReadOnlyList<Lesson>> GetLearnerVisibleByIdsAsync(
IReadOnlyCollection<int> lessonIds,
CancellationToken cancellationToken = default);
Task<(int Total, int Completed)> GetCompletionStatsAsync(int userId);
Task<IReadOnlyList<Lesson>> GetByCertificateLevelAsync(int certificateLevelId, CancellationToken cancellationToken = default);
Task<(int Total, Lesson? Lesson)> GetByCertificateLevelPositionAsync(
int certificateLevelId, int zeroBasedPosition, CancellationToken cancellationToken = default);
}

public sealed record AssessmentRoadmapLesson(
Expand Down
11 changes: 11 additions & 0 deletions RikiPath.Application/IServices/IAdminAiConfigurationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using RikiPath.Application.Requests.AdminConfig;
using RikiPath.Application.Responses;
using RikiPath.Application.Responses.AdminConfig;

namespace RikiPath.Application.IServices;

public interface IAdminAiConfigurationService
{
Task<ApiResponse<AdminAiConfigurationResponse>> GetAsync(CancellationToken ct);
Task<ApiResponse<AdminAiConfigurationResponse>> UpdateAsync(AdminAiConfigurationRequest request, int adminId, CancellationToken ct);
}
11 changes: 11 additions & 0 deletions RikiPath.Application/IServices/ICohortPreparationZipService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using RikiPath.Application.Responses;
using RikiPath.Application.Responses.StudyCourses;

namespace RikiPath.Application.IServices;

public interface ICohortPreparationZipService
{
Task<ApiResponse<CohortPreparationZipResponse>> UploadAsync(int cohortId, Stream content,
CancellationToken ct = default);
Task<ApiResponse<CohortPreparationZipResponse>> GetAsync(int cohortId, CancellationToken ct = default);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using RikiPath.Application.Responses;
using RikiPath.Application.Responses.MentorMeetings;

namespace RikiPath.Application.IServices;

public interface ICohortSessionLearningMaterialsService
{
Task<ApiResponse<CohortSessionLearningMaterialsResponse>> GetAsync(
int cohortId, int sessionId, CancellationToken ct = default);
Task<ApiResponse<CohortSessionLearningMaterialsResponse>> PrepareAsync(
int cohortId, int sessionId, IReadOnlyList<int> lessonIds, CancellationToken ct = default);
Task<bool> HasPreparedAsync(int cohortId, int sessionId, CancellationToken ct = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ public interface IGroupEnrollmentEntitlementContract
{
GroupEnrollmentEntitlementDecision EvaluateGroupEnrollment(
StudyCohort cohort,
StudyCoursePlan plan,
int learnerId,
string? entitlementReference);
}
2 changes: 2 additions & 0 deletions RikiPath.Application/IServices/ISidebarCounterService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using RikiPath.Application.Responses;
using RikiPath.Application.Responses.Sidebar;
using RikiPath.Domain.Enums;

namespace RikiPath.Application.IServices;

public interface ISidebarCounterService
{
Task<ApiResponse<SidebarCountersResponse>> GetMyCountersAsync(CancellationToken cancellationToken = default);
Task<ApiResponse<SidebarCountersResponse>> GetForUserAsync(int userId, Role role, CancellationToken cancellationToken = default);
}
10 changes: 10 additions & 0 deletions RikiPath.Application/IServices/IStudyCourseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ public interface IStudyCourseService
// Tìm lớp nhóm theo Mentor, cấp độ, cường độ, thứ và khung giờ (giờ Việt Nam).
Task<ApiResponse<object>> CohortsAsync(CohortDiscoveryFilter? filter, CancellationToken ct);
Task<ApiResponse<object>> SaveCohortAsync(int? id, SaveStudyCohort request, CancellationToken ct);
Task<ApiResponse<object>> CreateAdminCohortAsync(CreateAdminCohortRequest request, CancellationToken ct);
Task<ApiResponse<object>> AdminCohortMentorCandidatesAsync(AdminCohortMentorCandidatesRequest request, CancellationToken ct);
Task<ApiResponse<object>> CohortMentorInvitationsAsync(int? cohortId, CancellationToken ct);
Task<ApiResponse<object>> InviteCohortMentorAsync(int cohortId, InviteCohortMentorRequest request, CancellationToken ct);
Task<ApiResponse<object>> AcceptCohortMentorInvitationAsync(int invitationId, CancellationToken ct);
Task<ApiResponse<object>> DeclineCohortMentorInvitationAsync(int invitationId, DeclineCohortInvitationRequest request, CancellationToken ct);
Task<ApiResponse<object>> CancelCohortMentorInvitationAsync(int invitationId, CancellationToken ct);
Task<ApiResponse<object>> RequestCohortMentorChangeAsync(int cohortId, RequestCohortMentorChangeRequest request, CancellationToken ct);
// Admin xem trước xung đột lịch dạy của Mentor cho các khung giờ đã chọn (không ghi dữ liệu).
Task<ApiResponse<object>> CohortSchedulePreviewAsync(CohortSchedulePreviewRequest request, CancellationToken ct);
Task<ApiResponse<object>> CatalogAsync(CancellationToken ct);
Expand All @@ -36,6 +44,8 @@ public interface IStudyCourseService
Task<ApiResponse<object>> CancelPendingEnrollmentAsync(int id, CancellationToken ct);
Task<ApiResponse<object>> CancelCohortEnrollmentAsync(int id, CancelCohortEnrollmentRequest? request, CancellationToken ct);
Task<ApiResponse<object>> ConfirmPaymentAsync(int courseId, PaymentCallbackResult callback, string? reference, CancellationToken ct);
// Chỉ gọi nội bộ sau khi backend đã truy vấn trực tiếp trạng thái đơn từ PayOS.
Task<ApiResponse<object>> ConfirmVerifiedPaymentStatusAsync(int courseId, PaymentLinkInformation info, CancellationToken ct);
Task<ApiResponse<object>> ReconcileCoursePaymentAsync(int courseId, CancellationToken ct);
Task<ApiResponse<object>> AttendanceAsync(int id, int sessionId, ConfirmCourseAttendance request, CancellationToken ct);
Task<ApiResponse<object>> CompleteAsync(int id, CancellationToken ct);
Expand Down
Loading
Loading