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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ Legacy minimum-enrollment/preparation fields remain in stored policy revisions f
- 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.

## ZIP tài liệu chuẩn bị theo cấp độ

- Admin quản lý ZIP dùng chung cho từng cấp JLPT N5–N2 qua `GET /api/admin/level-preparation-zips` và `GET/PUT /api/admin/level-preparation-zips/{level}` (`PUT` nhận multipart `file`). Tệp nằm trong bucket Supabase private ở `level-preparation/{level}/materials.zip`; API danh sách chỉ trả trạng thái có ZIP, không công khai URL.
- Khi tạo lớp, Backend kiểm tra ZIP của level đã tồn tại và trả `409 COHORT_PREPARATION_ZIP_REQUIRED` nếu thiếu. Form tạo lớp không tải ZIP lên. `GET /api/study-courses/cohorts/{cohortId}/preparation-zip` giữ kiểm tra quyền cũ rồi ký URL ngắn hạn của ZIP theo level. Thay ZIP cấp độ áp dụng ngay cho mọi lớp cùng cấp; ZIP riêng của lớp cũ chỉ được dùng khi cấp độ chưa có ZIP chung.
- Không thay đổi entity, schema hay migration cho luồng này.

## 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.
Expand Down
11 changes: 7 additions & 4 deletions RikiPath.Application/Handlers/GrammarImportHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ private static ImportRowDiffResponse BuildRowDiff(
// ---- Validate ----
if (string.IsNullOrWhiteSpace(title)) diff.Errors.Add("Thiếu cột Title.");
if (string.IsNullOrWhiteSpace(structure)) diff.Errors.Add("Thiếu cột Structure.");
ImportHandlerSupport.CheckLevel(levelCode, levelsByCode, ambiguousLevelCodes, diff.Errors);
if (!string.IsNullOrWhiteSpace(levelCode))
ImportHandlerSupport.CheckLevel(levelCode, levelsByCode, ambiguousLevelCodes, diff.Errors);
else if (string.IsNullOrWhiteSpace(lessonTitle))
diff.Errors.Add("Cần Certificate Level Code hoặc Lesson Title để liên kết ngữ pháp.");

// ---- Kiểm tra "đã có chưa" ngoài dữ liệu của chính dòng ----
if (!string.IsNullOrWhiteSpace(title))
Expand Down Expand Up @@ -110,8 +113,8 @@ private static ImportRowDiffResponse BuildRowDiff(
UsageNotes = usageNotes,
ExampleSentence = exampleSentence,
ExampleSentenceMeaning = exampleSentenceMeaning,
CertificateLevelCode = levelCode!,
CertificateLevelId = levelsByCode[levelCode!],
CertificateLevelCode = levelCode ?? string.Empty,
CertificateLevelId = string.IsNullOrWhiteSpace(levelCode) ? 0 : levelsByCode[levelCode],
LessonTitle = lessonTitle,
};

Expand Down Expand Up @@ -156,4 +159,4 @@ private static ImportRowDiffResponse BuildRowDiff(
return diff;
}
}
}
}
11 changes: 7 additions & 4 deletions RikiPath.Application/Handlers/KanjiImportHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,10 @@ private static ImportRowDiffResponse BuildRowDiff(
if (!isValidStrokeCount)
diff.Errors.Add("Stroke Count phải là số nguyên dương.");

ImportHandlerSupport.CheckLevel(levelCode, levelsByCode, ambiguousLevelCodes, diff.Errors);
if (!string.IsNullOrWhiteSpace(levelCode))
ImportHandlerSupport.CheckLevel(levelCode, levelsByCode, ambiguousLevelCodes, diff.Errors);
else if (string.IsNullOrWhiteSpace(lessonTitle))
diff.Errors.Add("Cần Certificate Level Code hoặc Lesson Title để liên kết hán tự.");

if (!string.IsNullOrWhiteSpace(character))
{
Expand Down Expand Up @@ -122,8 +125,8 @@ private static ImportRowDiffResponse BuildRowDiff(
OnYomi = onYomi,
KunYomi = kunYomi,
StrokeCount = strokeCount,
CertificateLevelCode = levelCode!,
CertificateLevelId = levelsByCode[levelCode!],
CertificateLevelCode = levelCode ?? string.Empty,
CertificateLevelId = string.IsNullOrWhiteSpace(levelCode) ? 0 : levelsByCode[levelCode],
LessonTitle = lessonTitle,
};

Expand Down Expand Up @@ -171,4 +174,4 @@ private static ImportRowDiffResponse BuildRowDiff(
return diff;
}
}
}
}
27 changes: 15 additions & 12 deletions RikiPath.Application/Handlers/LessonImportHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public async Task<SheetImportResponse> BuildDiffAsync(IReadOnlyList<ExcelRow> ro

private static ImportRowDiffResponse BuildRowDiff(
ExcelRow row,
ILookup<(string Title, int CertificateLevelId), Lesson> existingByKey,
ILookup<(string Title, int? CertificateLevelId), Lesson> existingByKey,
Dictionary<string, int> levelsByCode,
HashSet<string> ambiguousLevelCodes,
Dictionary<string, Domain.Entities.LanguageSkill> skillsByName,
Expand All @@ -66,6 +66,7 @@ private static ImportRowDiffResponse BuildRowDiff(
var skillName = row.Get("Language Skill Name");
var sortOrderRaw = row.Get("Sort Order");
var topicTitle = ImportHandlerSupport.Clean(row.Get("Topic Title") ?? row.Get("Chapter Title"));
var topicDescription = ImportHandlerSupport.Clean(row.Get("Topic Description"));
var stageCode = ImportHandlerSupport.Clean(row.Get("Stage Code"));
var stageObjectives = ImportHandlerSupport.Clean(row.Get("Stage Objectives"));
var stageSortRaw = ImportHandlerSupport.Clean(row.Get("Stage Sort Order"));
Expand All @@ -74,8 +75,8 @@ private static ImportRowDiffResponse BuildRowDiff(
var prerequisiteTitle = ImportHandlerSupport.Clean(row.Get("Prerequisite Lesson Title"));
var sourceProvenance = ImportHandlerSupport.Clean(row.Get("Source Provenance"));

var hasKey = !string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(levelCode);
var rowKey = hasKey ? $"{title} / {levelCode}" : title ?? $"(dòng {row.RowNumber})";
var hasKey = !string.IsNullOrWhiteSpace(title);
var rowKey = hasKey ? $"{title} / {(string.IsNullOrWhiteSpace(levelCode) ? "Không cấp độ" : levelCode)}" : $"(dòng {row.RowNumber})";

var diff = new ImportRowDiffResponse
{
Expand All @@ -99,11 +100,12 @@ private static ImportRowDiffResponse BuildRowDiff(

if (string.IsNullOrWhiteSpace(title)) diff.Errors.Add("Thiếu cột LessonTitle.");
var audioUrl = ImportHandlerSupport.CheckUrl(audio, "AudioUrl", "", diff.Errors);
ImportHandlerSupport.CheckLevel(levelCode, levelsByCode, ambiguousLevelCodes, diff.Errors);
if (!string.IsNullOrWhiteSpace(levelCode))
ImportHandlerSupport.CheckLevel(levelCode, levelsByCode, ambiguousLevelCodes, diff.Errors);

Domain.Entities.LanguageSkill? skill = null;
if (string.IsNullOrWhiteSpace(skillName))
diff.Errors.Add("Thiếu cột Language Skill Name.");
skill = null;
else if (ambiguousSkillNames.Contains(skillName))
diff.Errors.Add($"Language Skill '{skillName}' bị trùng tên trong hệ thống, không xác định được kỹ năng.");
else if (!skillsByName.TryGetValue(skillName, out skill))
Expand Down Expand Up @@ -148,7 +150,7 @@ private static ImportRowDiffResponse BuildRowDiff(
return diff;
}

var levelId = levelsByCode[levelCode!];
int? levelId = string.IsNullOrWhiteSpace(levelCode) ? null : levelsByCode[levelCode];
var matches = existingByKey[(title!, levelId)];
if (matches.Skip(1).Any())
{
Expand All @@ -171,14 +173,15 @@ private static ImportRowDiffResponse BuildRowDiff(
LearningObjectives = learningObjectives ?? existing?.LearningObjectives,
PrerequisiteLessonTitle = prerequisiteTitle,
SourceProvenance = sourceProvenance ?? existing?.SourceProvenance,
CertificateLevelCode = levelCode!,
CertificateLevelCode = levelCode ?? string.Empty,
CertificateLevelId = levelId,
LanguageSkillId = skill!.Id,
LanguageSkillId = skill?.Id,
TopicId = existing?.TopicId,
TopicTitle = topicTitle ?? existing?.Topic?.Title,
StageCode = stageCode ?? existing?.Topic?.StageCode,
StageSortOrder = stageSortOrder ?? existing?.Topic?.SortOrder,
StageObjectives = stageObjectives ?? existing?.Topic?.LearningObjectives,
TopicDescription = topicDescription,
StageCode = stageCode,
StageSortOrder = stageSortOrder,
StageObjectives = stageObjectives,
};

if (existing is null)
Expand All @@ -196,7 +199,7 @@ private static ImportRowDiffResponse BuildRowDiff(
ImportHandlerSupport.CompareField(changed, "description", existing.Description, payload.Description);
if (audioUrl is not null)
ImportHandlerSupport.CompareField(changed, "audioUrl", existing.AudioUrl, audioUrl);
ImportHandlerSupport.CompareField(changed, "languageSkillName", existing.LanguageSkill?.Name, skill.Name);
ImportHandlerSupport.CompareField(changed, "languageSkillName", existing.LanguageSkill?.Name, skill?.Name);
ImportHandlerSupport.CompareField(changed, "sortOrder", existing.SortOrder.ToString(), payload.SortOrder.ToString());
if (topicTitle is not null)
ImportHandlerSupport.CompareField(changed, "topicTitle", existing.Topic?.Title, topicTitle);
Expand Down
23 changes: 15 additions & 8 deletions RikiPath.Application/Handlers/MockTestImportHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ public async Task<SheetImportResponse> BuildDiffAsync(IReadOnlyList<ExcelRow> ro
var existingTests = await unitOfWork.MockTests.Query()
.Include(t => t.CertificateLevel)
.Include(t => t.Sections).ThenInclude(s => s.Questions).ThenInclude(q => q.Options)
.Where(t => !t.IsDeleted && titles.Contains(t.Title))
.Where(t => !t.IsDeleted && !t.IsArchivedVersion && titles.Contains(t.Title)
&& (t.ExamKind == ExamKind.FullMockTest || t.ExamKind == ExamKind.Placement))
.ToListAsync(cancellationToken);
var (existingByKey, ambiguousKeys) = ImportHandlerSupport.IndexByKey(
existingTests, t => NaturalKey(t.Title, t.CertificateLevelId));
existingTests, t => NaturalKey(t.Title, t.CertificateLevelId,
t.ExamKind == ExamKind.Placement));

var (levelsByCode, ambiguousLevelCodes) = await ImportHandlerSupport.LoadLevelsAsync(unitOfWork, cancellationToken);

Expand All @@ -47,15 +49,16 @@ public async Task<SheetImportResponse> BuildDiffAsync(IReadOnlyList<ExcelRow> ro
certSectionsByCode, ambiguousSectionCodes, certSections.ToDictionary(s => s.Id, s => s.Code),
certSections, openRowKeys);

// Gộp theo tên đề + mã cấp độ; cùng tên ở N5 và N4 là hai đề khác nhau.
// Gộp theo tên, cấp độ và loại đề; placement không trộn với mock test cùng tên.
var groups = new List<List<ExcelRow>>();
var byExam = new Dictionary<string, List<ExcelRow>>(StringComparer.Ordinal);
foreach (var row in rows)
{
var title = ImportHandlerSupport.Clean(row.Get("MockTestTitle"));
if (title is null) { groups.Add([row]); continue; }
var levelCode = ImportHandlerSupport.Clean(row.Get("CertificateLevelCode"))?.ToUpperInvariant();
var examKey = $"{title}\u001f{levelCode}";
var placement = ImportHandlerSupport.Clean(row.Get("IsPlacementAssessment"))?.ToLowerInvariant();
var examKey = $"{title}\u001f{levelCode}\u001f{placement}";
if (!byExam.TryGetValue(examKey, out var list)) { byExam[examKey] = list = []; groups.Add(list); }
list.Add(row);
}
Expand All @@ -72,7 +75,8 @@ public async Task<SheetImportResponse> BuildDiffAsync(IReadOnlyList<ExcelRow> ro
return result;
}

private static string NaturalKey(string title, int certificateLevelId) => $"{title}|{certificateLevelId}";
private static string NaturalKey(string title, int certificateLevelId, bool placement) =>
$"{title}|{certificateLevelId}|{(placement ? "placement" : "mock")}";

private sealed record DiffContext(
Dictionary<string, Domain.Entities.MockTest> ExistingByKey,
Expand Down Expand Up @@ -129,7 +133,9 @@ private static ImportRowDiffResponse BuildGroupDiff(List<ExcelRow> group, DiffCo
else if (!int.TryParse(timeRaw, out timeLimit) || timeLimit <= 0)
errors.Add($"{P(first)}TimeLimitMinutes phải là số nguyên dương.");

var rowKey = title is not null && levelCode is not null ? $"{title} / {levelCode}" : title ?? $"(dòng {first.RowNumber})";
var rowKey = title is not null && levelCode is not null
? $"{title} / {levelCode}" + (isPlacement ? " / Placement" : string.Empty)
: title ?? $"(dòng {first.RowNumber})";
if (title is not null && levelCode is not null && ctx.OpenRowKeys.Contains(rowKey))
errors.Add($"{P(first)}Đề thi '{title}' ({levelCode}) đang có bản nháp chờ Quản trị viên duyệt, chưa thể nhập lại.");

Expand Down Expand Up @@ -328,7 +334,8 @@ private static ImportRowDiffResponse BuildGroupDiff(List<ExcelRow> group, DiffCo
});
}

var coverageError = ImportHandlerSupport.ValidateMockTestCoverage(levelCode, sectionPayloads, ctx.SkillNameById);
var coverageError = isPlacement ? null :
ImportHandlerSupport.ValidateMockTestCoverage(levelCode, sectionPayloads, ctx.SkillNameById);
if (coverageError is not null) errors.Add(P(first) + coverageError);
foreach (var section in sectionPayloads)
foreach (var question in section.Questions)
Expand All @@ -346,7 +353,7 @@ private static ImportRowDiffResponse BuildGroupDiff(List<ExcelRow> group, DiffCo
}

var levelId = ctx.LevelsByCode[levelCode!];
var key = NaturalKey(title!, levelId);
var key = NaturalKey(title!, levelId, isPlacement);
if (ctx.AmbiguousKeys.Contains(key))
{
diff.Errors.Add($"Có nhiều đề thi '{title}' ({levelCode}) trùng nhau trong hệ thống, cần dọn dữ liệu trước khi import.");
Expand Down
Loading
Loading