From 2b880f0386fdd226f675c1651c095a6c08bc6f0a Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Thu, 6 Aug 2026 13:59:32 +0300 Subject: [PATCH] Improve admin content search, role filters, and profile demographics display. Harden list/search paths that white-screened, tighten role management to team vs user roles, and show profile analytics/labels with field defaults instead of Other. Co-authored-by: Cursor --- src/api/rbac.api.ts | 8 +- src/app/AppRoutes.tsx | 5 - src/lib/apiErrors.ts | 13 +- src/lib/contentListFilters.ts | 5 +- src/lib/displayValue.tsx | 14 +- src/lib/examPrepPracticeEditPath.ts | 6 +- src/lib/learnEnglishPracticeEditPath.ts | 6 +- .../questionTypeDefinitionPracticeEditPath.ts | 27 +- src/lib/rbacRoleCategories.ts | 37 ++ src/lib/userProfileFieldDisplay.ts | 386 ++++++++++++++++++ src/pages/analytics/AnalyticsPage.tsx | 52 ++- .../content-management/AllCoursesPage.tsx | 7 +- .../ContentOverviewPage.tsx | 5 +- .../content-management/CourseCategoryPage.tsx | 3 +- .../content-management/CourseDetailPage.tsx | 13 +- .../CourseManagementPage.tsx | 14 +- .../CourseModuleDetailPage.tsx | 13 +- src/pages/content-management/CoursesPage.tsx | 13 +- .../content-management/EditPracticeFlow.tsx | 22 +- .../content-management/LearnEnglishPage.tsx | 9 +- .../LessonPracticesPage.tsx | 1 + .../content-management/ModuleDetailPage.tsx | 2 + .../content-management/NewContentPage.tsx | 28 +- .../content-management/ProgramCoursesPage.tsx | 7 +- .../content-management/ProgramDetailPage.tsx | 19 +- .../ProgramTypeSelectionPage.tsx | 34 +- .../QuestionTypeLibraryPage.tsx | 319 +-------------- .../content-management/QuestionsPage.tsx | 3 +- src/pages/content-management/SpeakingPage.tsx | 14 +- .../content-management/UnitManagementPage.tsx | 14 +- .../CatalogCoursePracticesPanel.tsx | 1 + .../components/ModulePracticeCard.tsx | 5 +- .../components/QuestionTypeCard.tsx | 11 +- .../components/UnitPracticesPanel.tsx | 1 + .../components/VideoCard.tsx | 12 +- .../SelectPracticeToAttachStep.tsx | 12 +- .../QuestionTypeBasicInfoStep.tsx | 12 - .../QuestionTypeReviewPublishStep.tsx | 23 +- src/pages/faqs/FaqsPage.tsx | 3 +- src/pages/notifications/NotificationsPage.tsx | 23 +- src/pages/payments/PaymentsPage.tsx | 29 +- src/pages/personas/PersonasPage.tsx | 7 +- src/pages/role-management/RolesListPage.tsx | 98 +++-- src/pages/team/TeamManagementPage.tsx | 10 +- .../components/ActivityLogListPanel.tsx | 4 +- .../user-management/DeletionRequestsPage.tsx | 18 +- src/pages/user-management/UserDetailPage.tsx | 55 +-- src/pages/user-management/UsersListPage.tsx | 51 +-- 48 files changed, 875 insertions(+), 599 deletions(-) create mode 100644 src/lib/rbacRoleCategories.ts create mode 100644 src/lib/userProfileFieldDisplay.ts diff --git a/src/api/rbac.api.ts b/src/api/rbac.api.ts index c0e1f55..300e09e 100644 --- a/src/api/rbac.api.ts +++ b/src/api/rbac.api.ts @@ -17,9 +17,11 @@ export const getRoles = (params?: GetRolesParams) => http.get("/rbac/roles", { params }) /** Fetch every RBAC role across paginated list responses. */ -export async function fetchAllRoles(): Promise { +export async function fetchAllRoles( + params?: Pick, +): Promise { const pageSize = 50 - const firstRes = await getRoles({ page: 1, page_size: pageSize }) + const firstRes = await getRoles({ page: 1, page_size: pageSize, ...params }) const firstBatch = firstRes.data?.data?.roles ?? [] const total = firstRes.data?.data?.total ?? firstBatch.length const totalPages = Math.max(1, Math.ceil(total / pageSize)) @@ -28,7 +30,7 @@ export async function fetchAllRoles(): Promise { const remaining = await Promise.all( Array.from({ length: totalPages - 1 }, (_, idx) => - getRoles({ page: idx + 2, page_size: pageSize }), + getRoles({ page: idx + 2, page_size: pageSize, ...params }), ), ) return [...firstBatch, ...remaining.flatMap((res) => res.data?.data?.roles ?? [])] diff --git a/src/app/AppRoutes.tsx b/src/app/AppRoutes.tsx index d8b9b6f..8f7603f 100644 --- a/src/app/AppRoutes.tsx +++ b/src/app/AppRoutes.tsx @@ -35,7 +35,6 @@ import { CourseManagementPage } from "../pages/content-management/CourseManageme import { UnitManagementPage } from "../pages/content-management/UnitManagementPage"; import { InitialAssessmentPage } from "../pages/content-management/InitialAssessmentPage"; import { QuestionTypeLibraryPage } from "../pages/content-management/QuestionTypeLibraryPage"; -import { QuestionTypeGroupDetailPage } from "../pages/content-management/QuestionTypeGroupDetailPage"; import { CreateQuestionTypeFlow } from "../pages/content-management/CreateQuestionTypeFlow"; import { NotFoundPage } from "../pages/NotFoundPage"; import { NotificationsPage } from "../pages/notifications/NotificationsPage"; @@ -198,10 +197,6 @@ export function AppRoutes() { path="/new-content/initial-assessment" element={} /> - } - /> } diff --git a/src/lib/apiErrors.ts b/src/lib/apiErrors.ts index 9193050..7aa0dd3 100644 --- a/src/lib/apiErrors.ts +++ b/src/lib/apiErrors.ts @@ -7,12 +7,15 @@ export function readApiResponseMessage(data: unknown): string { if (typeof data === "string") return data.trim() if (data && typeof data === "object") { const record = data as Record - if (typeof record.message === "string" && record.message.trim()) { - return record.message.trim() - } - if (typeof record.error === "string" && record.error.trim()) { - return record.error.trim() + const message = + typeof record.message === "string" ? record.message.trim() : "" + const detail = + typeof record.error === "string" ? record.error.trim() : "" + if (message && detail && detail !== message) { + return `${message}: ${detail}` } + if (message) return message + if (detail) return detail } return "" } diff --git a/src/lib/contentListFilters.ts b/src/lib/contentListFilters.ts index 848b23a..48a9320 100644 --- a/src/lib/contentListFilters.ts +++ b/src/lib/contentListFilters.ts @@ -9,7 +9,10 @@ export function textMatchesSearch( ): boolean { const needle = query.trim().toLowerCase() if (!needle) return true - return fields.some((field) => (field ?? "").toLowerCase().includes(needle)) + return fields.some((field) => { + if (typeof field !== "string") return false + return field.toLowerCase().includes(needle) + }) } export function matchesPublishStatusFilter( diff --git a/src/lib/displayValue.tsx b/src/lib/displayValue.tsx index 2b4b959..5d5f01f 100644 --- a/src/lib/displayValue.tsx +++ b/src/lib/displayValue.tsx @@ -1,4 +1,5 @@ import type { ReactNode } from "react" +import { SearchHighlight } from "../components/SearchHighlight" import { cn } from "./utils" export const UNASSIGNED_LABEL = "unassigned" @@ -32,19 +33,30 @@ export function DisplayValue({ value, className, unassignedClassName, + query = "", }: { value: string | number | null | undefined className?: string unassignedClassName?: string + /** When set, matching search keywords are highlighted. */ + query?: string }): ReactNode { if (typeof value === "number") { if (!Number.isFinite(value)) { return } + const asText = String(value) + if (query.trim()) { + return + } return {value} } if (isUnassignedLabel(value)) { return } - return {value!.trim()} + const text = value!.trim() + if (query.trim()) { + return + } + return {text} } diff --git a/src/lib/examPrepPracticeEditPath.ts b/src/lib/examPrepPracticeEditPath.ts index 2fe8dce..f6230a4 100644 --- a/src/lib/examPrepPracticeEditPath.ts +++ b/src/lib/examPrepPracticeEditPath.ts @@ -56,7 +56,7 @@ function parentTabFromKind(kind?: string): ExamPrepParentTab | null { } function buildCatalogCourseEditPath(catalogCourseId: number, practiceId: number): string { - return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/edit-practice/${practiceId}?backTo=courses` + return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/edit-practice/${practiceId}?kind=EXAM_PREP&backTo=courses` } function buildUnitEditPath( @@ -64,7 +64,7 @@ function buildUnitEditPath( unitId: number, practiceId: number, ): string { - return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/${unitId}/edit-practice/${practiceId}?backTo=unit` + return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/${unitId}/edit-practice/${practiceId}?kind=EXAM_PREP&backTo=unit` } function buildLessonEditPath( @@ -76,7 +76,7 @@ function buildLessonEditPath( lessonTitle?: string, ): string { const titleQuery = lessonTitle ? `lessonTitle=${encodeURIComponent(lessonTitle)}&` : "" - return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/${unitId}/${moduleId}/lessons/${lessonId}/edit-practice/${practiceId}?${titleQuery}backTo=lesson` + return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/${unitId}/${moduleId}/lessons/${lessonId}/edit-practice/${practiceId}?${titleQuery}kind=EXAM_PREP&backTo=lesson` } async function fetchAllCatalogCourses(): Promise { diff --git a/src/lib/learnEnglishPracticeEditPath.ts b/src/lib/learnEnglishPracticeEditPath.ts index 725f57e..2e22349 100644 --- a/src/lib/learnEnglishPracticeEditPath.ts +++ b/src/lib/learnEnglishPracticeEditPath.ts @@ -172,7 +172,7 @@ async function detectParentTab( } function buildCourseEditPath(programId: number, courseId: number, practiceId: number): string { - return `/new-content/learn-english/${programId}/courses/${courseId}/edit-practice/${practiceId}?backTo=courses` + return `/new-content/learn-english/${programId}/courses/${courseId}/edit-practice/${practiceId}?kind=LMS&backTo=courses` } function buildModuleEditPath( @@ -181,7 +181,7 @@ function buildModuleEditPath( moduleId: number, practiceId: number, ): string { - return `/new-content/learn-english/${programId}/courses/${courseId}/modules/${moduleId}/edit-practice/${practiceId}?backTo=module` + return `/new-content/learn-english/${programId}/courses/${courseId}/modules/${moduleId}/edit-practice/${practiceId}?kind=LMS&backTo=module` } function buildLessonEditPath( @@ -193,7 +193,7 @@ function buildLessonEditPath( lessonTitle?: string, ): string { const titleQuery = lessonTitle ? `lessonTitle=${encodeURIComponent(lessonTitle)}&` : "" - return `/new-content/learn-english/${programId}/courses/${courseId}/modules/${moduleId}/lessons/${lessonId}/edit-practice/${practiceId}?${titleQuery}backTo=lesson` + return `/new-content/learn-english/${programId}/courses/${courseId}/modules/${moduleId}/lessons/${lessonId}/edit-practice/${practiceId}?${titleQuery}kind=LMS&backTo=lesson` } async function resolveFromDirectNavFields( diff --git a/src/lib/questionTypeDefinitionPracticeEditPath.ts b/src/lib/questionTypeDefinitionPracticeEditPath.ts index d811f3f..cfdfac2 100644 --- a/src/lib/questionTypeDefinitionPracticeEditPath.ts +++ b/src/lib/questionTypeDefinitionPracticeEditPath.ts @@ -1,13 +1,26 @@ -import { resolveExamPrepPracticeEditPath } from "./examPrepPracticeEditPath" -import { resolveLearnEnglishPracticeEditPath } from "./learnEnglishPracticeEditPath" import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types" -/** Routes to the LMS or exam-prep practice editor based on `practice_kind`. */ +function practiceKindQuery( + practice: QuestionTypeDefinitionPractice, +): "EXAM_PREP" | "LMS" { + return (practice.practice_kind || "LMS").toUpperCase() === "EXAM_PREP" + ? "EXAM_PREP" + : "LMS" +} + +/** + * Edit path for a practice opened from the question-type definition list. + * + * Always uses the standalone editor with an explicit `kind` so LMS vs exam-prep + * full-fetch APIs are selected correctly. Hierarchy route resolution is + * intentionally skipped here — it can land on a lesson URL while still calling + * the wrong `/practices/:id/full` vs `/exam-prep/practices/:id/full` endpoint. + */ export async function resolveQuestionTypeDefinitionPracticeEditPath( practice: QuestionTypeDefinitionPractice, ): Promise { - if ((practice.practice_kind || "LMS").toUpperCase() === "EXAM_PREP") { - return resolveExamPrepPracticeEditPath(practice) - } - return resolveLearnEnglishPracticeEditPath(practice) + const id = Number(practice.practice_id) + if (!Number.isFinite(id) || id < 1) return null + const kind = practiceKindQuery(practice) + return `/new-content/practices/${id}/edit?kind=${kind}&backTo=question-types` } diff --git a/src/lib/rbacRoleCategories.ts b/src/lib/rbacRoleCategories.ts new file mode 100644 index 0000000..1472907 --- /dev/null +++ b/src/lib/rbacRoleCategories.ts @@ -0,0 +1,37 @@ +import { STAFF_TEAM_ROLE_OPTIONS } from "./teamRoles" + +/** System roles hidden from Role Management (retained in RBAC for legacy assignments). */ +const ROLES_HIDDEN_FROM_MANAGEMENT = new Set(["INSTRUCTOR", "SUPPORT"]) + +const USER_RBAC_ROLE_NAMES = new Set(["STUDENT", "OPEN_LEARNER"]) + +const TEAM_RBAC_ROLE_NAMES = new Set( + STAFF_TEAM_ROLE_OPTIONS.map((o) => o.value.toUpperCase()), +) + +export type RoleManagementCategory = "team" | "user" + +export function normalizeRbacRoleName(name: string): string { + return name.trim().toUpperCase().replace(/[\s-]+/g, "_") +} + +export function isRoleHiddenFromManagement(name: string): boolean { + return ROLES_HIDDEN_FROM_MANAGEMENT.has(normalizeRbacRoleName(name)) +} + +export function isTeamMemberRbacRole(name: string): boolean { + return TEAM_RBAC_ROLE_NAMES.has(normalizeRbacRoleName(name)) +} + +export function isUserRbacRole(name: string): boolean { + return USER_RBAC_ROLE_NAMES.has(normalizeRbacRoleName(name)) +} + +export function matchesRoleManagementCategory( + name: string, + category: RoleManagementCategory, +): boolean { + if (isRoleHiddenFromManagement(name)) return false + if (category === "team") return isTeamMemberRbacRole(name) + return isUserRbacRole(name) +} diff --git a/src/lib/userProfileFieldDisplay.ts b/src/lib/userProfileFieldDisplay.ts new file mode 100644 index 0000000..9e0ac92 --- /dev/null +++ b/src/lib/userProfileFieldDisplay.ts @@ -0,0 +1,386 @@ +/** + * Profile field options seeded in backend `field_options` (migration 000069). + * Admin UI shows labels; empty / OTHER / unknown / out-of-list values fall back to defaults. + */ + +export const DEFAULT_USER_AGE_GROUP_CODE = "25_34" +export const DEFAULT_USER_OCCUPATION_CODE = "STUDENTS" +export const DEFAULT_USER_REGION_CODE = "ADDIS_ABABA" +export const DEFAULT_USER_EDUCATION_LEVEL_CODE = "HIGH_SCHOOL" +export const DEFAULT_USER_LEARNING_GOAL_CODE = "EVERYDAY_CONVERSATION" +export const DEFAULT_USER_LANGUAGE_CHALLENGE_CODE = "PRONUNCIATION" +export const DEFAULT_USER_LANGUAGE_GOAL_CODE = "LEARN_TO_SPEAK_ENGLISH" +export const DEFAULT_USER_FAVOURITE_TOPIC_CODE = "FOOD_COOKING" +export const DEFAULT_USER_COUNTRY_CODE = "ET" +export const DEFAULT_USER_KNOWLEDGE_LEVEL_CODE = "BEGINNER" + +type ProfileFieldOption = { code: string; label: string } + +const AGE_GROUP_OPTIONS: ProfileFieldOption[] = [ + { code: "UNDER_13", label: "Under 13" }, + { code: "13_17", label: "13–17" }, + { code: "18_24", label: "18–24" }, + { code: "25_34", label: "25–34" }, + { code: "35_44", label: "35–44" }, + { code: "45_54", label: "45–54" }, + { code: "55_PLUS", label: "55+" }, +] + +const OCCUPATION_OPTIONS: ProfileFieldOption[] = [ + { code: "STUDENTS", label: "Students (High school & University)" }, + { code: "JOB_SEEKERS", label: "Job Seekers / Fresh Graduates" }, + { code: "WORKING_PROFESSIONALS", label: "Working Professionals (Corporate/Office)" }, + { code: "GOVERNMENT_NGO", label: "Government & NGO Workers" }, + { code: "ENTREPRENEURS", label: "Entrepreneurs & Small Business Owners" }, + { code: "HOSPITALITY_TOURISM", label: "Hospitality & Tourism Workers" }, + { code: "FREELANCERS_REMOTE", label: "Freelancers / Remote Workers (Digital Economy)" }, +] + +const ETHIOPIA_REGION_OPTIONS: ProfileFieldOption[] = [ + { code: "ADDIS_ABABA", label: "Addis Ababa" }, + { code: "AFAR", label: "Afar" }, + { code: "AMHARA", label: "Amhara" }, + { code: "BENISHANGUL_GUMUZ", label: "Benishangul-Gumuz" }, + { code: "CENTRAL_ETHIOPIA", label: "Central Ethiopia" }, + { code: "DIRE_DAWA", label: "Dire Dawa" }, + { code: "GAMBELA", label: "Gambela" }, + { code: "HARARI", label: "Harari" }, + { code: "OROMIA", label: "Oromia" }, + { code: "SIDAMA", label: "Sidama" }, + { code: "SOMALI", label: "Somali" }, + { code: "SOUTH_ETHIOPIA", label: "South Ethiopia" }, + { code: "SOUTH_WEST_ETHIOPIA_PEOPLES", label: "South West Ethiopia Peoples" }, + { code: "TIGRAY", label: "Tigray" }, +] + +const EDUCATION_LEVEL_OPTIONS: ProfileFieldOption[] = [ + { code: "NO_FORMAL", label: "No formal education" }, + { code: "PRIMARY", label: "Primary school" }, + { code: "SECONDARY", label: "Secondary school" }, + { code: "HIGH_SCHOOL", label: "High school" }, + { code: "VOCATIONAL", label: "Vocational / technical" }, + { code: "BACHELOR", label: "Bachelor's degree" }, + { code: "MASTER", label: "Master's degree" }, + { code: "DOCTORATE", label: "Doctorate" }, +] + +const LEARNING_GOAL_OPTIONS: ProfileFieldOption[] = [ + { code: "EVERYDAY_CONVERSATION", label: "Everyday conversation" }, + { code: "WORK_CAREER", label: "Work and career" }, + { code: "ACADEMIC_STUDY", label: "Academic study" }, + { code: "TRAVEL", label: "Travel" }, + { code: "EXAM_PREP", label: "Exam preparation" }, + { code: "PERSONAL_GROWTH", label: "Personal growth" }, +] + +const LANGUAGE_CHALLENGE_OPTIONS: ProfileFieldOption[] = [ + { code: "PRONUNCIATION", label: "Pronunciation" }, + { code: "WORDS_GRAMMAR", label: "Finding words or grammar quickly" }, + { code: "CONFIDENCE", label: "Feeling nervous or lacking confidence" }, + { code: "ACCENTS_FAST_SPEECH", label: "Understanding accents or fast speech" }, +] + +const LANGUAGE_GOAL_OPTIONS: ProfileFieldOption[] = [ + { code: "LEARN_TO_SPEAK_ENGLISH", label: "Learn to Speak English" }, + { code: "PRACTICE_TO_SPEAK_ENGLISH", label: "Practice Speaking English" }, + { code: "SKILL_BASED_COURSES", label: "Skill-based Courses" }, +] + +const FAVOURITE_TOPIC_OPTIONS: ProfileFieldOption[] = [ + { code: "FOOD_COOKING", label: "Food & Cooking" }, + { code: "HOBBIES_SPORTS_MUSIC", label: "Hobbies, Sports, Music" }, + { code: "TECH_NEWS_BUSINESS", label: "Tech, News, Business" }, + { code: "TRAVEL_PLACES_CULTURE", label: "Travel, Places, Culture" }, +] + +const KNOWLEDGE_LEVEL_OPTIONS: ProfileFieldOption[] = [ + { code: "BEGINNER", label: "Beginner" }, + { code: "INTERMEDIATE", label: "Intermediate" }, + { code: "ADVANCED", label: "Advanced" }, +] + +/** ISO-style country codes from field_options seed (subset used for label lookup). */ +const COUNTRY_OPTIONS: ProfileFieldOption[] = [ + { code: "AF", label: "Afghanistan" }, + { code: "AL", label: "Albania" }, + { code: "DZ", label: "Algeria" }, + { code: "AD", label: "Andorra" }, + { code: "AO", label: "Angola" }, + { code: "AR", label: "Argentina" }, + { code: "AM", label: "Armenia" }, + { code: "AU", label: "Australia" }, + { code: "AT", label: "Austria" }, + { code: "AZ", label: "Azerbaijan" }, + { code: "BH", label: "Bahrain" }, + { code: "BD", label: "Bangladesh" }, + { code: "BY", label: "Belarus" }, + { code: "BE", label: "Belgium" }, + { code: "BZ", label: "Belize" }, + { code: "BJ", label: "Benin" }, + { code: "BT", label: "Bhutan" }, + { code: "BO", label: "Bolivia" }, + { code: "BA", label: "Bosnia and Herzegovina" }, + { code: "BW", label: "Botswana" }, + { code: "BR", label: "Brazil" }, + { code: "BN", label: "Brunei" }, + { code: "BG", label: "Bulgaria" }, + { code: "BF", label: "Burkina Faso" }, + { code: "BI", label: "Burundi" }, + { code: "KH", label: "Cambodia" }, + { code: "CM", label: "Cameroon" }, + { code: "CA", label: "Canada" }, + { code: "TD", label: "Chad" }, + { code: "CL", label: "Chile" }, + { code: "CN", label: "China" }, + { code: "CO", label: "Colombia" }, + { code: "KM", label: "Comoros" }, + { code: "CG", label: "Congo" }, + { code: "CR", label: "Costa Rica" }, + { code: "HR", label: "Croatia" }, + { code: "CU", label: "Cuba" }, + { code: "CY", label: "Cyprus" }, + { code: "CZ", label: "Czech Republic" }, + { code: "DK", label: "Denmark" }, + { code: "DJ", label: "Djibouti" }, + { code: "DO", label: "Dominican Republic" }, + { code: "EC", label: "Ecuador" }, + { code: "EG", label: "Egypt" }, + { code: "SV", label: "El Salvador" }, + { code: "ER", label: "Eritrea" }, + { code: "EE", label: "Estonia" }, + { code: "SZ", label: "Eswatini" }, + { code: "ET", label: "Ethiopia" }, + { code: "FI", label: "Finland" }, + { code: "FR", label: "France" }, + { code: "GA", label: "Gabon" }, + { code: "GM", label: "Gambia" }, + { code: "GE", label: "Georgia" }, + { code: "DE", label: "Germany" }, + { code: "GH", label: "Ghana" }, + { code: "GR", label: "Greece" }, + { code: "GT", label: "Guatemala" }, + { code: "GN", label: "Guinea" }, + { code: "HT", label: "Haiti" }, + { code: "HN", label: "Honduras" }, + { code: "HU", label: "Hungary" }, + { code: "IS", label: "Iceland" }, + { code: "IN", label: "India" }, + { code: "ID", label: "Indonesia" }, + { code: "IR", label: "Iran" }, + { code: "IQ", label: "Iraq" }, + { code: "IE", label: "Ireland" }, + { code: "IL", label: "Israel" }, + { code: "IT", label: "Italy" }, + { code: "JM", label: "Jamaica" }, + { code: "JP", label: "Japan" }, + { code: "JO", label: "Jordan" }, + { code: "KZ", label: "Kazakhstan" }, + { code: "KE", label: "Kenya" }, + { code: "KW", label: "Kuwait" }, + { code: "KG", label: "Kyrgyzstan" }, + { code: "LA", label: "Laos" }, + { code: "LV", label: "Latvia" }, + { code: "LB", label: "Lebanon" }, + { code: "LR", label: "Liberia" }, + { code: "LY", label: "Libya" }, + { code: "LT", label: "Lithuania" }, + { code: "LU", label: "Luxembourg" }, + { code: "MG", label: "Madagascar" }, + { code: "MW", label: "Malawi" }, + { code: "MY", label: "Malaysia" }, + { code: "MV", label: "Maldives" }, + { code: "ML", label: "Mali" }, + { code: "MT", label: "Malta" }, + { code: "MX", label: "Mexico" }, + { code: "MD", label: "Moldova" }, + { code: "MC", label: "Monaco" }, + { code: "MN", label: "Mongolia" }, + { code: "MA", label: "Morocco" }, + { code: "MZ", label: "Mozambique" }, + { code: "MM", label: "Myanmar" }, + { code: "NA", label: "Namibia" }, + { code: "NP", label: "Nepal" }, + { code: "NL", label: "Netherlands" }, + { code: "NZ", label: "New Zealand" }, + { code: "NI", label: "Nicaragua" }, + { code: "NE", label: "Niger" }, + { code: "NG", label: "Nigeria" }, + { code: "KP", label: "North Korea" }, + { code: "NO", label: "Norway" }, + { code: "OM", label: "Oman" }, + { code: "PK", label: "Pakistan" }, + { code: "PA", label: "Panama" }, + { code: "PY", label: "Paraguay" }, + { code: "PE", label: "Peru" }, + { code: "PH", label: "Philippines" }, + { code: "PL", label: "Poland" }, + { code: "PT", label: "Portugal" }, + { code: "QA", label: "Qatar" }, + { code: "RO", label: "Romania" }, + { code: "RU", label: "Russia" }, + { code: "RW", label: "Rwanda" }, + { code: "SA", label: "Saudi Arabia" }, + { code: "SN", label: "Senegal" }, + { code: "RS", label: "Serbia" }, + { code: "SG", label: "Singapore" }, + { code: "SK", label: "Slovakia" }, + { code: "SI", label: "Slovenia" }, + { code: "SO", label: "Somalia" }, + { code: "ZA", label: "South Africa" }, + { code: "KR", label: "South Korea" }, + { code: "ES", label: "Spain" }, + { code: "LK", label: "Sri Lanka" }, + { code: "SD", label: "Sudan" }, + { code: "SE", label: "Sweden" }, + { code: "CH", label: "Switzerland" }, + { code: "SY", label: "Syria" }, + { code: "TW", label: "Taiwan" }, + { code: "TJ", label: "Tajikistan" }, + { code: "TZ", label: "Tanzania" }, + { code: "TH", label: "Thailand" }, + { code: "TN", label: "Tunisia" }, + { code: "TR", label: "Turkey" }, + { code: "UG", label: "Uganda" }, + { code: "UA", label: "Ukraine" }, + { code: "AE", label: "United Arab Emirates" }, + { code: "GB", label: "United Kingdom" }, + { code: "US", label: "United States" }, + { code: "UY", label: "Uruguay" }, + { code: "UZ", label: "Uzbekistan" }, + { code: "VE", label: "Venezuela" }, + { code: "VN", label: "Vietnam" }, + { code: "YE", label: "Yemen" }, + { code: "ZM", label: "Zambia" }, + { code: "ZW", label: "Zimbabwe" }, +] + +const REGION_ALIASES: Record = { + GAMBELA_PEOPLES_REGION: "GAMBELA", + SOUTH_WEST_ETHIOPIA_PEOPLES_REGION: "SOUTH_WEST_ETHIOPIA_PEOPLES", + SOUTHERN_NATIONS_NATIONALITIES_AND_PEOPLES_REGION: "SOUTH_ETHIOPIA", +} + +function normalizeProfileFieldKey(value: string): string { + return value + .trim() + .toUpperCase() + .replace(/['’]/g, "") + .replace(/[\s-]+/g, "_") + .replace(/_+/g, "_") +} + +function isCatchAllProfileValue(normalized: string): boolean { + return ( + !normalized || + normalized === "OTHER" || + normalized === "UNKNOWN" || + normalized === "UNASSIGNED" || + normalized === "N_A" || + normalized === "NA" + ) +} + +function labelForCode(options: ProfileFieldOption[], code: string): string { + return options.find((o) => o.code === code)?.label ?? code +} + +function resolveProfileFieldCode( + raw: string | null | undefined, + options: ProfileFieldOption[], + defaultCode: string, + aliases?: Record, +): string { + const trimmed = raw?.trim() ?? "" + const normalized = normalizeProfileFieldKey(trimmed) + if (isCatchAllProfileValue(normalized)) return defaultCode + + if (aliases?.[normalized]) return aliases[normalized] + + for (const opt of options) { + if (opt.code === "OTHER") continue + if (normalized === opt.code) return opt.code + if (normalized === normalizeProfileFieldKey(opt.label)) return opt.code + } + + const lower = trimmed.toLowerCase() + for (const opt of options) { + if (opt.code === "OTHER") continue + if (lower === opt.label.toLowerCase()) return opt.code + } + + return defaultCode +} + +function displayProfileFieldLabel( + raw: string | null | undefined, + options: ProfileFieldOption[], + defaultCode: string, + aliases?: Record, +): string { + const code = resolveProfileFieldCode(raw, options, defaultCode, aliases) + return labelForCode(options, code) +} + +export function displayUserAgeGroup(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, AGE_GROUP_OPTIONS, DEFAULT_USER_AGE_GROUP_CODE) +} + +export function displayUserOccupation(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, OCCUPATION_OPTIONS, DEFAULT_USER_OCCUPATION_CODE) +} + +export function displayUserRegion(raw: string | null | undefined): string { + return displayProfileFieldLabel( + raw, + ETHIOPIA_REGION_OPTIONS, + DEFAULT_USER_REGION_CODE, + REGION_ALIASES, + ) +} + +export function displayUserEducationLevel(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, EDUCATION_LEVEL_OPTIONS, DEFAULT_USER_EDUCATION_LEVEL_CODE) +} + +export function displayUserLearningGoal(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, LEARNING_GOAL_OPTIONS, DEFAULT_USER_LEARNING_GOAL_CODE) +} + +export function displayUserLanguageChallenge(raw: string | null | undefined): string { + return displayProfileFieldLabel( + raw, + LANGUAGE_CHALLENGE_OPTIONS, + DEFAULT_USER_LANGUAGE_CHALLENGE_CODE, + ) +} + +export function displayUserLanguageGoal(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, LANGUAGE_GOAL_OPTIONS, DEFAULT_USER_LANGUAGE_GOAL_CODE) +} + +export function displayUserFavouriteTopic(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, FAVOURITE_TOPIC_OPTIONS, DEFAULT_USER_FAVOURITE_TOPIC_CODE) +} + +export function displayUserCountry(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, COUNTRY_OPTIONS, DEFAULT_USER_COUNTRY_CODE) +} + +export function displayUserKnowledgeLevel(raw: string | null | undefined): string { + return displayProfileFieldLabel(raw, KNOWLEDGE_LEVEL_OPTIONS, DEFAULT_USER_KNOWLEDGE_LEVEL_CODE) +} + +/** Merge analytics rows that share the same display label (fixes OTHER→default duplicates). */ +export function mergeAnalyticsRowsByDisplayLabel( + rows: Array<{ label: string; count: number }>, + formatLabel: (raw: string) => string, +): Array<{ label: string; count: number }> { + const sums = new Map() + for (const row of rows) { + const label = formatLabel(row.label) + sums.set(label, (sums.get(label) ?? 0) + (row.count || 0)) + } + return Array.from(sums.entries()) + .map(([label, count]) => ({ label, count })) + .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label)) +} diff --git a/src/pages/analytics/AnalyticsPage.tsx b/src/pages/analytics/AnalyticsPage.tsx index d9abb02..790f3e2 100644 --- a/src/pages/analytics/AnalyticsPage.tsx +++ b/src/pages/analytics/AnalyticsPage.tsx @@ -63,18 +63,29 @@ import { formatRevenueAxisTick, } from "../../lib/analytics" import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types" -import { UnassignedLabel, isUnassignedLabel } from "../../lib/displayValue" +import { isUnassignedLabel } from "../../lib/displayValue" +import { + displayUserAgeGroup, + displayUserOccupation, + displayUserRegion, + displayUserEducationLevel, + displayUserLearningGoal, + displayUserLanguageChallenge, + displayUserCountry, + displayUserKnowledgeLevel, + mergeAnalyticsRowsByDisplayLabel, +} from "../../lib/userProfileFieldDisplay" const PIE_COLORS = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0", "#6366F1", "#F97316", "#14B8A6", "#EF4444", "#8B5CF6", "#EC4899", "#06B6D4", "#84CC16"] -function genderAnalyticsRowLabel(label: string): ReactNode { +function genderAnalyticsRowLabel(label: string): string { const trimmed = label?.trim() ?? "" if ( isUnassignedLabel(trimmed) || trimmed.toUpperCase() === "OTHER" || trimmed.toLowerCase() === "unknown" ) { - return + return "unassigned" } return formatAnalyticsLabel(label) } @@ -151,31 +162,26 @@ function BreakdownList({ data: LabelCount[] total?: number scrollable?: boolean - formatRowLabel?: (label: string) => ReactNode + formatRowLabel?: (label: string) => string }) { - const computedTotal = total ?? data.reduce((s, d) => s + d.count, 0) - const sorted = [...data].sort((a, b) => b.count - a.count) + const labelFn = formatRowLabel ?? formatAnalyticsLabel + const merged = mergeAnalyticsRowsByDisplayLabel(data, labelFn).filter( + (row) => row.label.trim().toUpperCase() !== "OTHER", + ) + const computedTotal = total ?? merged.reduce((s, d) => s + d.count, 0) return ( {title} - {sorted.length > 0 ? ( + {merged.length > 0 ? (
- {sorted.map((item, i) => { + {merged.map((item, i) => { const pct = computedTotal > 0 ? (item.count / computedTotal) * 100 : 0 - const displayLabel = formatRowLabel - ? formatRowLabel(item.label) - : formatAnalyticsLabel(item.label) - const titleText = - typeof displayLabel === "string" - ? displayLabel - : isUnassignedLabel(item.label) || item.label.toUpperCase() === "OTHER" - ? "unassigned" - : formatAnalyticsLabel(item.label) + const displayLabel = item.label return (
@@ -184,7 +190,7 @@ function BreakdownList({ className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }} /> - + {displayLabel}
@@ -634,21 +640,25 @@ export function AnalyticsPage() { title="Learning goal" data={users.by_learning_goal ?? []} total={users.total_users} + formatRowLabel={displayUserLearningGoal} /> {(users.by_knowledge_level?.length ?? 0) > 0 ? ( ) : null}
@@ -689,12 +703,14 @@ export function AnalyticsPage() { title="Learning goal" data={users.by_learning_goal ?? []} total={users.total_users} + formatRowLabel={displayUserLearningGoal} scrollable />
diff --git a/src/pages/content-management/AllCoursesPage.tsx b/src/pages/content-management/AllCoursesPage.tsx index 022ed8b..8b15879 100644 --- a/src/pages/content-management/AllCoursesPage.tsx +++ b/src/pages/content-management/AllCoursesPage.tsx @@ -34,6 +34,7 @@ import { cn } from "../../lib/utils" import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg" import { PageBackLink } from "../../components/navigation/PageBackLink" +import { SearchHighlight } from "../../components/SearchHighlight" type CourseWithCategory = Course & { category_name: string } @@ -346,16 +347,16 @@ export function AllCoursesPage() { >
- {course.title} +
{course.description && (
- {course.description} +
)}
- {course.category_name} + - {section.title} + - {section.description} + diff --git a/src/pages/content-management/CourseCategoryPage.tsx b/src/pages/content-management/CourseCategoryPage.tsx index 6f75608..9de5898 100644 --- a/src/pages/content-management/CourseCategoryPage.tsx +++ b/src/pages/content-management/CourseCategoryPage.tsx @@ -19,6 +19,7 @@ import { import { getCourseCategories, createCourseCategory, deleteCourseCategory } from "../../api/courses.api" import type { CourseCategory } from "../../types/course.types" import { toast } from "sonner" +import { SearchHighlight } from "../../components/SearchHighlight" export function CourseCategoryPage() { const [categories, setCategories] = useState([]) @@ -163,7 +164,7 @@ export function CourseCategoryPage() { - {category.name} + diff --git a/src/pages/content-management/CourseDetailPage.tsx b/src/pages/content-management/CourseDetailPage.tsx index a7d62de..c7265f3 100644 --- a/src/pages/content-management/CourseDetailPage.tsx +++ b/src/pages/content-management/CourseDetailPage.tsx @@ -58,7 +58,8 @@ import { AddModuleModal } from "./components/AddModuleModal"; import { ModuleIconUploadField } from "./components/ModuleIconUploadField"; import { ModulePracticeCard } from "./components/ModulePracticeCard"; import { PublishPracticeButton } from "./components/PublishPracticeButton"; -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" const MODULE_CARD_GRADIENT = "from-[#8E44AD] to-[#C39BD3]" as const; @@ -783,12 +784,13 @@ export function CourseDetailPage() { />

- {module.name} +

- {module.description?.trim() - ? module.description - : } +

@@ -852,6 +854,7 @@ export function CourseDetailPage() { key={practice.id} practice={practice} statusUpdating={publishStatusPracticeId === practice.id} + searchQuery={practiceSearch} onEdit={() => navigate( `/new-content/learn-english/${programIdParam}/courses/${courseIdNum}/edit-practice/${practice.id}?backTo=courses`, diff --git a/src/pages/content-management/CourseManagementPage.tsx b/src/pages/content-management/CourseManagementPage.tsx index 0521bce..9633ecd 100644 --- a/src/pages/content-management/CourseManagementPage.tsx +++ b/src/pages/content-management/CourseManagementPage.tsx @@ -47,7 +47,8 @@ import { ContentAccessTierChip } from "./components/ContentAccessTierChip"; import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar"; import { ContentPageDescription } from "./components/ContentPageDescription"; import type { ContentAccessTier, PracticePublishStatus } from "../../types/course.types"; -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" import { filterBySearchAndPublishStatus, type PublishStatusFilter, @@ -167,7 +168,7 @@ export function CourseManagementPage() { list.map((row, index) => ({ id: Number(row.id), name: row.name?.trim() || `Unit ${row.id}`, - description: row.description?.trim() || , + description: row.description?.trim() || "", thumbnail: row.thumbnail?.trim() || "", sortOrder: Number(row.sort_order ?? 0), publishStatus: row.publish_status ?? null, @@ -466,10 +467,7 @@ export function CourseManagementPage() { setSavingEdit(true); try { const existing = units.find((u) => u.id === editingUnitId); - const preservedDescription = - existing?.description && existing.description !== "unassigned" - ? existing.description - : null; + const preservedDescription = existing?.description?.trim() || null; const minioThumbnail = await resolveThumbnailToMinioUrl(editThumbnail); await updateExamPrepCatalogUnit(editingUnitId, { name, @@ -852,10 +850,10 @@ export function CourseManagementPage() { />

- {unit.name} +

- {unit.description} +

diff --git a/src/pages/content-management/CourseModuleDetailPage.tsx b/src/pages/content-management/CourseModuleDetailPage.tsx index 3cd66b0..7908b44 100644 --- a/src/pages/content-management/CourseModuleDetailPage.tsx +++ b/src/pages/content-management/CourseModuleDetailPage.tsx @@ -46,7 +46,7 @@ import type { import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar"; import { ContentPageDescription } from "./components/ContentPageDescription"; import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip"; -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" import { filterBySearchAndPublishStatus, type PublishStatusFilter, @@ -80,7 +80,7 @@ export function CourseModuleDetailPage() { [lessonPracticeChoice], ); const [moduleTitle, setModuleTitle] = useState("Module"); - const [moduleDescription, setModuleDescription] = useState("unassigned"); + const [moduleDescription, setModuleDescription] = useState(""); const [modulePublishStatus, setModulePublishStatus] = useState< PracticePublishStatus | string | null >(null); @@ -174,17 +174,17 @@ export function CourseModuleDetailPage() { const row = list.find((m) => Number(m.id) === parsedModuleId); if (row) { setModuleTitle(row.name?.trim() || `Module ${parsedModuleId}`); - setModuleDescription(row.description?.trim() || ); + setModuleDescription(row.description?.trim() || ""); setModulePublishStatus(row.publish_status ?? null); } else { setModuleTitle(`Module ${parsedModuleId}`); - setModuleDescription("unassigned"); + setModuleDescription(""); setModulePublishStatus(null); } } catch (error) { console.error(error); setModuleTitle(`Module ${parsedModuleId}`); - setModuleDescription("unassigned"); + setModuleDescription(""); } }, [parsedModuleId, parsedUnitId]); @@ -628,7 +628,7 @@ export function CourseModuleDetailPage() { {moduleTitle} - {moduleDescription} + @@ -876,6 +876,7 @@ export function CourseModuleDetailPage() { LESSON_THUMB_GRADIENTS[i % LESSON_THUMB_GRADIENTS.length] } durationSeconds={lesson.durationSeconds} + searchQuery={lessonSearch} onEdit={() => openEditLesson(lesson)} onDelete={() => setDeletingLessonId(lesson.id)} description={lesson.description} diff --git a/src/pages/content-management/CoursesPage.tsx b/src/pages/content-management/CoursesPage.tsx index b4e54b0..4c80afa 100644 --- a/src/pages/content-management/CoursesPage.tsx +++ b/src/pages/content-management/CoursesPage.tsx @@ -41,7 +41,8 @@ import { import type { CategorySubCategoryListItem, CourseCategory } from "../../types/course.types" import { cn } from "../../lib/utils" import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" export function CoursesPage() { const { categoryId } = useParams<{ categoryId: string }>() @@ -408,15 +409,19 @@ export function CoursesPage() {
-

{sub.name}

+

+ +

- {sub.category_name} + + +

- {sub.description?.trim() ? sub.description : } +

diff --git a/src/pages/content-management/EditPracticeFlow.tsx b/src/pages/content-management/EditPracticeFlow.tsx index d35c5e3..493d717 100644 --- a/src/pages/content-management/EditPracticeFlow.tsx +++ b/src/pages/content-management/EditPracticeFlow.tsx @@ -335,9 +335,25 @@ export function EditPracticeFlow() { setLoadingPractice(true); setLoadError(null); try { - const res = isExamPrep - ? await getExamPrepPracticeFull(practiceId) - : await getLearnEnglishPracticeFull(practiceId); + const loadPrimary = isExamPrep + ? getExamPrepPracticeFull + : getLearnEnglishPracticeFull; + const loadFallback = isExamPrep + ? getLearnEnglishPracticeFull + : getExamPrepPracticeFull; + + let res: Awaited>; + try { + res = await loadPrimary(practiceId); + } catch (primaryError) { + // Hierarchy URLs / mislabeled kind: retry the other practice table. + try { + res = await loadFallback(practiceId); + } catch { + throw primaryError; + } + } + const full = unwrapPracticeFullData(res); if (!full) throw new Error("Practice details were missing from the response."); const mapped = mapPracticeFullToFormState(full, typeDefinitions); diff --git a/src/pages/content-management/LearnEnglishPage.tsx b/src/pages/content-management/LearnEnglishPage.tsx index a71cc0f..fa0d44c 100644 --- a/src/pages/content-management/LearnEnglishPage.tsx +++ b/src/pages/content-management/LearnEnglishPage.tsx @@ -42,7 +42,8 @@ import { } from "../../lib/contentListFilters"; import { refreshFileUrl, uploadImageFile } from "../../api/files.api"; import type { LearningProgramListItem } from "../../types/course.types"; -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" /** Presigned MinIO/S3 URLs and our storage hosts — safe to send to POST /files/refresh-url. */ function looksLikeRefreshableFileUrl(url: string): boolean { @@ -728,12 +729,10 @@ export function LearnEnglishPage() { />

- {program.name} +

- {program.description?.trim() - ? program.description - : } +

void navigate(editPracticeHref(p.id))} onPublish={() => void handlePracticePublishStatus(p.id, "PUBLISHED") diff --git a/src/pages/content-management/ModuleDetailPage.tsx b/src/pages/content-management/ModuleDetailPage.tsx index dca42d8..c769ef2 100644 --- a/src/pages/content-management/ModuleDetailPage.tsx +++ b/src/pages/content-management/ModuleDetailPage.tsx @@ -614,6 +614,7 @@ export function ModuleDetailPage() { hoverModuleActions thumbnailUrl={resolveThumbnailForPreview(lesson.thumbnail)} thumbnailGradient={LESSON_THUMB_GRADIENTS[i % LESSON_THUMB_GRADIENTS.length]} + searchQuery={lessonSearch} durationSeconds={(() => { const raw = lesson.duration_seconds ?? lesson.duration ?? null; @@ -708,6 +709,7 @@ export function ModuleDetailPage() { key={practice.id} practice={practice} statusUpdating={publishStatusPracticeId === practice.id} + searchQuery={practiceSearch} onEdit={() => navigate( `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}/edit-practice/${practice.id}?backTo=module`, diff --git a/src/pages/content-management/NewContentPage.tsx b/src/pages/content-management/NewContentPage.tsx index 26d451d..9a8b0a2 100644 --- a/src/pages/content-management/NewContentPage.tsx +++ b/src/pages/content-management/NewContentPage.tsx @@ -49,25 +49,25 @@ export function NewContentPage() { - {/* Cards Grid */} -
+ {/* Cards Grid — equal-height cards with bottom-aligned actions */} +
{/* Learn English Card */} - -
+ +
- +

Learn English

-

+

Manage structured English learning content based on levels and modules.

- - @@ -75,19 +75,19 @@ export function NewContentPage() {
{/* Courses Card */} - -
+ +
- +

Courses

-

+

Manage skill-based and Duolingo/IELTS courses.

- - diff --git a/src/pages/content-management/ProgramCoursesPage.tsx b/src/pages/content-management/ProgramCoursesPage.tsx index 12e2f36..eab308c 100644 --- a/src/pages/content-management/ProgramCoursesPage.tsx +++ b/src/pages/content-management/ProgramCoursesPage.tsx @@ -46,7 +46,8 @@ import type { ProgramCourseListItem, } from "../../types/course.types"; import { PublishPracticeButton } from "./components/PublishPracticeButton"; -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" export function ProgramCoursesPage() { const navigate = useNavigate(); @@ -757,10 +758,10 @@ export function ProgramCoursesPage() { />

- {course.name} +

- {course.description?.trim() ? course.description : } +

diff --git a/src/pages/content-management/ProgramDetailPage.tsx b/src/pages/content-management/ProgramDetailPage.tsx index 7b99b61..caf4c0e 100644 --- a/src/pages/content-management/ProgramDetailPage.tsx +++ b/src/pages/content-management/ProgramDetailPage.tsx @@ -44,7 +44,8 @@ import { } from "../../lib/contentListFilters"; import { uploadImageFile } from "../../api/files.api"; import uploadIcon from "../../assets/icons/upload.png"; -import { UnassignedLabel } from "../../lib/displayValue" +import { DisplayValue } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" export function ProgramDetailPage() { const navigate = useNavigate(); @@ -117,7 +118,7 @@ export function ProgramDetailPage() { list.map((row) => ({ id: Number(row.id), name: row.name?.trim() || `Course ${row.id}`, - description: row.description?.trim() || , + description: row.description?.trim() || "", thumbnail: row.thumbnail?.trim() || null, sortOrder: Number(row.sort_order ?? 0), publishStatus: row.publish_status ?? null, @@ -311,7 +312,7 @@ export function ProgramDetailPage() { { id: row.id, name: row.name ?? name, - description: row.description?.trim() || , + description: row.description?.trim() || "", thumbnail: row.thumbnail?.trim() || null, sortOrder: Number(row.sort_order ?? 0), unitsCount: Number(row.units_count ?? 0), @@ -394,9 +395,7 @@ export function ProgramDetailPage() { const minioThumbnail = await resolveThumbnailToMinioUrl(editThumbnail); const existing = createdCourses.find((c) => c.id === editingCourseId); const preservedDescription = - existing?.description && existing.description !== "unassigned" - ? existing.description - : null; + typeof existing?.description === "string" ? existing.description.trim() || null : null; const response = await updateExamPrepCatalogCourse(editingCourseId, { name, description: preservedDescription, @@ -410,7 +409,7 @@ export function ProgramDetailPage() { ? { ...course, name: row?.name ?? name, - description: row?.description?.trim() || preservedDescription || , + description: row?.description?.trim() || preservedDescription || "", thumbnail: row?.thumbnail?.trim() || null, sortOrder: Number(row?.sort_order ?? sortOrderNum), unitsCount: Number(row?.units_count ?? course.unitsCount ?? 0), @@ -754,10 +753,10 @@ export function ProgramDetailPage() {
) : null}

- {course.name} +

-

- {course.description} +

+

diff --git a/src/pages/content-management/ProgramTypeSelectionPage.tsx b/src/pages/content-management/ProgramTypeSelectionPage.tsx index fe0d006..e782d53 100644 --- a/src/pages/content-management/ProgramTypeSelectionPage.tsx +++ b/src/pages/content-management/ProgramTypeSelectionPage.tsx @@ -11,9 +11,9 @@ export function ProgramTypeSelectionPage() {

Courses

-

- Organize courses under skill-based learning or English proficiency - exams. Select a program type to manage curriculum and modules. +

+ Organize courses under skill-based learning or English Proficiency + Exams. Select a program type to manage curriculum and modules.

@@ -32,20 +32,20 @@ export function ProgramTypeSelectionPage() {
- {/* Selection Cards Grid */} -
+ {/* Selection Cards Grid — equal width/height, consistent content alignment */} +
{/* Skill-Based Courses Card */} -
-
+
+
-
+

Skill-Based Courses

-

+

Practice-focused communication and skills training. Create modules for vocabulary, grammar, and real-world conversation scenarios. @@ -54,20 +54,20 @@ export function ProgramTypeSelectionPage() {

- {/* Duolingo/IELTS Card */} + {/* English Proficiency Exams Card */} -
-
+
+
-
+

- Duolingo/IELTS + English Proficiency Exams

-

- Duolingo/IELTS courses. Structure content by band scores, - sections, and mock tests. +

+ English Proficiency Exams courses. Structure content by band + scores, sections, and mock tests.

diff --git a/src/pages/content-management/QuestionTypeLibraryPage.tsx b/src/pages/content-management/QuestionTypeLibraryPage.tsx index 10a649d..49f754d 100644 --- a/src/pages/content-management/QuestionTypeLibraryPage.tsx +++ b/src/pages/content-management/QuestionTypeLibraryPage.tsx @@ -5,10 +5,7 @@ import { ChevronDown, ChevronLeft, ChevronRight, - ChevronUp, - FolderOpen, Layers, - Pencil, Plus, RefreshCw, Search, @@ -17,7 +14,6 @@ import { } from "lucide-react" import { toast } from "sonner" import { Button } from "../../components/ui/button" -import { Badge } from "../../components/ui/badge" import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel" import { Input } from "../../components/ui/input" import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card" @@ -39,25 +35,11 @@ import { deleteQuestionTypeDefinition, getQuestionTypeDefinitions, } from "../../api/questionTypeDefinitions.api" -import { - deleteQuestionTypeDefinitionGroup, - getQuestionTypeDefinitionGroups, -} from "../../api/questionTypeDefinitionGroups.api" -import type { - QuestionTypeDefinition, - QuestionTypeDefinitionGroup, -} from "../../types/questionTypeDefinition.types" -import { QuestionTypeGroupFormDialog } from "./components/QuestionTypeGroupFormDialog" +import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types" import { PageBackLink } from "../../components/navigation/PageBackLink" -import { - definitionBelongsToGroup, - isDefinitionUngrouped, - questionTypeGroupLabels, -} from "../../lib/questionTypeGroupIds" type StatusFilter = "All" | "ACTIVE" | "INACTIVE" type ScopeFilter = "all" | "system" | "custom" -type GroupFilter = "all" | "ungrouped" | number const STATUS_OPTIONS: { value: StatusFilter; label: string }[] = [ { value: "All", label: "All statuses" }, @@ -79,49 +61,23 @@ export function QuestionTypeLibraryPage() { const [loading, setLoading] = useState(true) const [definitions, setDefinitions] = useState([]) - const [groups, setGroups] = useState([]) - const [groupsLoading, setGroupsLoading] = useState(true) const [query, setQuery] = useState("") const [statusFilter, setStatusFilter] = useState("All") const [scopeFilter, setScopeFilter] = useState("all") - const [groupFilter, setGroupFilter] = useState("all") const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [offset, setOffset] = useState(0) const [definitionPendingDelete, setDefinitionPendingDelete] = useState(null) const [deleteSubmitting, setDeleteSubmitting] = useState(false) const [definitionForPractices, setDefinitionForPractices] = useState(null) - const [groupFormOpen, setGroupFormOpen] = useState(false) - const [groupPendingEdit, setGroupPendingEdit] = useState(null) - const [groupPendingDelete, setGroupPendingDelete] = useState(null) - const [groupDeleteSubmitting, setGroupDeleteSubmitting] = useState(false) - const [groupsSectionOpen, setGroupsSectionOpen] = useState(false) const hasActiveFilters = - query.trim().length > 0 || - statusFilter !== "All" || - scopeFilter !== "all" || - groupFilter !== "all" + query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all" const activeFilterCount = countActiveFilters([ { value: statusFilter, defaultValue: "All" }, { value: scopeFilter, defaultValue: "all" }, - { value: groupFilter === "all" ? "" : "filtered", defaultValue: "" }, ]) - const loadGroups = useCallback(async () => { - setGroupsLoading(true) - try { - const { groups: rows } = await getQuestionTypeDefinitionGroups() - setGroups(rows) - } catch (e) { - console.error(e) - notifyApiError(e, "Failed to load question type groups") - setGroups([]) - } finally { - setGroupsLoading(false) - } - }, []) - const load = useCallback(async () => { setLoading(true) try { @@ -143,12 +99,11 @@ export function QuestionTypeLibraryPage() { useEffect(() => { void load() - void loadGroups() - }, [load, loadGroups]) + }, [load]) useEffect(() => { setOffset(0) - }, [query, pageSize, scopeFilter, statusFilter, groupFilter]) + }, [query, pageSize, scopeFilter, statusFilter]) useEffect(() => { if (createdId) { @@ -165,23 +120,14 @@ export function QuestionTypeLibraryPage() { const isSystemScope = scopeFilter === "system" const filtered = useMemo(() => { - let rows = definitions - if (groupFilter === "ungrouped") { - rows = rows.filter((d) => isDefinitionUngrouped(d.group_ids)) - } else if (typeof groupFilter === "number") { - rows = rows.filter((d) => definitionBelongsToGroup(d.group_ids, groupFilter)) - } const q = query.trim().toLowerCase() - if (!q) return rows - return rows.filter((d) => { + if (!q) return definitions + return definitions.filter((d) => { const name = (d.display_name || "").toLowerCase() const key = (d.key || "").toLowerCase() - const groupName = questionTypeGroupLabels(d.group_ids, groups).toLowerCase() - return ( - name.includes(q) || key.includes(q) || String(d.id).includes(q) || groupName.includes(q) - ) + return name.includes(q) || key.includes(q) || String(d.id).includes(q) }) - }, [definitions, query, groupFilter, groups]) + }, [definitions, query]) const paginated = useMemo(() => { if (isSystemScope) return filtered @@ -201,42 +147,9 @@ export function QuestionTypeLibraryPage() { setQuery("") setStatusFilter("All") setScopeFilter("all") - setGroupFilter("all") setOffset(0) } - const definitionCountByGroup = useMemo(() => { - const counts = new Map() - for (const d of definitions) { - for (const id of d.group_ids ?? []) { - counts.set(id, (counts.get(id) ?? 0) + 1) - } - } - return counts - }, [definitions]) - - const ungroupedCount = useMemo( - () => definitions.filter((d) => isDefinitionUngrouped(d.group_ids)).length, - [definitions], - ) - - const handleConfirmDeleteGroup = async () => { - const row = groupPendingDelete - if (!row) return - setGroupDeleteSubmitting(true) - try { - await deleteQuestionTypeDefinitionGroup(row.id) - toast.success("Group deleted. Membership links for this group were removed.") - setGroupPendingDelete(null) - if (groupFilter === row.id) setGroupFilter("all") - await Promise.all([load(), loadGroups()]) - } catch (e) { - notifyApiError(e, "Delete failed") - } finally { - setGroupDeleteSubmitting(false) - } - } - const openDeleteConfirm = (row: QuestionTypeDefinition) => { if (row.is_system) { toast.error("System definitions cannot be deleted.") @@ -292,144 +205,6 @@ export function QuestionTypeLibraryPage() {
- - -
- - -
-
- {groupsSectionOpen ? ( - - {groupsLoading ? ( -
- - Loading groups… -
- ) : groups.length === 0 ? ( -
- No groups yet. Create one to organize your question type catalog. -
- ) : ( -
    - {groups.map((g) => ( -
  • - -
    - - {g.status} - - - - -
    -
  • - ))} -
- )} -
- ) : null} -
-
@@ -452,7 +227,6 @@ export function QuestionTypeLibraryPage() { disabled={loading} onClick={() => { void load() - void loadGroups() }} > @@ -527,39 +301,6 @@ export function QuestionTypeLibraryPage() { /> ))}
-
- - Group - - { - setGroupFilter("all") - resetPagination() - }} - /> - { - setGroupFilter("ungrouped") - resetPagination() - }} - /> - {typeof groupFilter === "number" ? ( - { - navigate(`/new-content/question-types/groups/${groupFilter}`) - }} - /> - ) : null} -
@@ -613,6 +354,7 @@ export function QuestionTypeLibraryPage() { is_system={d.is_system} stimulusKindsCount={d.stimulus_component_kinds?.length ?? 0} responseKindsCount={d.response_component_kinds?.length ?? 0} + searchQuery={query} deleteDisabled={!!d.is_system} onEdit={() => navigate(`/new-content/question-types/${d.id}/edit`)} onCreatePractice={() => @@ -697,49 +439,6 @@ export function QuestionTypeLibraryPage() { - { - void loadGroups() - void load() - }} - /> - - !groupDeleteSubmitting && !open && setGroupPendingDelete(null)} - > - - - Delete group? - - Deleting "{groupPendingDelete?.name}" will not delete any question types. - Definitions will be removed from this group only; other group memberships are unchanged. - - - - - - - - -
- {question.question_text} +
{question.question_type === "MCQ" && (question.options?.length ?? 0) > 0 && (
diff --git a/src/pages/content-management/SpeakingPage.tsx b/src/pages/content-management/SpeakingPage.tsx index a948449..d7483c1 100644 --- a/src/pages/content-management/SpeakingPage.tsx +++ b/src/pages/content-management/SpeakingPage.tsx @@ -39,6 +39,7 @@ import { countActiveFilters } from "../../lib/adminFilterUtils" import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" import { UnassignedLabel } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024 const ALLOWED_AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "m4a", "aac", "webm", "flac"]) @@ -1459,7 +1460,14 @@ export function SpeakingPage() { } onChange={() => togglePracticeSelection(group.practiceId)} /> - {group.practiceTitle} {group.practiceId ? `(#${group.practiceId})` : ""} + {group.practiceTitle ? ( + + ) : ( + "Unknown practice" + )}
@@ -1481,7 +1489,9 @@ export function SpeakingPage() { onChange={() => toggleQuestionSelection(question.id)} className="mt-1" /> -

{question.question_text}

+

+ +

- {module.name} +

- {module.description} +

diff --git a/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx b/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx index 754d78b..5ce872f 100644 --- a/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx +++ b/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx @@ -251,6 +251,7 @@ export function CatalogCoursePracticesPanel({ key={practice.id} practice={practice} statusUpdating={publishStatusUpdatingId === practice.id} + searchQuery={listSearch} onEdit={() => navigate(editPracticeHref(practice.id))} onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} diff --git a/src/pages/content-management/components/ModulePracticeCard.tsx b/src/pages/content-management/components/ModulePracticeCard.tsx index f43f489..83f1069 100644 --- a/src/pages/content-management/components/ModulePracticeCard.tsx +++ b/src/pages/content-management/components/ModulePracticeCard.tsx @@ -18,12 +18,14 @@ import { practicePublishStatus, } from "../../../lib/parentContextPractice"; import { resolveThumbnailForPreview } from "../../../lib/videoPreview"; +import { SearchHighlight } from "../../../components/SearchHighlight"; import { cn } from "../../../lib/utils"; import { PublishStatusConfirmDialog } from "./PublishStatusConfirmDialog"; type ModulePracticeCardProps = { practice: ParentContextPractice; statusUpdating?: boolean; + searchQuery?: string; onEdit?: () => void; onPublish?: () => void; onSaveAsDraft?: () => void; @@ -34,6 +36,7 @@ type ModulePracticeCardProps = { export function ModulePracticeCard({ practice, statusUpdating = false, + searchQuery = "", onEdit, onPublish, onSaveAsDraft, @@ -167,7 +170,7 @@ export function ModulePracticeCard({

- {practice.title} +

diff --git a/src/pages/content-management/components/QuestionTypeCard.tsx b/src/pages/content-management/components/QuestionTypeCard.tsx index 8e67ba4..53877e3 100644 --- a/src/pages/content-management/components/QuestionTypeCard.tsx +++ b/src/pages/content-management/components/QuestionTypeCard.tsx @@ -3,6 +3,7 @@ import { Badge } from "../../../components/ui/badge" import { Card } from "../../../components/ui/card" import { Button } from "../../../components/ui/button" import { cn } from "../../../lib/utils" +import { SearchHighlight } from "../../../components/SearchHighlight" import { UnassignedLabel, isUnassignedLabel } from "../../../lib/displayValue" export interface QuestionTypeDefinitionCardModel { @@ -13,6 +14,7 @@ export interface QuestionTypeDefinitionCardModel { is_system?: boolean stimulusKindsCount: number responseKindsCount: number + searchQuery?: string onEdit?: () => void onDelete?: () => void onViewPractices?: () => void @@ -28,6 +30,7 @@ export function QuestionTypeCard({ is_system, stimulusKindsCount, responseKindsCount, + searchQuery = "", onEdit, onDelete, onViewPractices, @@ -41,7 +44,9 @@ export function QuestionTypeCard({
-

{display_name}

+

+ +

{is_system ? ( @@ -55,7 +60,9 @@ export function QuestionTypeCard({ )}
-

#{id} · {definitionKey}

+

+ +

diff --git a/src/pages/content-management/components/UnitPracticesPanel.tsx b/src/pages/content-management/components/UnitPracticesPanel.tsx index 9ec191b..b814524 100644 --- a/src/pages/content-management/components/UnitPracticesPanel.tsx +++ b/src/pages/content-management/components/UnitPracticesPanel.tsx @@ -253,6 +253,7 @@ export function UnitPracticesPanel({ key={practice.id} practice={practice} statusUpdating={publishStatusUpdatingId === practice.id} + searchQuery={listSearch} onEdit={() => navigate(editPracticeHref(practice.id))} onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} diff --git a/src/pages/content-management/components/VideoCard.tsx b/src/pages/content-management/components/VideoCard.tsx index f029263..54c8a6b 100644 --- a/src/pages/content-management/components/VideoCard.tsx +++ b/src/pages/content-management/components/VideoCard.tsx @@ -17,6 +17,7 @@ import { } from "../../../components/ui/dialog"; import { isAdminOrSuperAdminRole } from "../../../lib/sessionRole"; import { cn } from "../../../lib/utils"; +import { SearchHighlight } from "../../../components/SearchHighlight"; import { applyShortPreviewToEmbedUrl, DEFAULT_PREVIEW_MAX_SECONDS, @@ -95,6 +96,8 @@ interface VideoCardProps { accessTierUpdating?: boolean; /** Shown under title on module lesson cards; reserved height keeps grid rows even. */ description?: string | null; + /** When set, matching search keywords are highlighted in title/description. */ + searchQuery?: string; } export function VideoCard({ @@ -118,6 +121,7 @@ export function VideoCard({ accessTierUpdating = false, hoverModuleActions = false, description, + searchQuery = "", }: VideoCardProps) { const [thumbFailed, setThumbFailed] = useState(false); const [probedDurationSeconds, setProbedDurationSeconds] = useState< @@ -552,12 +556,16 @@ export function VideoCard({

- {title} +

{hoverModuleActions ? (

- {description?.trim() ? description.trim() : "\u00a0"} + {description?.trim() ? ( + + ) : ( + "\u00a0" + )}

) : null} diff --git a/src/pages/content-management/components/practice-steps/SelectPracticeToAttachStep.tsx b/src/pages/content-management/components/practice-steps/SelectPracticeToAttachStep.tsx index 06ab36d..8ab237d 100644 --- a/src/pages/content-management/components/practice-steps/SelectPracticeToAttachStep.tsx +++ b/src/pages/content-management/components/practice-steps/SelectPracticeToAttachStep.tsx @@ -36,6 +36,7 @@ function publishStatusClass(status?: string | null): string { function matchesPracticeSearch( practice: ParentContextPractice, query: string, + isExamPrep: boolean, ): boolean { const tokens = getSearchTokens(query) if (tokens.length === 0) return true @@ -91,8 +92,11 @@ export function SelectPracticeToAttachStep({ }, [searchInput, unlinkedOnly, pageSize]) const filteredPractices = useMemo( - () => allPractices.filter((practice) => matchesPracticeSearch(practice, searchInput)), - [allPractices, searchInput], + () => + allPractices.filter((practice) => + matchesPracticeSearch(practice, searchInput, isExamPrep), + ), + [allPractices, searchInput, isExamPrep], ) const totalCount = filteredPractices.length @@ -199,7 +203,9 @@ export function SelectPracticeToAttachStep({ {practices.map((practice) => { const alreadyLinked = practiceAlreadyLinkedToParent(practice, targetParent) const isSelected = practice.id === selectedPracticeId - const parentsLabel = formatPracticeParentsSummary(practice.parents ?? []) + const parentsLabel = formatPracticeParentsSummary(practice.parents ?? [], { + isExamPrep, + }) return (
  • -
    - - setDraft((d) => ({ ...d, group_ids: groupIds }))} - /> -

    - Optional catalog groups for organizing this definition in the library. -

    -
    -
    -
    -
    Groups
    -
    {groupName || }
    -
    Status
    {draft.status}
    diff --git a/src/pages/faqs/FaqsPage.tsx b/src/pages/faqs/FaqsPage.tsx index 72b6c35..f1b0aef 100644 --- a/src/pages/faqs/FaqsPage.tsx +++ b/src/pages/faqs/FaqsPage.tsx @@ -49,6 +49,7 @@ import { FaqDeleteDialog } from "./components/FaqDeleteDialog" import { FaqAccessDenied } from "./components/FaqAccessDenied" import { FaqPublicPreviewDialog } from "./components/FaqPublicPreviewDialog" import { UnassignedLabel } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" type StatusFilter = "all" | FAQStatus @@ -333,7 +334,7 @@ export function FaqsPage() {

    - {faq.question} +

    diff --git a/src/pages/notifications/NotificationsPage.tsx b/src/pages/notifications/NotificationsPage.tsx index 2f78348..58043bb 100644 --- a/src/pages/notifications/NotificationsPage.tsx +++ b/src/pages/notifications/NotificationsPage.tsx @@ -29,6 +29,7 @@ import { countActiveFilters } from "../../lib/adminFilterUtils" import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { cn } from "../../lib/utils" import { SpinnerIcon } from "../../components/ui/spinner-icon" +import { SearchHighlight } from "../../components/SearchHighlight" import { useNavigate } from "react-router-dom" import { getNotifications, @@ -60,10 +61,12 @@ function NotificationItem({ notification, onToggleRead, toggling, + searchTerm = "", }: { notification: Notification onToggleRead: (id: string, currentlyRead: boolean) => void toggling: boolean + searchTerm?: string }) { const config = NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG const Icon = config.icon @@ -104,7 +107,10 @@ function NotificationItem({ notification.is_read ? "text-grayScale-600" : "text-grayScale-800", )} > - {getNotificationTitle(notification)} + {notification.level} @@ -116,7 +122,10 @@ function NotificationItem({ notification.is_read ? "text-grayScale-400" : "text-grayScale-600", )} > - {getNotificationMessage(notification)} +

    @@ -754,12 +763,18 @@ export function NotificationsPage() { n.is_read ? "text-grayScale-600" : "text-grayScale-800", )} > - {getNotificationTitle(n)} +

    - {getNotificationMessage(n)} +

    diff --git a/src/pages/payments/PaymentsPage.tsx b/src/pages/payments/PaymentsPage.tsx index 2bc9f29..980b0c2 100644 --- a/src/pages/payments/PaymentsPage.tsx +++ b/src/pages/payments/PaymentsPage.tsx @@ -64,6 +64,7 @@ import type { import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" import { UnassignedLabel } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" const STATUS_FILTERS: { value: PaymentStatus; label: string }[] = [ { value: "PENDING", label: "Pending" }, @@ -570,22 +571,40 @@ export function PaymentsPage() { {paginatedPayments.map((payment) => ( -

    #{payment.id}

    +

    + +

    - {payment.transaction_id || payment.session_id || } + {payment.transaction_id || payment.session_id ? ( + + ) : ( + + )}

    - {paymentCustomerName(payment)} +

    - {payment.user_email || `User #${payment.user_id}`} +

    - {payment.plan_name || `Plan #${payment.plan_id}`} +

    {payment.plan_category && (

    diff --git a/src/pages/personas/PersonasPage.tsx b/src/pages/personas/PersonasPage.tsx index 195e23e..ea4722a 100644 --- a/src/pages/personas/PersonasPage.tsx +++ b/src/pages/personas/PersonasPage.tsx @@ -11,6 +11,7 @@ import { } from "lucide-react" import { toast } from "sonner" import { listPersonas, updatePersona } from "../../api/personas.api" +import { SearchHighlight } from "../../components/SearchHighlight" import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel" import { Badge } from "../../components/ui/badge" import { Button } from "../../components/ui/button" @@ -309,10 +310,12 @@ export function PersonasPage() { /> -

    {persona.name}

    +

    + +

    {persona.description ? (

    - {persona.description} +

    ) : null}
    diff --git a/src/pages/role-management/RolesListPage.tsx b/src/pages/role-management/RolesListPage.tsx index 81c2f69..d8adc19 100644 --- a/src/pages/role-management/RolesListPage.tsx +++ b/src/pages/role-management/RolesListPage.tsx @@ -1,7 +1,5 @@ import { useCallback, useEffect, useMemo, useState } from "react" -import { useNavigate } from "react-router-dom" import { - Plus, Search, Shield, ShieldCheck, @@ -28,7 +26,6 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, } from "../../components/ui/dialog" import { - getRoles, getRoleDetail, getAllPermissions, setRolePermissions, @@ -36,6 +33,7 @@ import { deleteRole, bulkDeactivateRole, bulkReactivateRole, + fetchAllRoles, } from "../../api/rbac.api" import type { Role, RoleDetail, RolePermission } from "../../types/rbac.types" import { cn } from "../../lib/utils" @@ -45,9 +43,12 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon" import { InviteTeamMemberDialog } from "./components/InviteTeamMemberDialog" import { SuperAdminOnly } from "../../components/access/AdminAccessGates" import { STAFF_TEAM_ROLE_OPTIONS } from "../../lib/teamRoles" +import { + matchesRoleManagementCategory, + type RoleManagementCategory, +} from "../../lib/rbacRoleCategories" export function RolesListPage() { - const navigate = useNavigate() const staffRoleNames = useMemo( () => new Set(STAFF_TEAM_ROLE_OPTIONS.map((o) => o.value)), [], @@ -55,7 +56,7 @@ export function RolesListPage() { // List state const [roles, setRoles] = useState([]) - const [total, setTotal] = useState(0) + const [roleCategoryFilter, setRoleCategoryFilter] = useState("team") const [page, setPage] = useState(1) const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [query, setQuery] = useState("") @@ -105,23 +106,24 @@ export function RolesListPage() { return () => clearTimeout(timer) }, [query]) + useEffect(() => { + setPage(1) + }, [roleCategoryFilter]) + const fetchRoles = useCallback(async () => { setLoading(true) setError(null) try { - const res = await getRoles({ + const all = await fetchAllRoles({ query: debouncedQuery || undefined, - page, - page_size: pageSize, }) - setRoles(res.data.data.roles ?? []) - setTotal(res.data.data.total ?? 0) + setRoles(all) } catch { setError("Failed to load roles.") } finally { setLoading(false) } - }, [debouncedQuery, page, pageSize]) + }, [debouncedQuery]) // Fetch roles useEffect(() => { @@ -339,25 +341,51 @@ export function RolesListPage() { return entries.sort(([a], [b]) => a.localeCompare(b)) }, [allPermissionsMap, permSearch]) + const filteredRoles = useMemo( + () => roles.filter((role) => matchesRoleManagementCategory(role.name, roleCategoryFilter)), + [roles, roleCategoryFilter], + ) + + const total = filteredRoles.length const totalPages = Math.max(1, Math.ceil(total / pageSize)) + const safePage = Math.min(page, totalPages) + + const paginatedRoles = useMemo(() => { + const start = (safePage - 1) * pageSize + return filteredRoles.slice(start, start + pageSize) + }, [filteredRoles, safePage, pageSize]) return (
    {/* Header */} -
    -
    -

    Role Management

    -

    - Manage roles and their permissions. -

    -
    - +
    +

    Role Management

    +

    + Manage roles and their permissions. +

    +
    + +
    + {( + [ + { value: "team" as const, label: "Team member roles" }, + { value: "user" as const, label: "User roles" }, + ] as const + ).map(({ value, label }) => ( + + ))}
    {/* Search */} @@ -398,7 +426,7 @@ export function RolesListPage() { {/* Roles grid */} {!loading && !error && ( <> - {roles.length === 0 ? ( + {filteredRoles.length === 0 ? ( @@ -406,13 +434,15 @@ export function RolesListPage() {

    {debouncedQuery ? `No roles match "${debouncedQuery}".` - : "Create a new role to get started."} + : roleCategoryFilter === "team" + ? "No team member roles match this view." + : "No user roles match this view."}

    ) : (
    - {roles.map((role) => ( + {paginatedRoles.map((role) => (
    - Showing {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total} roles + Showing {(safePage - 1) * pageSize + 1}–{Math.min(safePage * pageSize, total)} of {total} roles @@ -583,20 +613,20 @@ export function RolesListPage() { variant="outline" size="icon" className="h-8 w-8" - disabled={page <= 1} - onClick={() => setPage((p) => p - 1)} + disabled={safePage <= 1} + onClick={() => setPage((p) => Math.max(1, p - 1))} > - {page} / {totalPages} + {safePage} / {totalPages} diff --git a/src/pages/team/TeamManagementPage.tsx b/src/pages/team/TeamManagementPage.tsx index aee8eff..0c6205e 100644 --- a/src/pages/team/TeamManagementPage.tsx +++ b/src/pages/team/TeamManagementPage.tsx @@ -34,6 +34,7 @@ import { InviteTeamMemberDialog } from "../role-management/components/InviteTeam import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export"; import { teamMemberExportQuery } from "../../lib/csvExportFilters"; import { UnassignedLabel } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" function formatDate(dateStr: string): string { return new Date(dateStr).toLocaleDateString("en-US", { @@ -372,9 +373,14 @@ export function TeamManagementPage() {
    - {member.first_name} {member.last_name} + +
    +
    +
    -
    {member.email}
    diff --git a/src/pages/user-log/components/ActivityLogListPanel.tsx b/src/pages/user-log/components/ActivityLogListPanel.tsx index e275d9a..369ee9a 100644 --- a/src/pages/user-log/components/ActivityLogListPanel.tsx +++ b/src/pages/user-log/components/ActivityLogListPanel.tsx @@ -65,7 +65,7 @@ import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination" import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types" import { ActorCell, ActorLabel } from "./ActorLabel" import { ActorHoverCard } from "./ActorHoverCard" -import { UnassignedLabel } from "../../../lib/displayValue" +import { UnassignedLabel, DisplayValue } from "../../../lib/displayValue" export interface ActivityLogListPanelProps { /** When set, locks the list to actions by this actor (user profile audit tab). */ @@ -451,7 +451,7 @@ export function ActivityLogListPanel({ scrollable ? "whitespace-nowrap" : "max-w-[280px] truncate", )} > - {log.message || } +

    {showActorColumn ? ( diff --git a/src/pages/user-management/DeletionRequestsPage.tsx b/src/pages/user-management/DeletionRequestsPage.tsx index 513899b..7a17a3a 100644 --- a/src/pages/user-management/DeletionRequestsPage.tsx +++ b/src/pages/user-management/DeletionRequestsPage.tsx @@ -28,6 +28,7 @@ import type { import type { Role } from "../../types/rbac.types" import { mapDeletionRequestApiItem } from "../../types/user.types" import { UnassignedLabel } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" const stateBadge: Record = { PENDING: "bg-amber-100 text-amber-700", @@ -540,10 +541,21 @@ export function DeletionRequestsPage() {

    - {item.first_name} {item.last_name} + +

    +

    + +

    +

    + {item.phone_number ? ( + + ) : ( + + )}

    -

    {item.email}

    -

    {item.phone_number || }

    {item.role || }

    diff --git a/src/pages/user-management/UserDetailPage.tsx b/src/pages/user-management/UserDetailPage.tsx index 545c8d8..c472dd4 100644 --- a/src/pages/user-management/UserDetailPage.tsx +++ b/src/pages/user-management/UserDetailPage.tsx @@ -36,6 +36,17 @@ import { UserLearningActivitySection } from "./components/UserLearningActivitySe import { UserAccountActivitySection } from "./components/UserAccountActivitySection"; import { UserSubscriptionsSection } from "./components/UserSubscriptionsSection"; import { DisplayValue, NOT_ASSIGNED_LABEL, UnassignedLabel, displayValue, isUnassignedLabel } from "../../lib/displayValue" +import { + displayUserAgeGroup, + displayUserOccupation, + displayUserRegion, + displayUserEducationLevel, + displayUserLearningGoal, + displayUserLanguageChallenge, + displayUserLanguageGoal, + displayUserFavouriteTopic, + displayUserCountry, +} from "../../lib/userProfileFieldDisplay" const activityIcons = { completed: CheckCircle2, @@ -72,12 +83,6 @@ function formatStatusLabel(status: string): string { .join(" "); } -function formatAgeGroup(ageGroup: string): string { - const value = ageGroup.trim(); - if (!value) return NOT_ASSIGNED_LABEL; - return value.replace(/_/g, "-"); -} - function formatDate(dateStr: string | null | undefined): string { if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL; const date = new Date(dateStr); @@ -334,8 +339,8 @@ export function UserDetailPage() { const contactFields = [ { icon: Mail, label: "Email", value: displayValue(user.email) }, - { icon: Globe, label: "Country", value: displayValue(user.country) }, - { icon: MapPin, label: "Region", value: displayValue(user.region) }, + { icon: Globe, label: "Country", value: displayUserCountry(user.country) }, + { icon: MapPin, label: "Region", value: displayUserRegion(user.region) }, ]; return ( @@ -416,7 +421,7 @@ export function UserDetailPage() { } /> - } /> +
    @@ -468,27 +473,23 @@ export function UserDetailPage() {
    - } /> - - } /> - } /> - } /> + + + + +
    - {user.learning_goal.trim() ? ( - <> - -
    -

    - Learning goal -

    -
    - {user.learning_goal.trim()} -
    -
    - - ) : null} + +
    +

    + Learning goal +

    +
    + {displayUserLearningGoal(user.learning_goal)} +
    +
    diff --git a/src/pages/user-management/UsersListPage.tsx b/src/pages/user-management/UsersListPage.tsx index 3b25460..3e85461 100644 --- a/src/pages/user-management/UsersListPage.tsx +++ b/src/pages/user-management/UsersListPage.tsx @@ -27,6 +27,8 @@ import { USER_FILTER_COUNTRIES, USER_FILTER_ETHIOPIA_REGIONS } from "../../data/ import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export" import { usersExportQuery } from "../../lib/csvExportFilters" import { UnassignedLabel } from "../../lib/displayValue" +import { SearchHighlight } from "../../components/SearchHighlight" +import { displayUserRegion, displayUserCountry } from "../../lib/userProfileFieldDisplay" function formatJoinedAt(iso: string): string { if (!iso?.trim()) return "unassigned" @@ -151,7 +153,6 @@ export function UsersListPage() { name: string nextStatus: UserStatus } | null>(null) - const [statusFilter, setStatusFilter] = useState("") const [createdAfterLocal, setCreatedAfterLocal] = useState("") const [createdBeforeLocal, setCreatedBeforeLocal] = useState("") const [countryFilter, setCountryFilter] = useState("") @@ -182,7 +183,6 @@ export function UsersListPage() { const res = await getUsers({ page, page_size: pageSize, - status: statusFilter || undefined, query: search || undefined, created_after: toRfc3339FromDatetimeLocal(createdAfterLocal), created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal), @@ -222,7 +222,6 @@ export function UsersListPage() { }, [ page, pageSize, - statusFilter, search, createdAfterLocal, createdBeforeLocal, @@ -333,7 +332,6 @@ export function UsersListPage() { } const activeFilterCount = countActiveFilters([ - { value: statusFilter }, { value: createdAfterLocal }, { value: createdBeforeLocal }, { value: countryFilter }, @@ -342,7 +340,6 @@ export function UsersListPage() { ]) const clearFilters = () => { - setStatusFilter("") setCreatedAfterLocal("") setCreatedBeforeLocal("") setCountryFilter("") @@ -354,7 +351,6 @@ export function UsersListPage() { const exportParams = useMemo( () => usersExportQuery({ - status: statusFilter || undefined, query: search || undefined, created_after: toRfc3339FromDatetimeLocal(createdAfterLocal), created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal), @@ -367,7 +363,6 @@ export function UsersListPage() { subscription_status: subscriptionStatusFilter || undefined, }), [ - statusFilter, search, createdAfterLocal, createdBeforeLocal, @@ -385,8 +380,16 @@ export function UsersListPage() { } return (
    - {hasPhone ?
    {phone!.trim()}
    : null} - {hasEmail ?
    {email!.trim()}
    : null} + {hasPhone ? ( +
    + +
    + ) : null} + {hasEmail ? ( +
    + +
    + ) : null}
    ) } @@ -491,23 +494,6 @@ export function UsersListPage() {
    } > -
    -
    - - -
    -
    {renderContactDetails(u.phoneNumber, u.email)} - {u.country || } - {u.region || } + + {displayUserCountry(u.country)} + + + {displayUserRegion(u.region)} + {formatJoinedAt(u.createdAt)}