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 <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-08-06 13:59:32 +03:00
parent d16cb84006
commit 2b880f0386
48 changed files with 875 additions and 599 deletions

View File

@ -17,9 +17,11 @@ export const getRoles = (params?: GetRolesParams) =>
http.get<GetRolesResponse>("/rbac/roles", { params })
/** Fetch every RBAC role across paginated list responses. */
export async function fetchAllRoles(): Promise<Role[]> {
export async function fetchAllRoles(
params?: Pick<GetRolesParams, "query" | "is_system">,
): Promise<Role[]> {
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<Role[]> {
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 ?? [])]

View File

@ -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={<InitialAssessmentPage />}
/>
<Route
path="/new-content/question-types/groups/:groupId"
element={<QuestionTypeGroupDetailPage />}
/>
<Route
path="/new-content/question-types/:definitionId/create-practice"
element={<AddPracticeFlow />}

View File

@ -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<string, unknown>
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 ""
}

View File

@ -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(

View File

@ -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 <UnassignedLabel className={unassignedClassName} />
}
const asText = String(value)
if (query.trim()) {
return <SearchHighlight text={asText} query={query} className={className} />
}
return <span className={className}>{value}</span>
}
if (isUnassignedLabel(value)) {
return <UnassignedLabel className={unassignedClassName} />
}
return <span className={className}>{value!.trim()}</span>
const text = value!.trim()
if (query.trim()) {
return <SearchHighlight text={text} query={query} className={className} />
}
return <span className={className}>{text}</span>
}

View File

