From b9d221024e4fee303f05d9c054ffa4811c781f4a Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sun, 1 Nov 2026 13:38:28 +0300 Subject: [PATCH] Integrate chapter learning management and public course discovery --- package.json | 1 + scripts/learning-integration.test.mjs | 109 +++++++++ src/api/courses.api.ts | 174 ++++++------- src/api/learningHierarchy.api.ts | 69 ++++++ src/api/publicCatalog.api.ts | 38 +++ src/api/users.api.ts | 120 ++------- src/app/AppRoutes.tsx | 223 ++--------------- src/components/sidebar/Sidebar.tsx | 7 +- src/lib/practiceParentTitles.ts | 230 ++---------------- src/lib/practiceParents.ts | 12 +- src/lib/publicApiBase.ts | 4 + src/pages/auth/LoginPage.tsx | 1 + src/pages/catalog/PublicCatalogPage.tsx | 85 +++++++ .../ContentManagementLayout.tsx | 2 +- .../LearningHierarchyPage.tsx | 149 ++++++++++++ .../PracticeQuestionsPage.tsx | 51 ++-- .../practice-steps/PracticeParentsField.tsx | 21 +- .../UserLearningActivitySection.tsx | 86 ++----- src/types/course.types.ts | 1 + src/types/userAdmin.types.ts | 29 +-- 20 files changed, 669 insertions(+), 743 deletions(-) create mode 100644 scripts/learning-integration.test.mjs create mode 100644 src/api/learningHierarchy.api.ts create mode 100644 src/api/publicCatalog.api.ts create mode 100644 src/lib/publicApiBase.ts create mode 100644 src/pages/catalog/PublicCatalogPage.tsx create mode 100644 src/pages/content-management/LearningHierarchyPage.tsx diff --git a/package.json b/package.json index f6df94c..9cd4ba7 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite", "build": "vite build", + "test:learning": "node --test scripts/learning-integration.test.mjs", "lint": "eslint .", "preview": "vite preview" }, diff --git a/scripts/learning-integration.test.mjs b/scripts/learning-integration.test.mjs new file mode 100644 index 0000000..e295a2c --- /dev/null +++ b/scripts/learning-integration.test.mjs @@ -0,0 +1,109 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { build } from "esbuild" + +async function loadModule(path, http = {}) { + const key = `learningTest${Math.random().toString(36).slice(2)}` + globalThis[key] = http + const result = await build({ + entryPoints: [path], bundle: true, write: false, platform: "node", format: "esm", + define: { "import.meta.env": "{}" }, + plugins: [{ name: "http-fixture", setup(builder) { + builder.onResolve({ filter: /(^|\/)http$/ }, () => ({ path: "http", namespace: "fixture" })) + builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ contents: `export default globalThis[${JSON.stringify(key)}]` })) + } }], + }) + const module = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString("base64")}`) + return module +} + +test("chapter lesson pagination uses the public collection key", async () => { + const calls = [] + const api = await loadModule("src/api/learningHierarchy.api.ts", { get: async (path, options) => { + calls.push([path, options.params]) + const offset = options.params.offset + return { data: { data: { lessons: Array.from({ length: offset === 0 ? 200 : 1 }, (_, i) => ({ id: offset + i + 1 })), total_count: 201 } } } + } }) + assert.equal((await api.listLearningItems("/chapters/7/lessons", "lessons")).length, 201) + assert.deepEqual(calls.map((call) => call[1].offset), [0, 200]) + assert.ok(calls.every((call) => call[0] === "/chapters/7/lessons")) +}) + +test("quiz publication updates both statuses without replacing questions", async () => { + const calls = [] + const api = await loadModule("src/api/learningHierarchy.api.ts", { put: async (...args) => calls.push(args) }) + await api.updateChapterQuiz(9, { publish_status: "PUBLISHED" }) + assert.deepEqual(calls, [["/quizzes/9/full", { practice: { publish_status: "PUBLISHED" }, question_set: { status: "PUBLISHED" } }]]) +}) + +test("quiz creation uses a QUIZ set and cleans it up if chapter linking fails", async () => { + const calls = [] + const failure = new Error("chapter unavailable") + const api = await loadModule("src/api/learningHierarchy.api.ts", { + post: async (path, body) => { + calls.push([path, body]) + if (path === "/question-sets") return { data: { data: { id: 12 } } } + throw failure + }, + delete: async (path) => calls.push([path]), + }) + await assert.rejects(api.createChapterQuiz(7, "Review"), failure) + assert.deepEqual(calls, [ + ["/question-sets", { title: "Review", set_type: "QUIZ", status: "DRAFT" }], + ["/chapters/7/quizzes", { title: "Review", question_set_id: 12, publish_status: "DRAFT" }], + ["/question-sets/12"], + ]) +}) + +test("public CHAPTER parents survive practice normalization", async () => { + const parents = await loadModule("src/lib/practiceParents.ts") + assert.deepEqual(parents.normalizePracticeParents({ parents: [{ parent_kind: "CHAPTER", parent_id: 7 }] }), [{ parent_kind: "CHAPTER", parent_id: 7 }]) + assert.equal(parents.formatPracticeParentLabel({ parent_kind: "CHAPTER", parent_id: 7 }), "Chapter #7") +}) + +test("admin quiz questions consume the data array from the question-set API", async () => { + const rows = [{ id: 31, question_text: "Review question" }] + const api = await loadModule("src/api/learningHierarchy.api.ts", { get: async (path) => { + assert.equal(path, "/question-sets/12/questions") + return { data: { data: rows } } + } }) + assert.deepEqual(await api.getQuizQuestions(12), rows) +}) + +test("user learning activity preserves the course chapter lesson tree", async () => { + const users = await loadModule("src/api/users.api.ts") + const activity = users.normalizeUserLearningActivity({ user_id: 42, learning: { + progress: { courses: [{ id: 3, name: "Course", chapters: [{ id: 7, course_id: 3, name: "Chapter", lessons: [{ id: 11, chapter_id: 7, title: "Lesson" }] }] }] }, + completions: { user_id: 42, courses: [{ id: 3 }] }, + } }) + const chapter = activity.learning.progress.courses[0].chapters[0] + assert.equal(chapter.course_id, 3) + assert.equal(chapter.lessons[0].chapter_id, 7) + assert.equal(chapter.lessons[0].title, "Lesson") + assert.equal(activity.learning.completions.courses.length, 1) + assert.equal("modules" in chapter, false) +}) + + +test("public catalog base strips the admin suffix", async () => { + const { publicApiBase } = await loadModule("src/lib/publicApiBase.ts") + assert.equal(publicApiBase("https://api.example.test/api/v1/admin/"), "https://api.example.test/api/v1") + assert.equal(publicApiBase("/api/v1"), "/api/v1") +}) + +test("catalog browsing does not send a staff token or cookies", async () => { + const original = globalThis.fetch + const calls = [] + globalThis.fetch = async (url, options) => { + calls.push([url, options]) + return { ok: true, json: async () => ({ data: { courses: [], total_count: 0 } }) } + } + try { + const api = await loadModule("src/api/publicCatalog.api.ts") + await api.getPublicCourses("hello world", 12) + await api.getPublicCourse(3) + assert.equal(calls[0][0], "/api/v1/catalog/courses?q=hello+world&limit=12&offset=12") + assert.equal(calls[1][0], "/api/v1/catalog/courses/3") + assert.ok(calls.every(([,options]) => options.credentials === "omit" && options.headers === undefined)) + } finally { globalThis.fetch = original } +}) diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index 477a3f8..2624202 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -512,160 +512,160 @@ export const reorderModuleLessons = ( data: ReorderOrderedIdsRequest, ) => http.put(`/modules/${moduleId}/lessons/reorder`, data) -/** PUT /exam-prep/catalog-courses/reorder */ +/** PUT /courses/reorder */ export const reorderExamPrepCatalogCourses = (data: ReorderOrderedIdsRequest) => - http.put("/exam-prep/catalog-courses/reorder", data) + http.put("/courses/reorder", data) -/** PUT /exam-prep/catalog-courses/:catalogCourseId/units/reorder */ +/** PUT /courses/:catalogCourseId/chapters/reorder */ export const reorderExamPrepUnitsInCatalogCourse = ( catalogCourseId: number, data: ReorderOrderedIdsRequest, ) => http.put( - `/exam-prep/catalog-courses/${catalogCourseId}/units/reorder`, + `/courses/${catalogCourseId}/chapters/reorder`, data, ) -/** PUT /exam-prep/units/:unitId/modules/reorder */ +/** PUT /chapters/:unitId/modules/reorder */ export const reorderExamPrepModulesInUnit = ( unitId: number, data: ReorderOrderedIdsRequest, -) => http.put(`/exam-prep/units/${unitId}/modules/reorder`, data) +) => http.put(`/chapters/${unitId}/modules/reorder`, data) -/** PUT /exam-prep/modules/:moduleId/lessons/reorder */ +/** PUT /modules/:moduleId/lessons/reorder */ export const reorderExamPrepLessonsInModule = ( moduleId: number, data: ReorderOrderedIdsRequest, -) => http.put(`/exam-prep/modules/${moduleId}/lessons/reorder`, data) +) => http.put(`/modules/${moduleId}/lessons/reorder`, data) export const createProgramCourse = ( programId: number, data: CreateProgramCourseRequest, ) => http.post(`/programs/${programId}/courses`, data) -/** English proficiency catalog course — POST /exam-prep/catalog-courses */ +/** English proficiency catalog course — POST /courses */ export const createExamPrepCatalogCourse = ( data: CreateExamPrepCatalogCourseRequest, -) => http.post("/exam-prep/catalog-courses", data) +) => http.post("/courses", data) -/** English proficiency catalog courses — GET /exam-prep/catalog-courses */ +/** English proficiency catalog courses — GET /courses */ export const getExamPrepCatalogCourses = (params?: { limit?: number; offset?: number }) => - http.get("/exam-prep/catalog-courses", { params }) + http.get("/courses", { params }) -/** English proficiency catalog course — PUT /exam-prep/catalog-courses/:catalogCourseId */ +/** English proficiency catalog course — PUT /courses/:catalogCourseId */ export const updateExamPrepCatalogCourse = ( catalogCourseId: number, data: UpdateExamPrepCatalogCourseRequest, ) => http.put( - `/exam-prep/catalog-courses/${catalogCourseId}`, + `/courses/${catalogCourseId}`, data, ) -/** English proficiency catalog course — DELETE /exam-prep/catalog-courses/:catalogCourseId */ +/** English proficiency catalog course — DELETE /courses/:catalogCourseId */ export const deleteExamPrepCatalogCourse = (catalogCourseId: number) => - http.delete(`/exam-prep/catalog-courses/${catalogCourseId}`) + http.delete(`/courses/${catalogCourseId}`) -/** English proficiency catalog unit — POST /exam-prep/catalog-courses/:catalogCourseId/units */ +/** English proficiency catalog unit — POST /courses/:catalogCourseId/chapters */ export const createExamPrepCatalogUnit = ( catalogCourseId: number, data: CreateExamPrepCatalogUnitRequest, ) => http.post( - `/exam-prep/catalog-courses/${catalogCourseId}/units`, + `/courses/${catalogCourseId}/chapters`, data, ) -/** English proficiency catalog units — GET /exam-prep/catalog-courses/:catalogCourseId/units */ +/** English proficiency catalog units — GET /courses/:catalogCourseId/chapters */ export const getExamPrepCatalogUnits = ( catalogCourseId: number, params?: { limit?: number; offset?: number }, ) => http.get( - `/exam-prep/catalog-courses/${catalogCourseId}/units`, + `/courses/${catalogCourseId}/chapters`, { params }, ) -/** English proficiency unit — PUT /exam-prep/units/:unitId */ +/** English proficiency unit — PUT /chapters/:unitId */ export const updateExamPrepCatalogUnit = ( unitId: number, data: UpdateExamPrepCatalogUnitRequest, -) => http.put(`/exam-prep/units/${unitId}`, data) +) => http.put(`/chapters/${unitId}`, data) -/** English proficiency unit — DELETE /exam-prep/units/:unitId */ +/** English proficiency unit — DELETE /chapters/:unitId */ export const deleteExamPrepCatalogUnit = (unitId: number) => - http.delete(`/exam-prep/units/${unitId}`) + http.delete(`/chapters/${unitId}`) -/** English proficiency unit modules — POST /exam-prep/units/:unitId/modules */ +/** English proficiency unit modules — POST /chapters/:unitId/modules */ export const createExamPrepUnitModule = ( unitId: number, data: CreateExamPrepUnitModuleRequest, ) => http.post( - `/exam-prep/units/${unitId}/modules`, + `/chapters/${unitId}/modules`, data, ) -/** English proficiency unit modules — GET /exam-prep/units/:unitId/modules */ +/** English proficiency unit modules — GET /chapters/:unitId/modules */ export const getExamPrepUnitModules = ( unitId: number, params?: { limit?: number; offset?: number }, ) => - http.get(`/exam-prep/units/${unitId}/modules`, { + http.get(`/chapters/${unitId}/modules`, { params, }) -/** English proficiency module — PUT /exam-prep/modules/:moduleId */ +/** English proficiency module — PUT /modules/:moduleId */ export const updateExamPrepUnitModule = ( moduleId: number, data: UpdateExamPrepUnitModuleRequest, ) => http.put( - `/exam-prep/modules/${moduleId}`, + `/modules/${moduleId}`, data, ) -/** English proficiency module — DELETE /exam-prep/modules/:moduleId */ +/** English proficiency module — DELETE /modules/:moduleId */ export const deleteExamPrepUnitModule = (moduleId: number) => - http.delete(`/exam-prep/modules/${moduleId}`) + http.delete(`/modules/${moduleId}`) -/** English proficiency module lessons — GET /exam-prep/modules/:moduleId/lessons */ +/** English proficiency module lessons — GET /modules/:moduleId/lessons */ export const getExamPrepModuleLessons = ( moduleId: number, params?: { limit?: number; offset?: number }, ) => http.get( - `/exam-prep/modules/${moduleId}/lessons`, + `/modules/${moduleId}/lessons`, { params, }, ) -/** English proficiency module lesson — POST /exam-prep/modules/:moduleId/lessons */ +/** English proficiency module lesson — POST /modules/:moduleId/lessons */ export const createExamPrepModuleLesson = ( moduleId: number, data: CreateExamPrepModuleLessonRequest, ) => http.post( - `/exam-prep/modules/${moduleId}/lessons`, + `/modules/${moduleId}/lessons`, data, ) -/** English proficiency lesson — PUT /exam-prep/lessons/:lessonId */ +/** English proficiency lesson — PUT /lessons/:lessonId */ export const updateExamPrepModuleLesson = ( lessonId: number, data: UpdateExamPrepModuleLessonRequest, ) => http.put( - `/exam-prep/lessons/${lessonId}`, + `/lessons/${lessonId}`, data, ) -/** PUT /exam-prep/lessons/:lessonId — set publish_status only. */ +/** PUT /lessons/:lessonId — set publish_status only. */ export const setExamPrepModuleLessonPublishStatus = ( lessonId: number, data: PublishStatusOnlyRequest, -) => http.put(`/exam-prep/lessons/${lessonId}`, data) +) => http.put(`/lessons/${lessonId}`, data) /** @deprecated Use setExamPrepModuleLessonPublishStatus */ export const publishExamPrepModuleLesson = ( @@ -673,115 +673,115 @@ export const publishExamPrepModuleLesson = ( data: PublishExamPrepModuleLessonRequest, ) => setExamPrepModuleLessonPublishStatus(lessonId, data) -/** PUT /exam-prep/lessons/:lessonId — set access_tier only. */ +/** PUT /lessons/:lessonId — set access_tier only. */ export const setExamPrepModuleLessonAccessTier = ( lessonId: number, data: AccessTierOnlyRequest, -) => http.put(`/exam-prep/lessons/${lessonId}`, data) +) => http.put(`/lessons/${lessonId}`, data) -/** English proficiency lesson — DELETE /exam-prep/lessons/:lessonId */ +/** English proficiency lesson — DELETE /lessons/:lessonId */ export const deleteExamPrepModuleLesson = (lessonId: number) => - http.delete(`/exam-prep/lessons/${lessonId}`) + http.delete(`/lessons/${lessonId}`) -/** POST /exam-prep/catalog-courses/:catalogCourseId/practices */ +/** POST /courses/:catalogCourseId/practices */ export const createExamPrepCatalogCoursePractice = ( catalogCourseId: number, data: CreateExamPrepCatalogCoursePracticeRequest, ) => http.post( - `/exam-prep/catalog-courses/${catalogCourseId}/practices`, + `/courses/${catalogCourseId}/practices`, data, ) -/** GET /exam-prep/catalog-courses/:catalogCourseId/practices */ +/** GET /courses/:catalogCourseId/practices */ export const getExamPrepCatalogCoursePractices = ( catalogCourseId: number, params?: { limit?: number; offset?: number }, ) => http.get( - `/exam-prep/catalog-courses/${catalogCourseId}/practices`, + `/courses/${catalogCourseId}/practices`, { params }, ) -/** POST /exam-prep/units/:unitId/practices */ +/** POST /chapters/:unitId/practices */ export const createExamPrepUnitPractice = ( unitId: number, data: CreateExamPrepUnitPracticeRequest, ) => http.post( - `/exam-prep/units/${unitId}/practices`, + `/chapters/${unitId}/practices`, data, ) -/** GET /exam-prep/units/:unitId/practices */ +/** GET /chapters/:unitId/practices */ export const getExamPrepUnitPractices = ( unitId: number, params?: { limit?: number; offset?: number }, ) => http.get( - `/exam-prep/units/${unitId}/practices`, + `/chapters/${unitId}/practices`, { params }, ) -/** POST /exam-prep/lessons/:lessonId/practices */ +/** POST /lessons/:lessonId/practices */ export const createExamPrepLessonPractice = ( lessonId: number, data: CreateExamPrepLessonPracticeRequest, ) => http.post( - `/exam-prep/lessons/${lessonId}/practices`, + `/lessons/${lessonId}/practices`, data, ) -/** GET /exam-prep/lessons/:lessonId/practices */ +/** GET /lessons/:lessonId/practices */ export const getExamPrepLessonPractices = ( lessonId: number, params?: { limit?: number; offset?: number }, ) => http.get( - `/exam-prep/lessons/${lessonId}/practices`, + `/lessons/${lessonId}/practices`, { params }, ) -/** POST /exam-prep/practices — create practice with optional parents. */ +/** POST /practices — create practice with optional parents. */ export const createExamPrepPractice = (data: CreateExamPrepPracticeRequest) => - http.post("/exam-prep/practices", data) + http.post("/practices", data) -/** GET /exam-prep/practices — list practices (supports unlinked_only). */ +/** GET /practices — list practices (supports unlinked_only). */ export const getExamPrepPractices = (params?: GetPracticesListParams) => - http.get("/exam-prep/practices", { params }) + http.get("/practices", { params }) -/** PUT /exam-prep/practices/:id/parents — replace all parent links. */ +/** PUT /practices/:id/parents — replace all parent links. */ export const updateExamPrepPracticeParents = ( practiceId: number, data: UpdatePracticeParentsRequest, ) => http.put( - `/exam-prep/practices/${practiceId}/parents`, + `/practices/${practiceId}/parents`, data, ) -/** DELETE /exam-prep/practices/:id/parents/:parentKind/:parentId — unlink one parent. */ +/** DELETE /practices/:id/parents/:parentKind/:parentId — unlink one parent. */ export const unlinkExamPrepPracticeParent = ( practiceId: number, parent: PracticeParent, ) => http.delete( - `/exam-prep/practices/${practiceId}/parents/${parent.parent_kind.toUpperCase()}/${parent.parent_id}`, + `/practices/${practiceId}/parents/${parent.parent_kind.toUpperCase()}/${parent.parent_id}`, { skipErrorToast: true }, ) -/** DELETE /exam-prep/practices/:practiceId */ +/** DELETE /practices/:practiceId */ export const deleteExamPrepPractice = (practiceId: number) => http.delete<{ message: string; success: boolean; status_code: number; metadata: unknown }>( - `/exam-prep/practices/${practiceId}`, + `/practices/${practiceId}`, ) -/** PUT /exam-prep/practices/:practiceId — set publish_status only. */ +/** PUT /practices/:practiceId — set publish_status only. */ export const setExamPrepPracticePublishStatus = ( practiceId: number, data: PublishStatusOnlyRequest, -) => http.put(`/exam-prep/practices/${practiceId}`, data) +) => http.put(`/practices/${practiceId}`, data) /** PUT /programs/:programId — set publish_status only. */ export const setLearningProgramPublishStatus = ( @@ -807,41 +807,41 @@ export const setProgramCourseAccessTier = ( data: AccessTierOnlyRequest, ) => http.put(`/courses/${courseId}`, data) -/** PUT /exam-prep/catalog-courses/:catalogCourseId — set publish_status only. */ +/** PUT /courses/:catalogCourseId — set publish_status only. */ export const setExamPrepCatalogCoursePublishStatus = ( catalogCourseId: number, data: PublishStatusOnlyRequest, -) => http.put(`/exam-prep/catalog-courses/${catalogCourseId}`, data) +) => http.put(`/courses/${catalogCourseId}`, data) -/** PUT /exam-prep/catalog-courses/:catalogCourseId — set access_tier only. */ +/** PUT /courses/:catalogCourseId — set access_tier only. */ export const setExamPrepCatalogCourseAccessTier = ( catalogCourseId: number, data: AccessTierOnlyRequest, -) => http.put(`/exam-prep/catalog-courses/${catalogCourseId}`, data) +) => http.put(`/courses/${catalogCourseId}`, data) -/** PUT /exam-prep/units/:unitId — set publish_status only. */ +/** PUT /chapters/:unitId — set publish_status only. */ export const setExamPrepCatalogUnitPublishStatus = ( unitId: number, data: PublishStatusOnlyRequest, -) => http.put(`/exam-prep/units/${unitId}`, data) +) => http.put(`/chapters/${unitId}`, data) -/** PUT /exam-prep/units/:unitId — set access_tier only. */ +/** PUT /chapters/:unitId — set access_tier only. */ export const setExamPrepCatalogUnitAccessTier = ( unitId: number, data: AccessTierOnlyRequest, -) => http.put(`/exam-prep/units/${unitId}`, data) +) => http.put(`/chapters/${unitId}`, data) -/** PUT /exam-prep/modules/:moduleId — set publish_status only. */ +/** PUT /modules/:moduleId — set publish_status only. */ export const setExamPrepUnitModulePublishStatus = ( moduleId: number, data: PublishStatusOnlyRequest, -) => http.put(`/exam-prep/modules/${moduleId}`, data) +) => http.put(`/modules/${moduleId}`, data) -/** PUT /exam-prep/modules/:moduleId — set access_tier only. */ +/** PUT /modules/:moduleId — set access_tier only. */ export const setExamPrepUnitModuleAccessTier = ( moduleId: number, data: AccessTierOnlyRequest, -) => http.put(`/exam-prep/modules/${moduleId}`, data) +) => http.put(`/modules/${moduleId}`, data) /** PUT /modules/:moduleId — set publish_status only (Learn English module). */ export const setTopLevelCourseModulePublishStatus = ( @@ -992,19 +992,19 @@ export const updateLearnEnglishPracticeFull = ( ) => http.put(`/practices/${practiceId}/full`, data) -/** GET /exam-prep/practices/:id/full */ +/** GET /practices/:id/full */ export const getExamPrepPracticeFull = (practiceId: number) => - http.get(`/exam-prep/practices/${practiceId}/full`, { + http.get(`/practices/${practiceId}/full`, { skipErrorToast: true, }) -/** PUT /exam-prep/practices/:id/full */ +/** PUT /practices/:id/full */ export const updateExamPrepPracticeFull = ( practiceId: number, data: UpdatePracticeFullRequest, ) => http.put( - `/exam-prep/practices/${practiceId}/full`, + `/practices/${practiceId}/full`, data, ) @@ -1167,15 +1167,15 @@ export const getQuestionSets = (params?: GetQuestionSetsParams) => http.get("/question-sets", { params }) export const getExamPrepAssessments = (parent: ExamPrepAssessmentParent) => - http.get("/exam-prep/assessments", { + http.get("/assessments", { params: { parent_kind: parent.kind, parent_id: parent.id }, }) export const linkExamPrepAssessment = (data: ExamPrepAssessmentLinkRequest) => - http.post("/exam-prep/assessments", data) + http.post("/assessments", data) export const unlinkExamPrepAssessment = (questionSetId: number, parent: ExamPrepAssessmentParent) => - http.delete(`/exam-prep/assessments/${questionSetId}/parents/${parent.kind}/${parent.id}`) + http.delete(`/assessments/${questionSetId}/parents/${parent.kind}/${parent.id}`) export const getQuestionSetsByOwner = (ownerType: string, ownerId: number) => http.get("/question-sets/by-owner", { diff --git a/src/api/learningHierarchy.api.ts b/src/api/learningHierarchy.api.ts new file mode 100644 index 0000000..3b7bf79 --- /dev/null +++ b/src/api/learningHierarchy.api.ts @@ -0,0 +1,69 @@ +import http from "./http" +import type { QuestionSetQuestion } from "../types/course.types" + +export type LearningKind = "course" | "chapter" | "lesson" | "quiz" +export type LearningItem = { + id: number + course_id?: number + chapter_id?: number + name?: string + title?: string + description?: string + thumbnail?: string + video_url?: string + publish_status: "DRAFT" | "PUBLISHED" + access_tier?: "FREE" | "PREMIUM" + question_set_id?: number +} + +export const learningCollections = { course: "courses", chapter: "chapters", lesson: "lessons", quiz: "quizzes" } as const + +type Envelope = { data: T; message: string; success: boolean; status_code: number } +type Page = { total_count: number; limit: number; offset: number } & Partial> + +export async function listLearningItems(path: string, key: typeof learningCollections[LearningKind]): Promise { + const result: LearningItem[] = [] + for (let offset = 0; ; offset += 200) { + const { data } = await http.get>(path, { params: { limit: 200, offset } }) + const page = data.data?.[key] + if (!Array.isArray(page)) throw new Error(`Invalid ${key} response`) + result.push(...page) + if (page.length < 200 || result.length >= data.data.total_count) return result + } +} + +export async function getLearningItem(kind: LearningKind, id: number): Promise { + const { data } = await http.get>(`/${learningCollections[kind]}/${id}`) + if (!data.data || data.data.id !== id) throw new Error(`Invalid ${kind} response`) + return data.data +} + +/** Admin question-set reads return a data array, unlike paginated learner quiz reads. */ +export async function getQuizQuestions(questionSetId: number): Promise { + const { data } = await http.get>(`/question-sets/${questionSetId}/questions`) + if (!Array.isArray(data.data)) throw new Error("Invalid quiz questions response") + return data.data +} + +/** Update quiz and question-set publication/title through one request. */ +export function updateChapterQuiz(id: number, changes: { title?: string; publish_status?: "DRAFT" | "PUBLISHED" }) { + return http.put(`/quizzes/${id}/full`, { + practice: changes, + question_set: { + ...(changes.title !== undefined ? { title: changes.title } : {}), + ...(changes.publish_status !== undefined ? { status: changes.publish_status } : {}), + }, + }) +} + +export async function createChapterQuiz(chapterId: number, title: string) { + const { data } = await http.post>("/question-sets", { title, set_type: "QUIZ", status: "DRAFT" }) + const setId = data.data?.id + if (!Number.isSafeInteger(setId) || setId <= 0) throw new Error("Invalid question set response") + try { + return await http.post(`/chapters/${chapterId}/quizzes`, { title, question_set_id: setId, publish_status: "DRAFT" }) + } catch (error) { + await http.delete(`/question-sets/${setId}`, { skipErrorToast: true }).catch(() => undefined) + throw error + } +} diff --git a/src/api/publicCatalog.api.ts b/src/api/publicCatalog.api.ts new file mode 100644 index 0000000..39f912d --- /dev/null +++ b/src/api/publicCatalog.api.ts @@ -0,0 +1,38 @@ +import { publicApiBase } from "../lib/publicApiBase" + +export type PublicCourse = { + id: number; name: string; description: string; thumbnail: string; access_tier: "FREE" | "PREMIUM" + chapter_count: number; lesson_count: number; quiz_count: number +} +export type PublicCourseOutline = PublicCourse & { chapters: { + id: number; name: string; description: string + lessons: { id: number; title: string; description: string; thumbnail: string; access_tier: "FREE" | "PREMIUM" }[] + quizzes: { id: number; title: string; question_count: number }[] +}[] } +export type PublicCatalogPage = { courses: PublicCourse[]; total_count: number; limit: number; offset: number } + +const base = publicApiBase(import.meta.env.VITE_API_BASE_URL ?? "/api/v1") + +// Use a separate anonymous client: staff tokens, refresh and login redirects do +// not belong in public discovery, even when a staff session exists in this tab. +async function read(path: string, signal?: AbortSignal): Promise { + const response = await fetch(`${base}${path}`, { signal, credentials: "omit" }) + if (!response.ok) throw new Error(response.status === 404 ? "This course is not available." : "Unable to load the course catalog. Please try again.") + const result = await response.json() + return result.data as T +} + +export function getPublicCourses(search: string, offset: number, signal?: AbortSignal) { + const params = new URLSearchParams({ q: search, limit: "12", offset: String(offset) }) + return read(`/catalog/courses?${params}`, signal) +} +export function getPublicCourse(id: number, signal?: AbortSignal) { + return read(`/catalog/courses/${id}`, signal) +} + +export function catalogThumbnail(value: string): string { + if (!value.startsWith("/static/")) return value + // Static uploads live on the API origin when the UI and API use different hosts. + if (/^https?:\/\//.test(base)) return `${new URL(base).origin}${value}` + return value +} diff --git a/src/api/users.api.ts b/src/api/users.api.ts index ef02b97..2933f7f 100644 --- a/src/api/users.api.ts +++ b/src/api/users.api.ts @@ -16,8 +16,7 @@ import type { LearningActivityAccess, LearningActivityCourse, LearningActivityLesson, - LearningActivityModule, - LearningActivityUnit, + LearningActivityChapter, UserLearningActivityData, UserLearningActivityResponse, UserSubscriptionPayment, @@ -127,119 +126,46 @@ function normalizeLearningActivityAccess(raw: unknown): LearningActivityAccess { function normalizeLearningActivityLesson(raw: unknown): LearningActivityLesson | null { if (!isRecord(raw)) return null; const id = Number(raw.id); - const moduleId = Number(raw.module_id); - if (!Number.isFinite(id) || !Number.isFinite(moduleId)) return null; - - return { - id, - module_id: moduleId, - title: String(raw.title ?? ""), - access: normalizeLearningActivityAccess(raw.access), - }; + const chapterId = Number(raw.chapter_id); + if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(chapterId) || chapterId <= 0) return null; + return { id, chapter_id: chapterId, title: String(raw.title ?? ""), access: normalizeLearningActivityAccess(raw.access) }; } -function normalizeLearningActivityModule(raw: unknown): LearningActivityModule | null { +function normalizeLearningActivityChapter(raw: unknown): LearningActivityChapter | null { if (!isRecord(raw)) return null; const id = Number(raw.id); - if (!Number.isFinite(id)) return null; - - const lessonsRaw = raw.lessons; - const lessons = Array.isArray(lessonsRaw) - ? lessonsRaw - .map((entry) => normalizeLearningActivityLesson(entry)) - .filter((entry): entry is LearningActivityLesson => entry !== null) + const courseId = Number(raw.course_id); + if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(courseId) || courseId <= 0) return null; + const lessons = Array.isArray(raw.lessons) + ? raw.lessons.map(normalizeLearningActivityLesson).filter((entry): entry is LearningActivityLesson => entry !== null) : []; - - const unitId = Number(raw.unit_id); - - return { - id, - unit_id: Number.isFinite(unitId) ? unitId : undefined, - name: String(raw.name ?? ""), - access: normalizeLearningActivityAccess(raw.access), - lessons, - }; -} - -function normalizeLearningActivityUnit(raw: unknown): LearningActivityUnit | null { - if (!isRecord(raw)) return null; - const id = Number(raw.id); - const catalogCourseId = Number(raw.catalog_course_id); - if (!Number.isFinite(id) || !Number.isFinite(catalogCourseId)) return null; - - const modulesRaw = raw.modules; - const modules = Array.isArray(modulesRaw) - ? modulesRaw - .map((entry) => normalizeLearningActivityModule(entry)) - .filter((entry): entry is LearningActivityModule => entry !== null) - : []; - - return { - id, - catalog_course_id: catalogCourseId, - name: String(raw.name ?? ""), - access: normalizeLearningActivityAccess(raw.access), - modules, - }; + return { id, course_id: courseId, name: String(raw.name ?? ""), access: normalizeLearningActivityAccess(raw.access), lessons }; } function normalizeLearningActivityCourse(raw: unknown): LearningActivityCourse | null { if (!isRecord(raw)) return null; const id = Number(raw.id); - if (!Number.isFinite(id)) return null; - - const modulesRaw = raw.modules; - const modules = Array.isArray(modulesRaw) - ? modulesRaw - .map((entry) => normalizeLearningActivityModule(entry)) - .filter((entry): entry is LearningActivityModule => entry !== null) - : undefined; - - const unitsRaw = raw.units; - const units = Array.isArray(unitsRaw) - ? unitsRaw - .map((entry) => normalizeLearningActivityUnit(entry)) - .filter((entry): entry is LearningActivityUnit => entry !== null) - : undefined; - - const catalogCourseId = Number(raw.catalog_course_id); - - return { - id, - catalog_course_id: Number.isFinite(catalogCourseId) ? catalogCourseId : undefined, - name: String(raw.name ?? ""), - access: normalizeLearningActivityAccess(raw.access), - modules, - units, - }; + if (!Number.isSafeInteger(id) || id <= 0) return null; + const chapters = Array.isArray(raw.chapters) + ? raw.chapters.map(normalizeLearningActivityChapter).filter((entry): entry is LearningActivityChapter => entry !== null) + : []; + return { id, name: String(raw.name ?? ""), access: normalizeLearningActivityAccess(raw.access), chapters }; } export function normalizeUserLearningActivity(raw: unknown): UserLearningActivityData | null { if (!isRecord(raw)) return null; const userId = Number(raw.user_id); - if (!Number.isFinite(userId)) return null; - - const examPrepRaw = isRecord(raw.exam_prep) ? raw.exam_prep : {}; - const examProgressRaw = isRecord(examPrepRaw.progress) ? examPrepRaw.progress : {}; - const catalogCoursesRaw = examProgressRaw.catalog_courses; - const catalogCourses = Array.isArray(catalogCoursesRaw) - ? catalogCoursesRaw - .map((entry) => normalizeLearningActivityCourse(entry)) - .filter((entry): entry is LearningActivityCourse => entry !== null) + if (!Number.isSafeInteger(userId) || userId <= 0 || !isRecord(raw.learning)) return null; + const progress = isRecord(raw.learning.progress) ? raw.learning.progress : {}; + const completions = isRecord(raw.learning.completions) ? raw.learning.completions : {}; + const courses = Array.isArray(progress.courses) + ? progress.courses.map(normalizeLearningActivityCourse).filter((entry): entry is LearningActivityCourse => entry !== null) : []; - - const examCompletionsRaw = isRecord(examPrepRaw.completions) ? examPrepRaw.completions : {}; - return { user_id: userId, - exam_prep: { - progress: { catalog_courses: catalogCourses }, - completions: { - user_id: Number(examCompletionsRaw.user_id) || userId, - catalog_courses: Array.isArray(examCompletionsRaw.catalog_courses) - ? examCompletionsRaw.catalog_courses - : [], - }, + learning: { + progress: { courses }, + completions: { user_id: Number(completions.user_id) || userId, courses: Array.isArray(completions.courses) ? completions.courses : [] }, }, recent_activity: normalizeUserRecentActivity(raw.recent_activity) ?? undefined, }; diff --git a/src/app/AppRoutes.tsx b/src/app/AppRoutes.tsx index 1687044..8d56ede 100644 --- a/src/app/AppRoutes.tsx +++ b/src/app/AppRoutes.tsx @@ -1,4 +1,7 @@ +import { PublicCatalogPage } from "../pages/catalog/PublicCatalogPage"; +import { getAccessToken } from "../lib/teamAuthStorage"; import { Navigate, Route, Routes } from "react-router-dom"; +import { LearningHierarchyPage } from "../pages/content-management/LearningHierarchyPage"; import { getDefaultAppHome } from "../lib/adminAccess"; import { getNormalizedSessionTeamRole } from "../lib/teamRole"; import { FullPanelGuard } from "../components/access/AdminAccessGates"; @@ -6,29 +9,9 @@ import { AppLayout } from "../layouts/AppLayout"; import { DashboardPage } from "../pages/DashboardPage"; import { AnalyticsPage } from "../pages/analytics/AnalyticsPage"; import { ContentManagementLayout } from "../pages/content-management/ContentManagementLayout"; -import { AllCoursesPage } from "../pages/content-management/AllCoursesPage"; -import { CourseFlowBuilderPage } from "../pages/content-management/CourseFlowBuilderPage"; -import { ContentOverviewPage } from "../pages/content-management/ContentOverviewPage"; -import { CoursesPage } from "../pages/content-management/CoursesPage"; import { PracticeQuestionsPage } from "../pages/content-management/PracticeQuestionsPage"; -import { AddNewPracticePage } from "../pages/content-management/AddNewPracticePage"; -import { SubModulesPage } from "../pages/content-management/SubCoursesPage"; -import { SubModuleContentPage } from "../pages/content-management/SubCourseContentPage"; -import { SpeakingPage } from "../pages/content-management/SpeakingPage"; -import { AddVideoPage } from "../pages/content-management/AddVideoPage"; -import { AddPracticePage } from "../pages/content-management/AddPracticePage"; -import { NewContentPage } from "../pages/content-management/NewContentPage"; -import { ReorderContentPage } from "../pages/content-management/ReorderContentPage"; -import { LessonPracticesPage } from "../pages/content-management/LessonPracticesPage"; -import { LessonAssessmentsPage } from "../pages/content-management/LessonAssessmentsPage"; import { AddPracticeFlow } from "../pages/content-management/AddPracticeFlow"; -import { LinkExistingPracticeFlow } from "../pages/content-management/LinkExistingPracticeFlow"; import { EditPracticeFlow } from "../pages/content-management/EditPracticeFlow"; -import { CourseModuleDetailPage } from "../pages/content-management/CourseModuleDetailPage"; -import { ProgramTypeSelectionPage } from "../pages/content-management/ProgramTypeSelectionPage"; -import { ProgramDetailPage } from "../pages/content-management/ProgramDetailPage"; -import { CourseManagementPage } from "../pages/content-management/CourseManagementPage"; -import { UnitManagementPage } from "../pages/content-management/UnitManagementPage"; import { QuestionTypeLibraryPage } from "../pages/content-management/QuestionTypeLibraryPage"; import { CreateQuestionTypeFlow } from "../pages/content-management/CreateQuestionTypeFlow"; import { NotFoundPage } from "../pages/NotFoundPage"; @@ -44,12 +27,8 @@ import { UserManagementLayout } from "../pages/user-management/UserManagementLay import { UsersListPage } from "../pages/user-management/UsersListPage"; import { UserGroupsPage } from "../pages/user-management/UserGroupsPage"; import { DeletionRequestsPage } from "../pages/user-management/DeletionRequestsPage"; -import { PracticeDetailsPage } from "../pages/content-management/PracticeDetailsPage"; -import { PracticeMembersPage } from "../pages/content-management/PracticeMembersPage"; import { QuestionsPage } from "../pages/content-management/QuestionsPage"; import { AddQuestionPage } from "../pages/content-management/AddQuestionPage"; -import { HumanLanguageHierarchyPage } from "../pages/content-management/HumanLanguageHierarchyPage"; -import { HumanLanguageSubModulePage } from "../pages/content-management/HumanLanguageSubModulePage"; import { UserLogPage } from "../pages/user-log/UserLogPage"; import { PaymentsPage } from "../pages/payments/PaymentsPage"; import { SubscriptionsExportPage } from "../pages/subscriptions/SubscriptionsExportPage"; @@ -73,6 +52,9 @@ import { PersonasPage } from "../pages/personas/PersonasPage"; export function AppRoutes() { return ( + : } /> + } /> + } /> } /> } /> } /> @@ -83,7 +65,6 @@ export function AppRoutes() { } /> } /> }> - } /> }> } /> @@ -100,188 +81,24 @@ export function AppRoutes() { }> - } /> - } /> - } /> - } /> - } - /> - } - /> - } - /> - } - /> - } - /> - {/* Course → Sub-module → Lesson/Practice */} - } - /> - } - /> - } - /> - } - /> - {/* Legacy aliases */} - } - /> - } - /> - } - /> - } - /> - } - /> - } /> - } /> - } /> - } /> + } /> + } /> } /> - } /> } /> } /> + } /> + } /> - - } /> - } /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> diff --git a/src/components/sidebar/Sidebar.tsx b/src/components/sidebar/Sidebar.tsx index 67af4ea..b4d9161 100644 --- a/src/components/sidebar/Sidebar.tsx +++ b/src/components/sidebar/Sidebar.tsx @@ -75,13 +75,12 @@ const navEntries: NavEntry[] = [ kind: "group", label: "Content", basePath: "/new-content", - activePaths: ["/new-content"], + activePaths: ["/new-content", "/content"], icon: BookOpen, children: [ - { label: "Learning content", to: "/new-content", end: true }, - { label: "Reorder structure", to: "/new-content/reorder" }, + { label: "Courses", to: "/new-content/courses" }, { label: "Question types", to: "/new-content/question-types" }, - { label: "Initial assessment", to: "/new-content/initial-assessment" }, + { label: "Question bank", to: "/content/questions" }, ], }, { diff --git a/src/lib/practiceParentTitles.ts b/src/lib/practiceParentTitles.ts index e7fa253..1eeb5bc 100644 --- a/src/lib/practiceParentTitles.ts +++ b/src/lib/practiceParentTitles.ts @@ -1,13 +1,4 @@ -import { - getExamPrepCatalogCourses, - getExamPrepCatalogUnits, - getExamPrepModuleLessons, - getExamPrepUnitModules, - getLearningPrograms, - getModuleLessons, - getProgramCourses, - getTopLevelCourseModules, -} from "../api/courses.api" +import http from "../api/http" import type { PracticeParent, PracticeParentKind } from "../types/course.types" import { dedupeParents, @@ -15,8 +6,6 @@ import { formatPracticeParentsSummary, } from "./practiceParents" -const LIST_LIMIT = 200 - export type PracticeParentTitleMap = Map export type PracticeParentTitleHints = { @@ -30,8 +19,8 @@ export function practiceParentKey(parent: PracticeParent): string { } function kindLabel(kind: PracticeParentKind): string { - if (kind === "CATALOG_COURSE") return "Catalog course" - if (kind === "UNIT") return "Unit" + if (kind === "CATALOG_COURSE") return "Course" + if (kind === "UNIT" || kind === "CHAPTER") return "Chapter" if (kind === "COURSE") return "Course" if (kind === "MODULE") return "Module" return "Lesson" @@ -73,206 +62,29 @@ function applyHints( } } -async function resolveLearnEnglishCourseTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const progRes = await getLearningPrograms({ limit: LIST_LIMIT, offset: 0 }) - const programs = progRes.data?.data?.programs ?? [] - for (const program of programs) { - if (ids.size === 0) break - const cRes = await getProgramCourses(program.id, { limit: LIST_LIMIT, offset: 0 }) - for (const course of cRes.data?.data?.courses ?? []) { - if (ids.has(course.id)) { - map.set(`COURSE:${course.id}`, course.name?.trim() || `Course #${course.id}`) - ids.delete(course.id) - } - } - } -} - -async function resolveExamPrepCourseTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const res = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 }) - for (const course of res.data?.data?.catalog_courses ?? []) { - if (ids.has(course.id)) { - const title = course.name?.trim() || `Course #${course.id}` - map.set(`CATALOG_COURSE:${course.id}`, title) - map.set(`COURSE:${course.id}`, title) - ids.delete(course.id) - } - } -} - -async function resolveExamPrepUnitTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 }) - for (const course of coursesRes.data?.data?.catalog_courses ?? []) { - if (ids.size === 0) break - const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 }) - for (const unit of unitsRes.data?.data?.units ?? []) { - if (ids.has(unit.id)) { - map.set(`UNIT:${unit.id}`, unit.name?.trim() || `Unit #${unit.id}`) - ids.delete(unit.id) - } - } - } -} - -async function resolveLearnEnglishModuleTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const progRes = await getLearningPrograms({ limit: LIST_LIMIT, offset: 0 }) - const programs = progRes.data?.data?.programs ?? [] - for (const program of programs) { - if (ids.size === 0) break - const cRes = await getProgramCourses(program.id, { limit: LIST_LIMIT, offset: 0 }) - const courses = cRes.data?.data?.courses ?? [] - const moduleBatches = await Promise.all( - courses.map((course) => - getTopLevelCourseModules(course.id, { limit: LIST_LIMIT, offset: 0 }), - ), - ) - for (let i = 0; i < courses.length; i++) { - for (const module of moduleBatches[i].data?.data?.modules ?? []) { - if (ids.has(module.id)) { - map.set(`MODULE:${module.id}`, module.name?.trim() || `Module #${module.id}`) - ids.delete(module.id) - } - } - if (ids.size === 0) break - } - } -} - -async function resolveExamPrepModuleTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 }) - const catalogCourses = coursesRes.data?.data?.catalog_courses ?? [] - for (const course of catalogCourses) { - if (ids.size === 0) break - const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 }) - const units = unitsRes.data?.data?.units ?? [] - for (const unit of units) { - const modulesRes = await getExamPrepUnitModules(unit.id, { limit: LIST_LIMIT, offset: 0 }) - for (const module of modulesRes.data?.data?.modules ?? []) { - if (ids.has(module.id)) { - map.set(`MODULE:${module.id}`, module.name?.trim() || `Module #${module.id}`) - ids.delete(module.id) - } - } - if (ids.size === 0) break - } - } -} - -async function resolveLearnEnglishLessonTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const progRes = await getLearningPrograms({ limit: LIST_LIMIT, offset: 0 }) - const programs = progRes.data?.data?.programs ?? [] - for (const program of programs) { - if (ids.size === 0) break - const cRes = await getProgramCourses(program.id, { limit: LIST_LIMIT, offset: 0 }) - const courses = cRes.data?.data?.courses ?? [] - for (const course of courses) { - if (ids.size === 0) break - const mRes = await getTopLevelCourseModules(course.id, { limit: LIST_LIMIT, offset: 0 }) - const modules = mRes.data?.data?.modules ?? [] - const lessonBatches = await Promise.all( - modules.map((module) => - getModuleLessons(module.id, { limit: LIST_LIMIT, offset: 0 }), - ), - ) - for (let i = 0; i < modules.length; i++) { - for (const lesson of lessonBatches[i].data?.data?.lessons ?? []) { - if (ids.has(lesson.id)) { - map.set(`LESSON:${lesson.id}`, lesson.title?.trim() || `Lesson #${lesson.id}`) - ids.delete(lesson.id) - } - } - if (ids.size === 0) break - } - } - } -} - -async function resolveExamPrepLessonTitles( - ids: Set, - map: PracticeParentTitleMap, -): Promise { - if (ids.size === 0) return - const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 }) - const catalogCourses = coursesRes.data?.data?.catalog_courses ?? [] - for (const course of catalogCourses) { - if (ids.size === 0) break - const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 }) - const units = unitsRes.data?.data?.units ?? [] - for (const unit of units) { - if (ids.size === 0) break - const modulesRes = await getExamPrepUnitModules(unit.id, { limit: LIST_LIMIT, offset: 0 }) - const modules = modulesRes.data?.data?.modules ?? [] - for (const module of modules) { - if (ids.size === 0) break - const lessonsRes = await getExamPrepModuleLessons(module.id, { - limit: LIST_LIMIT, - offset: 0, - }) - for (const lesson of lessonsRes.data?.data?.lessons ?? []) { - if (ids.has(lesson.id)) { - map.set(`LESSON:${lesson.id}`, lesson.title?.trim() || `Lesson #${lesson.id}`) - ids.delete(lesson.id) - } - } - } - } - } -} - +/** Resolve only the requested IDs against the canonical hierarchy. */ export async function resolvePracticeParentTitles( parents: PracticeParent[], hints?: PracticeParentTitleHints, ): Promise { const map: PracticeParentTitleMap = new Map() applyHints(map, hints) - - const normalized = dedupeParents(parents) - const unresolvedCourses = new Set() - const unresolvedCatalogCourses = new Set() - const unresolvedUnits = new Set() - const unresolvedModules = new Set() - const unresolvedLessons = new Set() - - for (const parent of normalized) { - if (map.has(practiceParentKey(parent))) continue - if (parent.parent_kind === "COURSE") unresolvedCourses.add(parent.parent_id) - if (parent.parent_kind === "CATALOG_COURSE") unresolvedCatalogCourses.add(parent.parent_id) - if (parent.parent_kind === "UNIT") unresolvedUnits.add(parent.parent_id) - if (parent.parent_kind === "MODULE") unresolvedModules.add(parent.parent_id) - if (parent.parent_kind === "LESSON") unresolvedLessons.add(parent.parent_id) - } - - await resolveLearnEnglishCourseTitles(unresolvedCourses, map) - await resolveExamPrepCourseTitles(unresolvedCatalogCourses, map) - await resolveExamPrepUnitTitles(unresolvedUnits, map) - await resolveLearnEnglishModuleTitles(unresolvedModules, map) - await resolveExamPrepModuleTitles(unresolvedModules, map) - await resolveLearnEnglishLessonTitles(unresolvedLessons, map) - await resolveExamPrepLessonTitles(unresolvedLessons, map) - + await Promise.all(dedupeParents(parents).map(async parent => { + const key = practiceParentKey(parent) + if (map.has(key)) return + const collection = parent.parent_kind === "COURSE" || parent.parent_kind === "CATALOG_COURSE" + ? "courses" + : parent.parent_kind === "CHAPTER" || parent.parent_kind === "UNIT" + ? "chapters" + : parent.parent_kind === "LESSON" ? "lessons" : null + if (!collection) return + try { + const { data } = await http.get(`/${collection}/${parent.parent_id}`, { skipErrorToast: true }) + const title = data.data?.name ?? data.data?.title + if (typeof title === "string" && title.trim()) map.set(key, title.trim()) + } catch { + // A deleted or inaccessible parent retains its ID label. + } + })) return map } diff --git a/src/lib/practiceParents.ts b/src/lib/practiceParents.ts index bda4667..fe6039f 100644 --- a/src/lib/practiceParents.ts +++ b/src/lib/practiceParents.ts @@ -1,6 +1,7 @@ import type { PracticeParent, PracticeParentKind } from "../types/course.types" const PARENT_KINDS: PracticeParentKind[] = [ + "CHAPTER", "COURSE", "MODULE", "LESSON", @@ -74,7 +75,7 @@ export function validatePracticeParents( const required = options?.required !== false const normalized = dedupeParents(parents) if (normalized.length === 0) { - return required ? "Select at least one course, module, or lesson." : null + return required ? "Select at least one course, chapter, or lesson." : null } for (let i = 0; i < parents.length; i++) { const row = parents[i] @@ -97,9 +98,10 @@ export function validatePracticeParents( export function formatPracticeParentLabel(parent: PracticeParent): string { switch (parent.parent_kind) { case "CATALOG_COURSE": - return `Catalog course #${parent.parent_id}` + return `Course #${parent.parent_id}` case "UNIT": - return `Unit #${parent.parent_id}` + case "CHAPTER": + return `Chapter #${parent.parent_id}` case "COURSE": return `Course #${parent.parent_id}` case "MODULE": @@ -118,8 +120,8 @@ export function formatPracticeParentsSummary( const list = dedupeParents(parents) if (list.length === 0) { return options?.isExamPrep - ? "Not attached to any catalog course, unit, or lesson" - : "Not attached to any course, module, or lesson" + ? "Not attached to any course, chapter, or lesson" + : "Not attached to any course, chapter, or lesson" } return list.map(formatPracticeParentLabel).join(" · ") } diff --git a/src/lib/publicApiBase.ts b/src/lib/publicApiBase.ts new file mode 100644 index 0000000..6fd0bc1 --- /dev/null +++ b/src/lib/publicApiBase.ts @@ -0,0 +1,4 @@ +/** Public discovery must never inherit the staff /admin scope. */ +export function publicApiBase(value: string): string { + return value.replace(/\/+$/, "").replace(/\/admin$/, "") +} diff --git a/src/pages/auth/LoginPage.tsx b/src/pages/auth/LoginPage.tsx index b727870..4b07215 100644 --- a/src/pages/auth/LoginPage.tsx +++ b/src/pages/auth/LoginPage.tsx @@ -234,6 +234,7 @@ export function LoginPage() { return (
+ Explore courses without signing in {/* Decorative left panel */}
{/* Abstract decorative shapes */} diff --git a/src/pages/catalog/PublicCatalogPage.tsx b/src/pages/catalog/PublicCatalogPage.tsx new file mode 100644 index 0000000..0a5fb5f --- /dev/null +++ b/src/pages/catalog/PublicCatalogPage.tsx @@ -0,0 +1,85 @@ +import { useEffect, useState } from "react" +import { Link, useParams, useSearchParams } from "react-router-dom" +import { ArrowLeft, ArrowRight, BookOpen, CheckCircle2, LockKeyhole, Search } from "lucide-react" +import { BrandLogo } from "../../components/brand/BrandLogo" +import { catalogThumbnail, getPublicCourse, getPublicCourses, type PublicCatalogPage as Catalog, type PublicCourseOutline } from "../../api/publicCatalog.api" + +const learnerApp = import.meta.env.VITE_LEARNER_APP_URL as string | undefined + +export function PublicCatalogPage() { + const { courseId } = useParams<{ courseId: string }>() + const [params, setParams] = useSearchParams() + const search = params.get("q") ?? "" + const offset = Math.max(0, Number(params.get("offset")) || 0) + const [draftSearch, setDraftSearch] = useState(search) + const [catalog, setCatalog] = useState(null) + const [course, setCourse] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState("") + const [retry, setRetry] = useState(0) + + useEffect(() => { + const controller = new AbortController() + async function load() { + setLoading(true); setError(""); setCourse(null) + try { + if (courseId) { + const id = Number(courseId) + if (!Number.isSafeInteger(id) || id < 1) throw new Error("This course is not available.") + const outline = await getPublicCourse(id, controller.signal) + if (!controller.signal.aborted) setCourse(outline) + } else { + const page = await getPublicCourses(search, offset, controller.signal) + if (!controller.signal.aborted) setCatalog(page) + } + } catch (problem) { + if (!controller.signal.aborted) setError(problem instanceof Error ? problem.message : "Unable to load courses.") + } finally { if (!controller.signal.aborted) setLoading(false) } + } + void load() + return () => controller.abort() + }, [courseId, search, offset, retry]) + + return
+
+ + +
+
+ {courseId ? All courses :
+

Your next chapter starts here

+

Build skills.
Open new possibilities.

+

Explore our courses, discover what you will learn, and find the right place to begin. Browse every published course without an account.

+
{ event.preventDefault(); setParams(draftSearch.trim() ? { q: draftSearch.trim() } : {}) }} className="mt-7 flex max-w-xl gap-2 rounded-xl border border-[#163d35]/15 bg-white p-2"> + + +
+
} + {loading ?

Loading courses...

: error ?

{error}

: course ? <> +
+

{course.access_tier === "PREMIUM" ? "Premium course" : "Free course"}

{course.name}

{course.description}

+

{course.chapter_count} chapters · {course.lesson_count} lessons · {course.quiz_count} quizzes

+ {learnerApp ? Sign in to learn :

Sign in through your learning app to watch lessons and take quizzes.

} +
{course.thumbnail ? : }
+
+

What you will learn

+ {course.chapters.map((chapter, index) =>
+ {index + 1}. {chapter.name}{chapter.lessons.length} lessons +

{chapter.description}

+
    {chapter.lessons.map(lesson =>
  • {lesson.title}

    {lesson.description}

    {lesson.access_tier === "PREMIUM" ? "Premium lesson" : "Free lesson"}
  • )} + {chapter.quizzes.map(quiz =>
  • {quiz.title}

    Chapter quiz · {quiz.question_count} questions

  • )}
+
)} + {!course.chapters.length &&

The course outline will be available soon.

} +
+ :
+

{search ? `Results for “${search}”` : "Explore our courses"}

{catalog?.total_count ?? 0} courses
+
{catalog?.courses.map(item => +
{item.thumbnail ? : }
+
{item.access_tier === "PREMIUM" ? "Premium" : "Free"}

{item.name}

{item.description}

{item.chapter_count} chapters · {item.lesson_count} lessons · {item.quiz_count} quizzes

View course
+ )}
+ {!catalog?.courses.length &&

{search ? "No courses match your search. Try another topic." : "New courses are on their way. Check back soon."}

} + {!!catalog?.total_count && } +
} +
Rezina · Learn at your own pace.
+
+} diff --git a/src/pages/content-management/ContentManagementLayout.tsx b/src/pages/content-management/ContentManagementLayout.tsx index 33707f7..2640218 100644 --- a/src/pages/content-management/ContentManagementLayout.tsx +++ b/src/pages/content-management/ContentManagementLayout.tsx @@ -11,7 +11,7 @@ export function ContentManagementLayout() { Content Management

- View and manage practice content for courses, modules, and lessons + Manage courses, chapters, lessons, and chapter quizzes

diff --git a/src/pages/content-management/LearningHierarchyPage.tsx b/src/pages/content-management/LearningHierarchyPage.tsx new file mode 100644 index 0000000..cc77622 --- /dev/null +++ b/src/pages/content-management/LearningHierarchyPage.tsx @@ -0,0 +1,149 @@ +import { useCallback, useEffect, useRef, useState } from "react" +import { Link, useParams } from "react-router-dom" +import { ArrowDown, ArrowLeft, ArrowUp, BookOpen, Pencil, Plus, Trash2 } from "lucide-react" +import { toast } from "sonner" +import http from "../../api/http" +import { Button } from "../../components/ui/button" +import { Input } from "../../components/ui/input" +import { Textarea } from "../../components/ui/textarea" +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../components/ui/dialog" +import { notifyApiError } from "../../lib/apiErrors" + +import { + createChapterQuiz, getLearningItem, listLearningItems as allItems, + learningCollections as collection, updateChapterQuiz, + type LearningItem as Item, type LearningKind as Kind, +} from "../../api/learningHierarchy.api" + +type Editor = { kind: Kind; item?: Item } + +export function LearningHierarchyPage() { + const { courseId, chapterId } = useParams<{ courseId: string; chapterId: string }>() + const kind: Kind = chapterId ? "lesson" : courseId ? "chapter" : "course" + const path = chapterId ? `/chapters/${chapterId}/lessons` : courseId ? `/courses/${courseId}/chapters` : "/courses" + const activePath = useRef(path) + const requestVersion = useRef(0) + useEffect(() => { activePath.current = path; return () => { requestVersion.current += 1 } }, [path]) + const [items, setItems] = useState([]) + const [quizzes, setQuizzes] = useState([]) + const [course, setCourse] = useState(null) + const [chapter, setChapter] = useState(null) + const [loading, setLoading] = useState(true) + const [failed, setFailed] = useState(false) + const [busy, setBusy] = useState(false) + const [search, setSearch] = useState("") + const [editor, setEditor] = useState(null) + const [deleting, setDeleting] = useState<{ item: Item; kind: Kind } | null>(null) + const [form, setForm] = useState({ name: "", description: "", thumbnail: "", video_url: "", access_tier: "FREE" }) + + const load = useCallback(async () => { + if (activePath.current !== path) return + const version = ++requestVersion.current + setLoading(true); setFailed(false) + try { + const [rows, quizRows, courseRes, chapterRes] = await Promise.all([ + allItems(path, collection[kind]), + chapterId ? allItems(`/chapters/${chapterId}/quizzes`, "quizzes") : Promise.resolve([]), + courseId ? getLearningItem("course", Number(courseId)) : Promise.resolve(null), + chapterId ? getLearningItem("chapter", Number(chapterId)) : Promise.resolve(null), + ]) + if (version !== requestVersion.current || activePath.current !== path) return + if (chapterRes && chapterRes.course_id !== Number(courseId)) { + throw new Error("This chapter does not belong to the selected course") + } + setItems(rows); setQuizzes(quizRows); setCourse(courseRes); setChapter(chapterRes) + } catch (error) { if (version === requestVersion.current && activePath.current === path) { setFailed(true); notifyApiError(error, "Unable to load learning content") } } + finally { if (version === requestVersion.current && activePath.current === path) setLoading(false) } + }, [path, kind, courseId, chapterId]) + useEffect(() => { setSearch(""); void load() }, [load]) + + function openEditor(next: Editor) { + setEditor(next) + const item = next.item + setForm({ name: item?.name ?? item?.title ?? "", description: item?.description ?? "", thumbnail: item?.thumbnail ?? "", video_url: item?.video_url ?? "", access_tier: item?.access_tier ?? "FREE" }) + } + async function save(event: React.FormEvent) { + event.preventDefault() + if (!editor || busy || !form.name.trim()) return + setBusy(true) + try { + const payload = { ...form, name: form.name.trim() } + if (editor.kind === "quiz") { + if (editor.item) { + await updateChapterQuiz(editor.item.id, { title: form.name.trim() }) + } else { + await createChapterQuiz(Number(chapterId), form.name.trim()) + } + } else { + const body = editor.kind === "lesson" ? { title: payload.name, description: payload.description, thumbnail: payload.thumbnail, video_url: payload.video_url, access_tier: payload.access_tier } : payload + if (editor.item) await http.put(`/${collection[editor.kind]}/${editor.item.id}`, body) + else await http.post(path, { ...body, publish_status: "DRAFT" }) + } + setEditor(null); toast.success(`${editor.kind} saved`); await load() + } catch (error) { notifyApiError(error, "Unable to save content") } + finally { setBusy(false) } + } + async function publish(item: Item, itemKind: Kind) { + setBusy(true) + try { + const status = item.publish_status === "PUBLISHED" ? "DRAFT" : "PUBLISHED" + if (itemKind === "quiz") await updateChapterQuiz(item.id, { publish_status: status }) + else await http.put(`/${collection[itemKind]}/${item.id}`, { publish_status: status }) + await load() + } catch (error) { notifyApiError(error, "Unable to change publication status") } + finally { setBusy(false) } + } + async function remove() { + if (!deleting) return + setBusy(true) + try { await http.delete(`/${collection[deleting.kind]}/${deleting.item.id}`); setDeleting(null); await load() } + catch (error) { notifyApiError(error, "Unable to delete content") } + finally { setBusy(false) } + } + async function move(index: number, direction: number) { + const ordered = [...items]; const target = index + direction + if (target < 0 || target >= ordered.length) return + ;[ordered[index], ordered[target]] = [ordered[target], ordered[index]] + setBusy(true) + try { await http.put(`${path}/reorder`, { ordered_ids: ordered.map(item => item.id) }); setItems(ordered) } + catch (error) { notifyApiError(error, "Unable to reorder content") } + finally { setBusy(false) } + } + const title = chapter?.name ?? course?.name ?? "Courses" + const matches = (item: Item) => (item.name ?? item.title ?? "").toLowerCase().includes(search.toLowerCase()) + function card(item: Item, itemKind: Kind, index?: number) { + return
+
+

{item.name ?? item.title}

{item.publish_status === "PUBLISHED" ? "Published" : "Draft"}{item.access_tier ? ` · ${item.access_tier.toLowerCase()}` : ""}

+
+ {index !== undefined && !search && <>} + + +
+
+ {item.description &&

{item.description}

} + {item.video_url && View lesson video} +
+ {itemKind === "course" && } + {itemKind === "chapter" && } + {itemKind === "quiz" && } + +
+
+ } + return
+ +

{title}

{chapterId ? "Manage the lessons and quizzes in this chapter." : courseId ? "Organize this course into chapters." : "Create courses, organize chapters, and add lessons and chapter quizzes."}

+ {courseId && } + setSearch(event.target.value)} /> + {loading ?

Loading content…

: failed ?

Content could not be loaded.

: <> +

{collection[kind]}

{items.map((item, index) => matches(item) ? card(item, kind, index) : null)}
{!items.some(matches) &&

{search ? "No matching content." : `No ${collection[kind]} yet. Add your first ${kind} to get started.`}

}
+ {chapterId &&

Chapter quizzes

{quizzes.filter(matches).map(item => card(item, "quiz"))}
{!quizzes.some(matches) &&

{search ? "No matching quizzes." : "No quizzes yet. Create a quiz, add its questions, then publish it."}

}
} + } + { if (!open && !busy) setEditor(null) }}>{editor?.item ? "Edit" : "Add"} {editor?.kind}
+ {editor?.kind !== "quiz" && <>