@ -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<ExamPrepCatalogCourseItem[]> {

View File

@ -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(

View File

@ -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<string | null> {
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`
}

View File

@ -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)
}

View File

@ -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<string, string> = {
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, string>,
): 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, string>,
): 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<string, number>()
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))
}

View File

@ -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 <UnassignedLabel />
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 (
<Card className="shadow-none flex flex-col">
<CardHeader className="pb-2">
<CardTitle className="text-sm">{title}</CardTitle>
</CardHeader>
<CardContent className="p-4 pt-0 flex-1 flex flex-col">
{sorted.length > 0 ? (
{merged.length > 0 ? (
<div
className="space-y-2.5 flex-1 overflow-y-auto overscroll-contain pr-1 max-h-[320px]"
>
{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 (
<div key={`${item.label}-${i}`}>
<div className="mb-1 flex items-center justify-between gap-2 text-xs">
@ -184,7 +190,7 @@ function BreakdownList({
className="h-2 w-2 shrink-0 rounded-full"
style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }}
/>
<span className="truncate text-grayScale-600" title={titleText}>
<span className="truncate text-grayScale-600" title={displayLabel}>
{displayLabel}
</span>
</div>
@ -634,21 +640,25 @@ export function AnalyticsPage() {
title="Learning goal"
data={users.by_learning_goal ?? []}
total={users.total_users}
formatRowLabel={displayUserLearningGoal}
/>
<BreakdownList
title="Language challenge"
data={users.by_language_challange ?? []}
total={users.total_users}
formatRowLabel={displayUserLanguageChallenge}
/>
<BreakdownList
title="Occupation"
data={users.by_occupation ?? []}
total={users.total_users}
formatRowLabel={displayUserOccupation}
/>
<BreakdownList
title="Age group"
data={users.by_age_group ?? []}
total={users.total_users}
formatRowLabel={displayUserAgeGroup}
/>
<BreakdownList
title="Gender"
@ -660,22 +670,26 @@ export function AnalyticsPage() {
title="Education level"
data={users.by_education_level ?? []}
total={users.total_users}
formatRowLabel={displayUserEducationLevel}
/>
<BreakdownList
title="Country"
data={users.by_country ?? []}
total={users.total_users}
formatRowLabel={displayUserCountry}
/>
<BreakdownList
title="Region"
data={users.by_region ?? []}
total={users.total_users}
formatRowLabel={displayUserRegion}
/>
{(users.by_knowledge_level?.length ?? 0) > 0 ? (
<BreakdownList
title="Knowledge level"
data={users.by_knowledge_level ?? []}
total={users.total_users}
formatRowLabel={displayUserKnowledgeLevel}
/>
) : null}
</div>
@ -689,12 +703,14 @@ export function AnalyticsPage() {
title="Learning goal"
data={users.by_learning_goal ?? []}
total={users.total_users}
formatRowLabel={displayUserLearningGoal}
scrollable
/>
<BreakdownList
title="Language challenge"
data={users.by_language_challange ?? []}
total={users.total_users}
formatRowLabel={displayUserLanguageChallenge}
scrollable
/>
</div>

View File

@ -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() {
>
<TableCell className="max-w-md py-3.5">
<div className="truncate text-sm font-semibold text-grayScale-700">
{course.title}
<SearchHighlight text={course.title} query={search} />
</div>
{course.description && (
<div className="mt-1 truncate text-xs text-grayScale-400">
{course.description}
<SearchHighlight text={course.description} query={search} />
</div>
)}
</TableCell>
<TableCell className="py-3.5 text-sm text-grayScale-500">
{course.category_name}
<SearchHighlight text={course.category_name} query={search} />
</TableCell>
<TableCell className="hidden py-3.5 md:table-cell">
<Badge

View File

@ -7,6 +7,7 @@ import { Input } from "../../components/ui/input"
import { getCourseCategories } from "../../api/courses.api"
import type { CourseCategory } from "../../types/course.types"
import { cn } from "../../lib/utils"
import { SearchHighlight } from "../../components/SearchHighlight"
const contentSections = [
{
@ -271,10 +272,10 @@ export function ContentOverviewPage() {
</div>
<CardTitle className="text-[15px] font-semibold text-grayScale-700 transition-colors duration-200 group-hover:text-brand-600">
{section.title}
<SearchHighlight text={section.title} query={searchQuery} />
</CardTitle>
<CardDescription className="mt-1 text-[13px] leading-relaxed text-grayScale-400">
{section.description}
<SearchHighlight text={section.description} query={searchQuery} />
</CardDescription>
</CardHeader>

View File

@ -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<CourseCategory[]>([])
@ -163,7 +164,7 @@ export function CourseCategoryPage() {
<FolderOpen className="h-6 w-6" />
</div>
<CardTitle className="text-lg font-semibold text-grayScale-600 transition-colors group-hover:text-grayScale-700">
{category.name}
<SearchHighlight text={category.name} query={searchQuery} />
</CardTitle>
</CardHeader>

View File

@ -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() {
/>
</div>
<h3 className="text-lg font-bold tracking-tight text-[#0F172A]">
{module.name}
<SearchHighlight text={module.name} query={moduleSearch} />
</h3>
<p className="text-[12px] font-medium leading-snug text-grayScale-400 line-clamp-3">
{module.description?.trim()
? module.description
: <UnassignedLabel />}
<DisplayValue
value={module.description}
query={moduleSearch}
/>
</p>
</div>
</div>
@ -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`,

View File

@ -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() || <UnassignedLabel />,
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() {
/>
</div>
<h3 className="text-[18px] font-medium text-grayScale-900 transition-colors">
{unit.name}
<SearchHighlight text={unit.name} query={listSearch} />
</h3>
<p className="text-[12px] text-grayScale-500 font-medium line-clamp-3">
{unit.description}
<DisplayValue value={unit.description} query={listSearch} />
</p>
</div>

View File

@ -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() || <UnassignedLabel />);
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}
</h1>
<ContentPageDescription className="text-[16px] font-medium text-grayScale-400">
{moduleDescription}
<DisplayValue value={moduleDescription} />
</ContentPageDescription>
</div>
@ -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}

View File

@ -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() {
<div className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-grayScale-50 text-grayScale-400 transition-colors group-hover:bg-brand-500 group-hover:text-white">
<BookOpen className="h-4 w-4" />
</div>
<p className="min-w-0 text-sm font-medium text-grayScale-600">{sub.name}</p>
<p className="min-w-0 text-sm font-medium text-grayScale-600">
<SearchHighlight text={sub.name} query={searchQuery} />
</p>
</div>
</TableCell>
<TableCell className="hidden lg:table-cell">
<span className="text-sm text-grayScale-600">{sub.category_name}</span>
<span className="text-sm text-grayScale-600">
<SearchHighlight text={sub.category_name} query={searchQuery} />
</span>
</TableCell>
<TableCell>
<p className="max-w-md truncate text-sm text-grayScale-600" title={sub.description || undefined}>
{sub.description?.trim() ? sub.description : <UnassignedLabel />}
<DisplayValue value={sub.description} query={searchQuery} />
</p>
</TableCell>
<TableCell className="hidden xl:table-cell tabular-nums text-sm text-grayScale-600">

View File

@ -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<ReturnType<typeof getExamPrepPracticeFull>>;
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);

View File

@ -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() {
/>
</div>
<h3 className="text-xl font-bold text-grayScale-700 line-clamp-2">
{program.name}
<SearchHighlight text={program.name} query={listSearch} />
</h3>
<p className="mt-2 text-sm leading-relaxed text-grayScale-500 line-clamp-4">
{program.description?.trim()
? program.description
: <UnassignedLabel />}
<DisplayValue value={program.description} query={listSearch} />
</p>
</div>
<Link

View File

@ -657,6 +657,7 @@ export function LessonPracticesPage() {
key={p.id}
practice={p}
statusUpdating={publishStatusUpdatingId === p.id}
searchQuery={listSearch}
onEdit={() => void navigate(editPracticeHref(p.id))}
onPublish={() =>
void handlePracticePublishStatus(p.id, "PUBLISHED")

View File

@ -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`,

View File

@ -49,25 +49,25 @@ export function NewContentPage() {
</div>
</div>
{/* Cards Grid */}
<div className="grid max-w-5xl gap-8 grid-cols-1 md:grid-cols-2">
{/* Cards Grid — equal-height cards with bottom-aligned actions */}
<div className="grid max-w-5xl gap-8 grid-cols-1 items-stretch md:grid-cols-2">
{/* Learn English Card */}
<Card className="overflow-hidden border-none shadow-soft">
<div className="flex h-56 items-center justify-center bg-white/50">
<Card className="flex h-full flex-col overflow-hidden border-none shadow-soft">
<div className="flex h-56 shrink-0 items-center justify-center bg-white/50">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-brand-100/30">
<Mic className="h-10 w-10 text-brand-500" />
</div>
</div>
<CardContent className="border-t border-grayScale-200 bg-white p-8 text-center">
<CardContent className="flex flex-1 flex-col border-t border-grayScale-200 bg-white p-8 text-center">
<h3 className="text-xl font-bold text-grayScale-700">
Learn English
</h3>
<p className="mt-3 text-sm leading-relaxed text-grayScale-500">
<p className="mt-3 flex-1 text-sm leading-relaxed text-grayScale-500">
Manage structured English learning content based on levels and
modules.
</p>
<Link to="/new-content/learn-english">
<Button className="mt-8 h-12 w-full rounded-[6px] bg-brand-500 text-base font-semibold ">
<Link to="/new-content/learn-english" className="mt-8 block w-full">
<Button className="h-12 w-full rounded-[6px] bg-brand-500 text-base font-semibold">
Manage Learn English
</Button>
</Link>
@ -75,19 +75,19 @@ export function NewContentPage() {
</Card>
{/* Courses Card */}
<Card className="overflow-hidden border-none shadow-soft">
<div className="flex h-56 items-center justify-center bg-white/50">
<Card className="flex h-full flex-col overflow-hidden border-none shadow-soft">
<div className="flex h-56 shrink-0 items-center justify-center bg-white/50">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-brand-100/30">
<Mic className="h-10 w-10 text-brand-500" />
</div>
</div>
<CardContent className="border-t border-grayScale-200 bg-white p-8 text-center">
<CardContent className="flex flex-1 flex-col border-t border-grayScale-200 bg-white p-8 text-center">
<h3 className="text-xl font-bold text-grayScale-700">Courses</h3>
<p className="mt-3 text-sm leading-relaxed text-grayScale-500">
<p className="mt-3 flex-1 text-sm leading-relaxed text-grayScale-500">
Manage skill-based and Duolingo/IELTS courses.
</p>
<Link to="/new-content/courses" className="block w-full">
<Button className="mt-8 h-12 w-full rounded-[6px] bg-brand-500 text-base font-semibold ">
<Link to="/new-content/courses" className="mt-8 block w-full">
<Button className="h-12 w-full rounded-[6px] bg-brand-500 text-base font-semibold">
Manage Courses
</Button>
</Link>

View File

@ -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() {
/>
</div>
<h3 className="text-xl font-bold text-grayScale-700">
{course.name}
<SearchHighlight text={course.name} query={listSearch} />
</h3>
<p className="mt-2 text-[13px] leading-relaxed text-grayScale-500 line-clamp-2">
{course.description?.trim() ? course.description : <UnassignedLabel />}
<DisplayValue value={course.description} query={listSearch} />
</p>
<div className="my-6 grid grid-cols-3 gap-4 border-y border-grayScale-50 py-4">

View File

@ -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() || <UnassignedLabel />,
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() || <UnassignedLabel />,
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 || <UnassignedLabel />,
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() {
</div>
) : null}
<h3 className="text-[18px] font-medium text-grayScale-900">
{course.name}
<SearchHighlight text={course.name} query={listSearch} />
</h3>
<p className="text-[14px] text-grayScale-500 font-medium">
{course.description}
<p className="text-[14px] text-grayScale-500 font-medium">
<DisplayValue value={course.description} query={listSearch} />
</p>
</div>

View File

@ -11,9 +11,9 @@ export function ProgramTypeSelectionPage() {
<h1 className="text-[28px] font-bold tracking-tight text-grayScale-900">
Courses
</h1>
<p className="max-w-2xl text-[15px] font-medium text-grayScale-500">
Organize courses under skill-based learning or English proficiency
exams. Select a program type to manage curriculum and modules.
<p className="max-w-2xl text-[15px] font-medium text-grayScale-500">
Organize courses under skill-based learning or English Proficiency
Exams. Select a program type to manage curriculum and modules.
</p>
</div>
@ -32,20 +32,20 @@ export function ProgramTypeSelectionPage() {
</div>
</div>
{/* Selection Cards Grid */}
<div className="flex flex-warp gap-10 pt-4">
{/* Selection Cards Grid — equal width/height, consistent content alignment */}
<div className="grid max-w-5xl grid-cols-1 items-stretch gap-8 pt-4 md:grid-cols-2">
{/* Skill-Based Courses Card */}
<Link to="/new-content/courses/skill-based" className="group h-full">
<div className="bg-white rounded-[6px] w-[500px] border border-grayScale-100 px-10 py-12 h-full transition-all flex flex-col items-start gap-10">
<div className="h-16 w-16 rounded-full bg-brand-50/10 flex items-center justify-center">
<div className="flex h-full flex-col items-start gap-10 rounded-[6px] border border-grayScale-100 bg-white px-10 py-12 transition-all">
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-full bg-brand-50/10">
<Brain className="h-8 w-8 text-brand-500" />
</div>
<div className="space-y-3 flex-1">
<div className="flex min-h-0 flex-1 flex-col space-y-3">
<h3 className="text-[20px] font-bold text-grayScale-900">
Skill-Based Courses
</h3>
<p className="text-[15px] leading-relaxed text-grayScale-500 font-medium">
<p className="flex-1 text-[15px] font-medium leading-relaxed text-grayScale-500">
Practice-focused communication and skills training. Create
modules for vocabulary, grammar, and real-world conversation
scenarios.
@ -54,20 +54,20 @@ export function ProgramTypeSelectionPage() {
</div>
</Link>
{/* Duolingo/IELTS Card */}
{/* English Proficiency Exams Card */}
<Link to="/new-content/courses/proficiency" className="group h-full">
<div className="bg-white w-[500px] rounded-[6px] border border-grayScale-100 px-10 py-12 h-full transition-all flex flex-col items-start gap-10">
<div className="h-16 w-16 rounded-full bg-brand-50/10 flex items-center justify-center">
<div className="flex h-full flex-col items-start gap-10 rounded-[6px] border border-grayScale-100 bg-white px-10 py-12 transition-all">
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-full bg-brand-50/10">
<GraduationCap className="h-8 w-8 text-brand-500" />
</div>
<div className="space-y-3 flex-1">
<div className="flex min-h-0 flex-1 flex-col space-y-3">
<h3 className="text-[20px] font-bold text-grayScale-900 transition-colors">
Duolingo/IELTS
English Proficiency Exams
</h3>
<p className="text-[15px] leading-relaxed text-grayScale-500 font-medium">
Duolingo/IELTS courses. Structure content by band scores,
sections, and mock tests.
<p className="flex-1 text-[15px] font-medium leading-relaxed text-grayScale-500">
English Proficiency Exams courses. Structure content by band
scores, sections, and mock tests.
</p>
</div>
</div>

View File

@ -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<QuestionTypeDefinition[]>([])
const [groups, setGroups] = useState<QuestionTypeDefinitionGroup[]>([])
const [groupsLoading, setGroupsLoading] = useState(true)
const [query, setQuery] = useState("")
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("all")
const [groupFilter, setGroupFilter] = useState<GroupFilter>("all")
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
const [offset, setOffset] = useState(0)
const [definitionPendingDelete, setDefinitionPendingDelete] = useState<QuestionTypeDefinition | null>(null)
const [deleteSubmitting, setDeleteSubmitting] = useState(false)
const [definitionForPractices, setDefinitionForPractices] = useState<QuestionTypeDefinition | null>(null)
const [groupFormOpen, setGroupFormOpen] = useState(false)
const [groupPendingEdit, setGroupPendingEdit] = useState<QuestionTypeDefinitionGroup | null>(null)
const [groupPendingDelete, setGroupPendingDelete] = useState<QuestionTypeDefinitionGroup | null>(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<number, number>()
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() {
</div>
</div>
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
<CardHeader
className={cn(
"px-6 py-5",
groupsSectionOpen ? "border-b border-grayScale-100" : "",
)}
>
<div className="flex flex-wrap items-center justify-between gap-3">
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-3 text-left"
onClick={() => setGroupsSectionOpen((open) => !open)}
aria-expanded={groupsSectionOpen}
>
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600">
<FolderOpen className="h-5 w-5" aria-hidden />
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<CardTitle className="text-base font-bold text-grayScale-900">Groups</CardTitle>
{!groupsSectionOpen && !groupsLoading ? (
<span className="rounded-full bg-grayScale-100 px-2 py-0.5 text-[11px] font-semibold text-grayScale-600">
{groups.length} group{groups.length === 1 ? "" : "s"}
</span>
) : null}
</div>
<p className="text-xs text-grayScale-500 mt-0.5">
{groupsSectionOpen
? "Organize definitions by subject, skill, or workflow"
: "Click to expand and manage groups"}
</p>
</div>
{groupsSectionOpen ? (
<ChevronUp className="h-5 w-5 shrink-0 text-grayScale-400" aria-hidden />
) : (
<ChevronDown className="h-5 w-5 shrink-0 text-grayScale-400" aria-hidden />
)}
</button>
<Button
type="button"
size="sm"
variant="outline"
className="shrink-0 rounded-[8px] border-grayScale-200"
onClick={() => {
setGroupPendingEdit(null)
setGroupFormOpen(true)
}}
>
<Plus className="mr-2 h-4 w-4" />
Create group
</Button>
</div>
</CardHeader>
{groupsSectionOpen ? (
<CardContent className="p-0">
{groupsLoading ? (
<div className="flex items-center justify-center gap-2 px-6 py-10 text-sm text-grayScale-500">
<SpinnerIcon className="h-5 w-5 text-brand-500" />
Loading groups…
</div>
) : groups.length === 0 ? (
<div className="px-6 py-10 text-center text-sm text-grayScale-500">
No groups yet. Create one to organize your question type catalog.
</div>
) : (
<ul className="divide-y divide-grayScale-100">
{groups.map((g) => (
<li
key={g.id}
className="flex flex-wrap items-center justify-between gap-3 px-6 py-4 hover:bg-grayScale-50/80"
>
<button
type="button"
className="min-w-0 flex-1 text-left"
onClick={() => navigate(`/new-content/question-types/groups/${g.id}`)}
>
<p className="font-semibold text-grayScale-900">{g.name}</p>
<p className="mt-0.5 text-xs text-grayScale-500">
{definitionCountByGroup.get(g.id) ?? 0} definition
{(definitionCountByGroup.get(g.id) ?? 0) === 1 ? "" : "s"}
{g.description ? ` · ${g.description}` : ""}
</p>
</button>
<div className="flex items-center gap-2">
<Badge
className={cn(
"border-none shadow-none text-[11px]",
g.status === "ACTIVE"
? "bg-[#F0FDF4] text-[#16A34A]"
: "bg-grayScale-100 text-grayScale-600",
)}
>
{g.status}
</Badge>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8"
onClick={() => {
setGroupFilter(g.id)
resetPagination()
}}
>
Filter
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => {
setGroupPendingEdit(g)
setGroupFormOpen(true)
}}
aria-label={`Edit ${g.name}`}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-grayScale-500 hover:text-red-600"
onClick={() => setGroupPendingDelete(g)}
aria-label={`Delete ${g.name}`}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</li>
))}
</ul>
)}
</CardContent>
) : null}
</Card>
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
<CardHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
<div className="flex flex-wrap items-center justify-between gap-3">
@ -452,7 +227,6 @@ export function QuestionTypeLibraryPage() {
disabled={loading}
onClick={() => {
void load()
void loadGroups()
}}
>
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
@ -527,39 +301,6 @@ export function QuestionTypeLibraryPage() {
/>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
Group
</span>
<FilterChip
label="All groups"
active={groupFilter === "all"}
disabled={loading}
onClick={() => {
setGroupFilter("all")
resetPagination()
}}
/>
<FilterChip
label={`Ungrouped (${ungroupedCount})`}
active={groupFilter === "ungrouped"}
disabled={loading}
onClick={() => {
setGroupFilter("ungrouped")
resetPagination()
}}
/>
{typeof groupFilter === "number" ? (
<FilterChip
label={questionTypeGroupLabel(groupFilter, groups)}
active
disabled={loading}
onClick={() => {
navigate(`/new-content/question-types/groups/${groupFilter}`)
}}
/>
) : null}
</div>
</div>
</AdminFiltersPanel>
</div>
@ -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() {
</CardContent>
</Card>
<QuestionTypeGroupFormDialog
open={groupFormOpen}
onOpenChange={setGroupFormOpen}
group={groupPendingEdit}
onSaved={() => {
void loadGroups()
void load()
}}
/>
<Dialog
open={groupPendingDelete !== null}
onOpenChange={(open) => !groupDeleteSubmitting && !open && setGroupPendingDelete(null)}
>
<DialogContent className="max-w-md rounded-2xl border-grayScale-200">
<DialogHeader>
<DialogTitle>Delete group?</DialogTitle>
<DialogDescription className="text-left">
Deleting &quot;{groupPendingDelete?.name}&quot; will not delete any question types.
Definitions will be removed from this group only; other group memberships are unchanged.
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 border-t border-grayScale-100 px-6 py-4 sm:justify-end">
<Button
type="button"
variant="outline"
disabled={groupDeleteSubmitting}
onClick={() => setGroupPendingDelete(null)}
>
Cancel
</Button>
<Button
type="button"
variant="destructive"
disabled={groupDeleteSubmitting}
onClick={() => void handleConfirmDeleteGroup()}
>
{groupDeleteSubmitting ? <SpinnerIcon className="h-4 w-4" /> : "Delete group"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<QuestionTypeDefinitionPracticesDialog
definition={definitionForPractices}
open={definitionForPractices !== null}

View File

@ -24,6 +24,7 @@ import { cn } from "../../lib/utils"
import { PageBackLink } from "../../components/navigation/PageBackLink"
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
import { UnassignedLabel } from "../../lib/displayValue"
import { SearchHighlight } from "../../components/SearchHighlight"
type QuestionTypeFilter = "all" | "MCQ" | "TRUE_FALSE" | "SHORT_ANSWER" | "AUDIO"
type DifficultyFilter = "all" | "EASY" | "MEDIUM" | "HARD"
@ -495,7 +496,7 @@ export function QuestionsPage() {
</TableCell>
<TableCell className="max-w-md py-3.5">
<div className="truncate text-sm font-medium text-grayScale-600">
{question.question_text}
<SearchHighlight text={question.question_text} query={searchQuery} />
</div>
{question.question_type === "MCQ" && (question.options?.length ?? 0) > 0 && (
<div className="mt-1 truncate text-xs text-grayScale-400">

View File

@ -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 ? (
<SearchHighlight
text={`${group.practiceTitle}${group.practiceId ? ` (#${group.practiceId})` : ""}`}
query={searchQuery}
/>
) : (
"Unknown practice"
)}
</label>
</div>
</div>
@ -1481,7 +1489,9 @@ export function SpeakingPage() {
onChange={() => toggleQuestionSelection(question.id)}
className="mt-1"
/>
<p className="text-sm font-medium leading-snug text-grayScale-800">{question.question_text}</p>
<p className="text-sm font-medium leading-snug text-grayScale-800">
<SearchHighlight text={question.question_text} query={searchQuery} />
</p>
</div>
<Button
variant="ghost"

View File

@ -50,7 +50,8 @@ import {
import { PracticeActionButton } from "./components/PracticeActionButton";
import { UnitPracticesPanel } from "./components/UnitPracticesPanel";
import { cn } from "../../lib/utils";
import { UnassignedLabel } from "../../lib/displayValue"
import { DisplayValue } from "../../lib/displayValue"
import { SearchHighlight } from "../../components/SearchHighlight"
export function UnitManagementPage() {
const navigate = useNavigate();
@ -210,7 +211,7 @@ export function UnitManagementPage() {
list.map((row, index) => ({
id: Number(row.id),
name: row.name?.trim() || `Module ${row.id}`,
description: row.description?.trim() || <UnassignedLabel />,
description: row.description?.trim() || "",
thumbnail: row.thumbnail?.trim() || "",
icon: row.icon?.trim() || "",
sortOrder: Number(row.sort_order ?? 0),
@ -524,10 +525,7 @@ export function UnitManagementPage() {
setSavingEdit(true);
try {
const existing = modules.find((m) => m.id === editingModuleId);
const preservedDescription =
existing?.description && existing.description !== "unassigned"
? existing.description
: null;
const preservedDescription = existing?.description?.trim() || null;
const minioThumbnail = await resolveToMinioUrl(editThumbnail);
const minioIcon = await resolveToMinioUrl(editIcon);
await updateExamPrepUnitModule(editingModuleId, {
@ -962,10 +960,10 @@ export function UnitManagementPage() {
/>
</div>
<h3 className="text-[16px] font-medium text-grayScale-900 leading-tight">
{module.name}
<SearchHighlight text={module.name} query={listSearch} />
</h3>
<p className="text-[12px] text-grayScale-500 font-medium line-clamp-2">
{module.description}
<DisplayValue value={module.description} query={listSearch} />
</p>
</div>
</div>

View File

@ -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")}

View File

@ -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({
</div>
<h3 className="line-clamp-3 min-h-[2.75rem] text-[14px] font-bold leading-snug text-[#0F172A]">
{practice.title}
<SearchHighlight text={practice.title} query={searchQuery} />
</h3>
<div className="mt-auto grid grid-cols-1 gap-2 pt-2">

View File

@ -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({
<Card className="group overflow-hidden border-grayScale-200 rounded-[12px] bg-white transition-all duration-300">
<div className="px-4 py-6 space-y-4">
<div className="flex items-start justify-between gap-2">
<h3 className="text-[18px] font-bold text-grayScale-900 leading-[1.2]">{display_name}</h3>
<h3 className="text-[18px] font-bold text-grayScale-900 leading-[1.2]">
<SearchHighlight text={display_name} query={searchQuery} />
</h3>
{is_system ? (
<Badge className="shrink-0 border-none bg-violet-100 text-violet-800 flex items-center gap-1">
<Shield className="h-3 w-3" />
@ -55,7 +60,9 @@ export function QuestionTypeCard({
)}
</div>
<p className="text-[12px] font-mono text-grayScale-500 break-all">#{id} · {definitionKey}</p>
<p className="text-[12px] font-mono text-grayScale-500 break-all">
<SearchHighlight text={`#${id} · ${definitionKey}`} query={searchQuery} />
</p>
<div className="flex flex-wrap items-center gap-2 text-grayScale-700 font-medium text-[14px]">
<Layers className="h-4 w-4 text-[#9E2891]" />

View File

@ -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")}

View File

@ -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({
</div>
<h3 className="line-clamp-2 min-h-[3rem] shrink-0 text-[16px] font-medium leading-snug text-grayScale-900">
{title}
<SearchHighlight text={title} query={searchQuery} />
</h3>
{hoverModuleActions ? (
<p className="mt-1 line-clamp-2 min-h-[2.5rem] shrink-0 text-[13px] leading-snug text-grayScale-500">
{description?.trim() ? description.trim() : "\u00a0"}
{description?.trim() ? (
<SearchHighlight text={description.trim()} query={searchQuery} />
) : (
"\u00a0"
)}
</p>
) : null}

View File

@ -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 (
<li key={practice.id}>
<button

View File

@ -4,7 +4,6 @@ import { Textarea } from "../../../../components/ui/textarea"
import { Select } from "../../../../components/ui/select"
import type { QuestionTypeDefinitionCreatePayload } from "../../../../types/questionTypeDefinition.types"
import type { FieldErrorMap } from "../../lib/questionTypeDefinitionValidation"
import { QuestionTypeGroupsMultiSelect } from "../QuestionTypeGroupSelect"
import { QuestionTypeStepFooter } from "./QuestionTypeStepFooter"
interface QuestionTypeBasicInfoStepProps {
@ -82,17 +81,6 @@ export function QuestionTypeBasicInfoStep({
/>
</div>
<div className="space-y-2 max-w-md">
<label className="text-[14px] font-medium text-grayScale-700 dark:text-grayScale-500">Groups</label>
<QuestionTypeGroupsMultiSelect
value={draft.group_ids ?? null}
onChange={(groupIds) => setDraft((d) => ({ ...d, group_ids: groupIds }))}
/>
<p className="text-grayScale-400 text-[13px] font-medium">
Optional catalog groups for organizing this definition in the library.
</p>
</div>
<div className="space-y-2 max-w-xs">
<label className="text-[14px] font-medium text-grayScale-700 dark:text-grayScale-500 flex items-center gap-1">
Status <span className="text-red-500">*</span>

View File

@ -1,4 +1,4 @@
import { useEffect, useState } from "react"
import { useState } from "react"
import { ArrowLeft, Loader2 } from "lucide-react"
import { useNavigate } from "react-router-dom"
import { toast } from "sonner"
@ -11,7 +11,6 @@ import {
updateQuestionTypeDefinition,
validateQuestionTypeDefinition,
} from "../../../../api/questionTypeDefinitions.api"
import { getQuestionTypeDefinitionGroups } from "../../../../api/questionTypeDefinitionGroups.api"
import type { QuestionTypeDefinitionCreatePayload } from "../../../../types/questionTypeDefinition.types"
import {
buildCreatePayload,
@ -19,7 +18,6 @@ import {
inferRuntimeQuestionType,
} from "../../lib/questionTypeDefinitionValidation"
import { slotLabel } from "./componentKindUi"
import { questionTypeGroupLabels } from "../../../../lib/questionTypeGroupIds"
import { UnassignedLabel } from "../../../../lib/displayValue"
interface QuestionTypeReviewPublishStepProps {
@ -40,26 +38,11 @@ export function QuestionTypeReviewPublishStep({
}: QuestionTypeReviewPublishStepProps) {
const navigate = useNavigate()
const [submitting, setSubmitting] = useState(false)
const [groupName, setGroupName] = useState<string>("")
const isEdit = editDefinitionId != null && editDefinitionId > 0
const payload = buildCreatePayload(draft)
const runtime = inferRuntimeQuestionType(payload.key, payload.response_component_kinds)
useEffect(() => {
if (!payload.group_ids?.length) {
setGroupName("Ungrouped")
return
}
getQuestionTypeDefinitionGroups()
.then((res) => {
setGroupName(questionTypeGroupLabels(payload.group_ids, res.groups))
})
.catch(() => {
setGroupName(payload.group_ids!.map((id) => `Group #${id}`).join(", "))
})
}, [payload.group_ids])
const submit = async (status: "ACTIVE" | "INACTIVE") => {
if (isEdit && saveDisabled) return
const body = { ...payload, status }
@ -134,10 +117,6 @@ export function QuestionTypeReviewPublishStep({
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Description</dt>
<dd className="font-medium text-grayScale-800 dark:text-grayScale-500 mt-1">{payload.description || <UnassignedLabel />}</dd>
</div>
<div>
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Groups</dt>
<dd className="font-medium text-grayScale-900 dark:text-grayScale-600 mt-1">{groupName || <UnassignedLabel />}</dd>
</div>
<div>
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Status</dt>
<dd className="font-medium text-grayScale-900 dark:text-grayScale-600 mt-1">{draft.status}</dd>

View File

@ -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() {
<TableRow key={faq.id}>
<TableCell className="max-w-xs">
<p className="line-clamp-2 font-medium text-grayScale-900">
{faq.question}
<SearchHighlight text={faq.question} query={query} />
</p>
</TableCell>
<TableCell>

View File

@ -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)}
<SearchHighlight
text={getNotificationTitle(notification)}
query={searchTerm}
/>
</span>
<Badge variant={getNotificationLevelBadge(notification.level)} className="text-[10px] px-1.5 py-0">
{notification.level}
@ -116,7 +122,10 @@ function NotificationItem({
notification.is_read ? "text-grayScale-400" : "text-grayScale-600",
)}
>
{getNotificationMessage(notification)}
<SearchHighlight
text={getNotificationMessage(notification)}
query={searchTerm}
/>
</p>
</div>
@ -754,12 +763,18 @@ export function NotificationsPage() {
n.is_read ? "text-grayScale-600" : "text-grayScale-800",
)}
>
{getNotificationTitle(n)}
<SearchHighlight
text={getNotificationTitle(n)}
query={searchTerm}
/>
</p>
</TableCell>
<TableCell className="hidden lg:table-cell">
<p className="max-w-sm truncate text-xs text-grayScale-500">
{getNotificationMessage(n)}
<SearchHighlight
text={getNotificationMessage(n)}
query={searchTerm}
/>
</p>
</TableCell>
<TableCell>

View File

@ -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) => (
<tr key={payment.id} className="group transition-colors hover:bg-grayScale-50/60">
<td className="whitespace-nowrap px-3 py-2.5 sm:px-4">
<p className="font-semibold text-grayScale-900">#{payment.id}</p>
<p className="font-semibold text-grayScale-900">
<SearchHighlight text={`#${payment.id}`} query={searchQuery} />
</p>
<p className="mt-0.5 max-w-[140px] truncate font-mono text-[11px] text-grayScale-500">
{payment.transaction_id || payment.session_id || <UnassignedLabel />}
{payment.transaction_id || payment.session_id ? (
<SearchHighlight
text={payment.transaction_id || payment.session_id || ""}
query={searchQuery}
/>
) : (
<UnassignedLabel />
)}
</p>
</td>
<td className="px-3 py-2.5 sm:px-4">
<p className="max-w-[150px] truncate font-medium text-grayScale-900">
{paymentCustomerName(payment)}
<SearchHighlight
text={paymentCustomerName(payment)}
query={searchQuery}
/>
</p>
<p className="mt-0.5 max-w-[150px] truncate text-xs text-grayScale-500">
{payment.user_email || `User #${payment.user_id}`}
<SearchHighlight
text={payment.user_email || `User #${payment.user_id}`}
query={searchQuery}
/>
</p>
</td>
<td className="px-3 py-2.5 sm:px-4">
<p className="max-w-[160px] truncate font-medium text-grayScale-800">
{payment.plan_name || `Plan #${payment.plan_id}`}
<SearchHighlight
text={payment.plan_name || `Plan #${payment.plan_id}`}
query={searchQuery}
/>
</p>
{payment.plan_category && (
<p className="mt-0.5 truncate text-[11px] text-grayScale-400">

View File

@ -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() {
/>
</TableCell>
<TableCell className="py-3.5">
<p className="text-sm font-semibold text-grayScale-700">{persona.name}</p>
<p className="text-sm font-semibold text-grayScale-700">
<SearchHighlight text={persona.name} query={query} />
</p>
{persona.description ? (
<p className="mt-0.5 line-clamp-2 text-xs text-grayScale-500">
{persona.description}
<SearchHighlight text={persona.description} query={query} />
</p>
) : null}
</TableCell>

View File

@ -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<Role[]>([])
const [total, setTotal] = useState(0)
const [roleCategoryFilter, setRoleCategoryFilter] = useState<RoleManagementCategory>("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 (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">Role Management</h1>
<p className="mt-1 text-sm text-grayScale-400">
Manage roles and their permissions.
</p>
</div>
<Button
onClick={() => navigate("/roles/add")}
className="bg-brand-500 hover:bg-brand-600"
>
<Plus className="h-4 w-4" />
Add New Role
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">Role Management</h1>
<p className="mt-1 text-sm text-grayScale-400">
Manage roles and their permissions.
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{(
[
{ value: "team" as const, label: "Team member roles" },
{ value: "user" as const, label: "User roles" },
] as const
).map(({ value, label }) => (
<button
key={value}
type="button"
onClick={() => setRoleCategoryFilter(value)}
className={cn(
"h-9 rounded-full px-3 text-xs font-semibold transition-colors",
roleCategoryFilter === value
? "bg-brand-500 text-white"
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
)}
>
{label}
</button>
))}
</div>
{/* Search */}
@ -398,7 +426,7 @@ export function RolesListPage() {
{/* Roles grid */}
{!loading && !error && (
<>
{roles.length === 0 ? (
{filteredRoles.length === 0 ? (
<Card className="shadow-none border border-dashed border-grayScale-200 bg-grayScale-50/60">
<CardContent className="flex flex-col items-center justify-center gap-2 py-16 text-center">
<Shield className="h-10 w-10 text-grayScale-300" />
@ -406,13 +434,15 @@ export function RolesListPage() {
<p className="text-xs text-grayScale-400">
{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."}
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{roles.map((role) => (
{paginatedRoles.map((role) => (
<Card
key={role.id}
className="overflow-hidden border border-grayScale-100 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md"
@ -553,7 +583,7 @@ export function RolesListPage() {
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-grayScale-100 pt-4 text-sm text-grayScale-500">
<div className="flex flex-wrap items-center gap-2">
<span>
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
</span>
<span className="hidden h-4 w-px bg-grayScale-200 sm:inline" />
<span className="flex items-center gap-2">
@ -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))}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="px-3 text-xs font-medium text-grayScale-600">
{page} / {totalPages}
{safePage} / {totalPages}
</span>
<Button
variant="outline"
size="icon"
className="h-8 w-8"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
disabled={safePage >= totalPages}
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
>
<ChevronRight className="h-4 w-4" />
</Button>

View File

@ -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() {
</Avatar>
<div>
<div className="font-medium text-grayScale-600">
{member.first_name} {member.last_name}
<SearchHighlight
text={`${member.first_name} ${member.last_name}`.trim()}
query={search}
/>
</div>
<div className="text-xs text-grayScale-400">
<SearchHighlight text={member.email ?? ""} query={search} />
</div>
<div className="text-xs text-grayScale-400">{member.email}</div>
</div>
</div>
</TableCell>

View File

@ -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 || <UnassignedLabel />}
<DisplayValue value={log.message} query={searchQuery} />
</p>
</TableCell>
{showActorColumn ? (

View File

@ -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<string, string> = {
PENDING: "bg-amber-100 text-amber-700",
@ -540,10 +541,21 @@ export function DeletionRequestsPage() {
<TableRow key={`${item.user_id}-${index}`} className="group">
<TableCell className="py-3.5">
<p className="text-sm font-medium text-grayScale-700">
{item.first_name} {item.last_name}
<SearchHighlight
text={`${item.first_name} ${item.last_name}`.trim()}
query={query}
/>
</p>
<p className="text-xs text-grayScale-500">
<SearchHighlight text={item.email ?? ""} query={query} />
</p>
<p className="text-xs text-grayScale-500">
{item.phone_number ? (
<SearchHighlight text={item.phone_number} query={query} />
) : (
<UnassignedLabel />
)}
</p>
<p className="text-xs text-grayScale-500">{item.email}</p>
<p className="text-xs text-grayScale-500">{item.phone_number || <UnassignedLabel />}</p>
</TableCell>
<TableCell className="py-3.5">
<p className="text-sm text-grayScale-700">{item.role || <UnassignedLabel />}</p>

View File

@ -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() {
<InfoRow label="Joined" value={formatDate(user.created_at)} />
<InfoRow label="Last login" value={formatDateTime(user.last_login, "Never")} />
<InfoRow label="Gender" value={<DisplayValue value={user.gender} />} />
<InfoRow label="Occupation" value={<DisplayValue value={user.occupation} />} />
<InfoRow label="Occupation" value={displayUserOccupation(user.occupation)} />
</div>
</CardContent>
</Card>
@ -468,27 +473,23 @@ export function UserDetailPage() {
</CardHeader>
<CardContent className="space-y-5">
<div className="grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">
<InfoItem label="Education level" value={<DisplayValue value={user.education_level} />} />
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
<InfoItem label="Favorite topic" value={<DisplayValue value={user.favoutite_topic} />} />
<InfoItem label="Language goal" value={<DisplayValue value={user.language_goal} />} />
<InfoItem label="Challenge" value={<DisplayValue value={user.language_challange} />} />
<InfoItem label="Education level" value={displayUserEducationLevel(user.education_level)} />
<InfoItem label="Age group" value={displayUserAgeGroup(user.age_group)} />
<InfoItem label="Favorite topic" value={displayUserFavouriteTopic(user.favoutite_topic)} />
<InfoItem label="Language goal" value={displayUserLanguageGoal(user.language_goal)} />
<InfoItem label="Challenge" value={displayUserLanguageChallenge(user.language_challange)} />
<InfoItem label="Role" value={formatRoleLabel(user.role)} />
</div>
{user.learning_goal.trim() ? (
<>
<Separator />
<div>
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
Learning goal
</p>
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-700">
{user.learning_goal.trim()}
</div>
</div>
</>
) : null}
<Separator />
<div>
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
Learning goal
</p>
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-700">
{displayUserLearningGoal(user.learning_goal)}
</div>
</div>
</CardContent>
</Card>

View File

@ -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 (
<div className="space-y-1 text-sm text-grayScale-600">
{hasPhone ? <div className="tabular-nums">{phone!.trim()}</div> : null}
{hasEmail ? <div className="break-all text-grayScale-500">{email!.trim()}</div> : null}
{hasPhone ? (
<div className="tabular-nums">
<SearchHighlight text={phone!.trim()} query={search} />
</div>
) : null}
{hasEmail ? (
<div className="break-all text-grayScale-500">
<SearchHighlight text={email!.trim()} query={search} />
</div>
) : null}
</div>
)
}
@ -491,23 +494,6 @@ export function UsersListPage() {
</div>
}
>
<div className="flex flex-wrap gap-3">
<div className="relative w-full sm:w-auto">
<select
value={statusFilter}
onChange={(e) => {
setStatusFilter(e.target.value)
setPage(1)
}}
className="h-9 w-full sm:w-auto appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
>
<option value="">All statuses</option>
<option value="ACTIVE">Active</option>
<option value="INACTIVE">Inactive</option>
</select>
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
<div className="flex flex-col gap-1">
<label htmlFor="filter-created-after" className="text-xs font-medium text-grayScale-500">
@ -660,15 +646,22 @@ export function UsersListPage() {
</AvatarFallback>
</Avatar>
<div className="font-medium text-grayScale-600">
{u.firstName} {u.lastName}
<SearchHighlight
text={`${u.firstName} ${u.lastName}`.trim()}
query={search}
/>
</div>
</div>
</TableCell>
<TableCell className="hidden md:table-cell align-top">
{renderContactDetails(u.phoneNumber, u.email)}
</TableCell>
<TableCell className="hidden md:table-cell text-grayScale-500">{u.country || <UnassignedLabel />}</TableCell>
<TableCell className="hidden md:table-cell text-grayScale-500">{u.region || <UnassignedLabel />}</TableCell>
<TableCell className="hidden md:table-cell text-grayScale-500">
{displayUserCountry(u.country)}
</TableCell>
<TableCell className="hidden md:table-cell text-grayScale-500">
{displayUserRegion(u.region)}
</TableCell>
<TableCell className="hidden md:table-cell text-sm text-grayScale-500 whitespace-nowrap">
{formatJoinedAt(u.createdAt)}
</TableCell>