diff --git a/src/api/http.ts b/src/api/http.ts index fea7cea..f690b0a 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -1,4 +1,5 @@ import axios, { type AxiosInstance, type AxiosError, type InternalAxiosRequestConfig } from "axios"; +import { toast } from "sonner"; import { teamRefresh } from "./teamRefresh.api"; import { TeamAuthError } from "../types/auth.types"; import { @@ -7,6 +8,7 @@ import { getRefreshToken, saveTeamSession, } from "../lib/teamAuthStorage"; +import { markApiErrorNotified, readApiResponseMessage } from "../lib/apiErrors"; const http: AxiosInstance = axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL, @@ -90,19 +92,9 @@ const shouldAttachApiAuth = (url?: string): boolean => { return requestOrigin === API_BASE_ORIGIN; }; -function readErrorMessage(data: unknown): string { - if (typeof data === "string") return data; - if (data && typeof data === "object") { - const record = data as Record; - if (typeof record.error === "string") return record.error; - if (typeof record.message === "string") return record.message; - } - return ""; -} - function isRefreshableAccessTokenError(error: AxiosError): boolean { if (error.response?.status !== 401) return false; - const message = readErrorMessage(error.response.data).toLowerCase(); + const message = readApiResponseMessage(error.response.data).toLowerCase(); return ( message.includes("access token expired") || message.includes("invalid access token") @@ -202,6 +194,16 @@ http.interceptors.response.use( } } + const skipErrorToast = + originalRequest.skipErrorToast || isAuthEndpointRequest(originalRequest.url); + if (!skipErrorToast && error.response) { + const message = readApiResponseMessage(error.response.data); + if (message) { + toast.error(message); + markApiErrorNotified(error); + } + } + return Promise.reject(error); }, ); diff --git a/src/api/rbac.api.ts b/src/api/rbac.api.ts index 2fc88ef..c0e1f55 100644 --- a/src/api/rbac.api.ts +++ b/src/api/rbac.api.ts @@ -10,11 +10,30 @@ import type { GetPermissionsResponse, BulkRoleDeactivateResponse, BulkRoleReactivateResponse, + Role, } from "../types/rbac.types" export const getRoles = (params?: GetRolesParams) => http.get("/rbac/roles", { params }) +/** Fetch every RBAC role across paginated list responses. */ +export async function fetchAllRoles(): Promise { + const pageSize = 50 + const firstRes = await getRoles({ page: 1, page_size: pageSize }) + const firstBatch = firstRes.data?.data?.roles ?? [] + const total = firstRes.data?.data?.total ?? firstBatch.length + const totalPages = Math.max(1, Math.ceil(total / pageSize)) + + if (totalPages === 1) return firstBatch + + const remaining = await Promise.all( + Array.from({ length: totalPages - 1 }, (_, idx) => + getRoles({ page: idx + 2, page_size: pageSize }), + ), + ) + return [...firstBatch, ...remaining.flatMap((res) => res.data?.data?.roles ?? [])] +} + export const getRoleDetail = (roleId: number) => http.get(`/rbac/roles/${roleId}`) diff --git a/src/api/team.api.ts b/src/api/team.api.ts index 4d7afc3..bda1ebe 100644 --- a/src/api/team.api.ts +++ b/src/api/team.api.ts @@ -155,7 +155,9 @@ export const changeTeamMemberPassword = (id: number, data: ChangeTeamMemberPassw /** POST /team/members/invite — send invitation email (permission: team.members.invite). */ export const inviteTeamMember = (data: InviteTeamMemberRequest) => - http.post("/team/members/invite", data) + http.post("/team/members/invite", data, { + skipErrorToast: true, + }) /** GET /team/invitations/verify?token= — public (accept-invite page). */ export const verifyTeamInvitation = (token: string) => diff --git a/src/assets/personas/amanuel.png b/src/assets/personas/amanuel.png new file mode 100644 index 0000000..91b42d1 Binary files /dev/null and b/src/assets/personas/amanuel.png differ diff --git a/src/assets/personas/aseffa.png b/src/assets/personas/aseffa.png new file mode 100644 index 0000000..afb75bf Binary files /dev/null and b/src/assets/personas/aseffa.png differ diff --git a/src/assets/personas/bethel.png b/src/assets/personas/bethel.png new file mode 100644 index 0000000..1461c76 Binary files /dev/null and b/src/assets/personas/bethel.png differ diff --git a/src/assets/personas/dawit.png b/src/assets/personas/dawit.png new file mode 100644 index 0000000..15b38c8 Binary files /dev/null and b/src/assets/personas/dawit.png differ diff --git a/src/assets/personas/hana.png b/src/assets/personas/hana.png new file mode 100644 index 0000000..c238cb6 Binary files /dev/null and b/src/assets/personas/hana.png differ diff --git a/src/assets/personas/liya.png b/src/assets/personas/liya.png new file mode 100644 index 0000000..77a0aae Binary files /dev/null and b/src/assets/personas/liya.png differ diff --git a/src/assets/personas/mahlet.png b/src/assets/personas/mahlet.png new file mode 100644 index 0000000..c8e20c0 Binary files /dev/null and b/src/assets/personas/mahlet.png differ diff --git a/src/assets/personas/nahom.png b/src/assets/personas/nahom.png new file mode 100644 index 0000000..92ee9d5 Binary files /dev/null and b/src/assets/personas/nahom.png differ diff --git a/src/components/content-management/DynamicSchemaSlotField.tsx b/src/components/content-management/DynamicSchemaSlotField.tsx index 319f6d7..3825d95 100644 --- a/src/components/content-management/DynamicSchemaSlotField.tsx +++ b/src/components/content-management/DynamicSchemaSlotField.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, @@ -199,7 +200,7 @@ function DynamicImageSlot({ toast.success("Image uploaded") } catch (e) { console.error(e) - toast.error("Failed to upload image") + notifyApiError(e, "Failed to upload image") } finally { setUploading(false) } @@ -220,7 +221,7 @@ function DynamicImageSlot({ toast.success("Image URL imported to storage") } catch (e) { console.error(e) - toast.error("Could not import image from URL") + notifyApiError(e, "Could not import image from URL") } finally { setUploading(false) } @@ -454,7 +455,7 @@ function DynamicAudioSlot({ toast.success("Audio uploaded") } catch (e) { console.error(e) - toast.error("Failed to upload audio") + notifyApiError(e, "Failed to upload audio") } finally { setUploading(false) } @@ -477,7 +478,7 @@ function DynamicAudioSlot({ toast.success("Audio URL imported to storage") } catch (e) { console.error(e) - toast.error("Could not import audio from URL") + notifyApiError(e, "Could not import audio from URL") } finally { setUploading(false) } @@ -783,7 +784,7 @@ function DynamicPdfSlot({ toast.success("PDF uploaded") } catch (e) { console.error(e) - toast.error("Failed to upload PDF") + notifyApiError(e, "Failed to upload PDF") } finally { setUploading(false) } diff --git a/src/components/content-management/PracticeQuestionEditorFields.tsx b/src/components/content-management/PracticeQuestionEditorFields.tsx index af67909..475960c 100644 --- a/src/components/content-management/PracticeQuestionEditorFields.tsx +++ b/src/components/content-management/PracticeQuestionEditorFields.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, @@ -330,7 +331,7 @@ export function PracticeQuestionEditorFields({ toast.success("Audio uploaded successfully") } catch (error) { console.error("Failed to upload audio:", error) - toast.error("Failed to upload audio file") + notifyApiError(error, "Failed to upload audio file") } finally { if (field === "voice_prompt") setUploadingVoice(false) else setUploadingSample(false) @@ -387,7 +388,7 @@ export function PracticeQuestionEditorFields({ else setSamplePreviewUrl(url) } catch (error) { console.error("Failed to resolve audio:", error) - toast.error("Could not import/resolve audio URL") + notifyApiError(error, "Could not import/resolve audio URL") } finally { if (field === "voice_prompt") setUploadingVoice(false) else setUploadingSample(false) @@ -419,7 +420,7 @@ export function PracticeQuestionEditorFields({ toast.success("Image uploaded successfully") } catch (error) { console.error("Failed to upload image:", error) - toast.error("Failed to upload image") + notifyApiError(error, "Failed to upload image") } finally { setUploadingImage(false) } @@ -435,7 +436,7 @@ export function PracticeQuestionEditorFields({ setImagePreviewUrl(resolved) } catch (error) { console.error("Failed to resolve image preview URL:", error) - toast.error("Could not resolve image preview URL") + notifyApiError(error, "Could not resolve image preview URL") } } @@ -704,7 +705,7 @@ export function PracticeQuestionEditorFields({ }) } catch (e) { console.error(e) - toast.error("Failed to load definition details") + notifyApiError(e, "Failed to load definition details") } finally { setDefinitionDetailLoading(false) } diff --git a/src/components/export/ExportCsvButton.tsx b/src/components/export/ExportCsvButton.tsx index 746f67e..28da5ff 100644 --- a/src/components/export/ExportCsvButton.tsx +++ b/src/components/export/ExportCsvButton.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { Download } from "lucide-react" import { useState } from "react" import { toast } from "sonner" @@ -43,7 +44,7 @@ export function ExportCsvButton({ const filename = await downloadCsvExport(exportPath, params, { resourceName }) toast.success(`Downloaded ${filename}`) } catch (e) { - toast.error(e instanceof Error ? e.message : "Export failed") + notifyApiError(e, "Export failed") } finally { setExporting(false) } diff --git a/src/components/navigation/PageBackLink.tsx b/src/components/navigation/PageBackLink.tsx new file mode 100644 index 0000000..321c3cb --- /dev/null +++ b/src/components/navigation/PageBackLink.tsx @@ -0,0 +1,39 @@ +import { ArrowLeft } from "lucide-react"; +import { useNavigate } from "react-router-dom"; +import { navigateBack } from "../../lib/navigateBack"; +import { cn } from "../../lib/utils"; + +type PageBackLinkProps = { + fallbackTo: string; + label?: string; + className?: string; + iconClassName?: string; +}; + +export function PageBackLink({ + fallbackTo, + label = "Back", + className, + iconClassName, +}: PageBackLinkProps) { + const navigate = useNavigate(); + + return ( + + ); +} diff --git a/src/components/notifications/EmailComposeFields.tsx b/src/components/notifications/EmailComposeFields.tsx index 2bc5641..84559b6 100644 --- a/src/components/notifications/EmailComposeFields.tsx +++ b/src/components/notifications/EmailComposeFields.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from "react" import { Link } from "react-router-dom" import { Eye, ExternalLink, RefreshCw } from "lucide-react" import { toast } from "sonner" +import { notifyApiError } from "../../lib/apiErrors" import { parseEmailTemplatePreviewResponse, previewEmailTemplate, @@ -123,10 +124,7 @@ export function EmailComposeFields({ if (!result) throw new Error("Empty preview response") setPreview(result) } catch (err: unknown) { - const msg = - (err as { response?: { data?: { message?: string } } })?.response?.data?.message ?? - "Failed to preview email template" - toast.error(msg) + notifyApiError(err, "Failed to preview email template") } finally { setPreviewLoading(false) } diff --git a/src/components/notifications/NotificationDeleteDialog.tsx b/src/components/notifications/NotificationDeleteDialog.tsx index 034cade..902bcaa 100644 --- a/src/components/notifications/NotificationDeleteDialog.tsx +++ b/src/components/notifications/NotificationDeleteDialog.tsx @@ -1,6 +1,7 @@ import { useState } from "react" import { Trash2 } from "lucide-react" import { toast } from "sonner" +import { notifyApiError } from "../../lib/apiErrors" import { deleteNotification } from "../../api/notifications.api" import { Button } from "../ui/button" import { @@ -43,12 +44,7 @@ export function NotificationDeleteDialog({ onDeleted?.(notification.id) } catch (e: unknown) { console.error(e) - const msg = - (e as { response?: { data?: { message?: string; error?: string } } })?.response - ?.data?.error ?? - (e as { response?: { data?: { message?: string } } })?.response?.data?.message ?? - "Failed to delete notification" - toast.error(msg) + notifyApiError(e, "Failed to delete notification") } finally { setDeleting(false) } diff --git a/src/components/personas/PersonaAvatar.tsx b/src/components/personas/PersonaAvatar.tsx new file mode 100644 index 0000000..5ff8155 --- /dev/null +++ b/src/components/personas/PersonaAvatar.tsx @@ -0,0 +1,43 @@ +import { cn } from "../../lib/utils" + +const SIZE_CLASSES = { + sm: "size-10", + md: "size-12", + lg: "size-16", + xl: "size-24", +} as const + +type PersonaAvatarProps = { + src: string + alt?: string + size?: keyof typeof SIZE_CLASSES + selected?: boolean + className?: string +} + +export function PersonaAvatar({ + src, + alt = "", + size = "md", + selected = false, + className, +}: PersonaAvatarProps) { + return ( +
+ {alt} +
+ ) +} diff --git a/src/components/profile/ProfileAvatarUpload.tsx b/src/components/profile/ProfileAvatarUpload.tsx index f35691e..cd45d3a 100644 --- a/src/components/profile/ProfileAvatarUpload.tsx +++ b/src/components/profile/ProfileAvatarUpload.tsx @@ -1,6 +1,7 @@ import { useCallback, useRef, useState, type ChangeEvent } from "react" import { Camera } from "lucide-react" import { toast } from "sonner" +import { notifyApiError } from "../../lib/apiErrors" import { uploadImageFile } from "../../api/files.api" import { updateTeamMe } from "../../api/team.api" import { SpinnerIcon } from "../ui/spinner-icon" @@ -53,10 +54,7 @@ export function ProfileAvatarUpload({ toast.success(updateRes.data.message || "Profile picture updated") } catch (err: unknown) { console.error(err) - const uploadMsg = - (err as { response?: { data?: { message?: string } } })?.response?.data - ?.message - toast.error(uploadMsg ?? "Failed to update profile picture") + notifyApiError(err, "Failed to update profile picture") } finally { setUploading(false) } diff --git a/src/components/topbar/NotificationDropdown.tsx b/src/components/topbar/NotificationDropdown.tsx index 5a419cf..4e5ab31 100644 --- a/src/components/topbar/NotificationDropdown.tsx +++ b/src/components/topbar/NotificationDropdown.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react" import { useNavigate } from "react-router-dom" import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react" @@ -207,7 +208,7 @@ export function NotificationDropdown() { next.delete(pending.notification.id) return next }) - toast.error("Failed to delete notification") + notifyApiError(err, "Failed to delete notification") } }, [commitDeleteNotification, selectedNotificationId]) @@ -282,7 +283,7 @@ export function NotificationDropdown() { } } else { setDetailError(true) - toast.error("Failed to load notification details") + notifyApiError(err, "Failed to load notification details") } } finally { setDetailLoading(false) diff --git a/src/components/ui/avatar.tsx b/src/components/ui/avatar.tsx index 45941df..2b2de9c 100644 --- a/src/components/ui/avatar.tsx +++ b/src/components/ui/avatar.tsx @@ -19,7 +19,11 @@ export const AvatarImage = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )) AvatarImage.displayName = AvatarPrimitive.Image.displayName diff --git a/src/hooks/useActivePersonas.ts b/src/hooks/useActivePersonas.ts index b7db317..688ca78 100644 --- a/src/hooks/useActivePersonas.ts +++ b/src/hooks/useActivePersonas.ts @@ -1,13 +1,15 @@ import { useCallback, useEffect, useState } from "react" -import { listActivePersonasForPicker } from "../api/personas.api" +import { getPersonaById, listActivePersonasForPicker } from "../api/personas.api" import { mapPersonaToCard, type PersonaCardModel } from "../lib/personaDisplay" type UseActivePersonasOptions = { limit?: number + /** Include this persona in the picker even when inactive or missing from the active list. */ + ensurePersonaId?: number | null } export function useActivePersonas(options: UseActivePersonasOptions = {}) { - const { limit = 200 } = options + const { limit = 200, ensurePersonaId = null } = options const [personas, setPersonas] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) @@ -16,7 +18,23 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) { setLoading(true) setError(null) try { - const list = await listActivePersonasForPicker(limit) + let list = await listActivePersonasForPicker(limit) + const ensureId = + ensurePersonaId != null && + Number.isFinite(ensurePersonaId) && + ensurePersonaId > 0 + ? ensurePersonaId + : null + if (ensureId != null && !list.some((persona) => persona.id === ensureId)) { + try { + const res = await getPersonaById(ensureId) + if (res.data) { + list = [res.data, ...list] + } + } catch { + // Keep active list only if the saved persona cannot be loaded. + } + } setPersonas(list.map(mapPersonaToCard)) } catch (e: unknown) { const msg = @@ -27,7 +45,7 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) { } finally { setLoading(false) } - }, [limit]) + }, [limit, ensurePersonaId]) useEffect(() => { void load() diff --git a/src/lib/apiErrors.ts b/src/lib/apiErrors.ts new file mode 100644 index 0000000..9193050 --- /dev/null +++ b/src/lib/apiErrors.ts @@ -0,0 +1,45 @@ +import axios from "axios" +import { toast } from "sonner" + +const API_ERROR_NOTIFIED = "__apiErrorNotified" + +export function readApiResponseMessage(data: unknown): string { + if (typeof data === "string") return data.trim() + if (data && typeof data === "object") { + const record = data as Record + if (typeof record.message === "string" && record.message.trim()) { + return record.message.trim() + } + if (typeof record.error === "string" && record.error.trim()) { + return record.error.trim() + } + } + return "" +} + +export function getApiErrorMessage(error: unknown, fallback: string): string { + if (axios.isAxiosError(error)) { + const message = readApiResponseMessage(error.response?.data) + if (message) return message + } + return fallback +} + +export function markApiErrorNotified(error: unknown): void { + if (error && typeof error === "object") { + ;(error as Record)[API_ERROR_NOTIFIED] = true + } +} + +export function wasApiErrorNotified(error: unknown): boolean { + return Boolean( + error && typeof error === "object" && (error as Record)[API_ERROR_NOTIFIED], + ) +} + +/** Show API `message`/`error` from failed requests, or a fallback when absent. */ +export function notifyApiError(error: unknown, fallback: string): void { + if (wasApiErrorNotified(error)) return + toast.error(getApiErrorMessage(error, fallback)) + markApiErrorNotified(error) +} diff --git a/src/lib/navigateBack.ts b/src/lib/navigateBack.ts new file mode 100644 index 0000000..b21c0dd --- /dev/null +++ b/src/lib/navigateBack.ts @@ -0,0 +1,14 @@ +import type { NavigateFunction } from "react-router-dom"; + +export function canNavigateBack(): boolean { + const idx = (window.history.state as { idx?: number } | null)?.idx; + return typeof idx === "number" && idx > 0; +} + +export function navigateBack(navigate: NavigateFunction, fallbackTo: string): void { + if (canNavigateBack()) { + navigate(-1); + return; + } + navigate(fallbackTo); +} diff --git a/src/lib/personaDisplay.ts b/src/lib/personaDisplay.ts index 449fb0c..923f365 100644 --- a/src/lib/personaDisplay.ts +++ b/src/lib/personaDisplay.ts @@ -2,6 +2,14 @@ import type { GetPersonasResponse, PersonaListItem, } from "../types/persona.types" +import amanuelAvatar from "../assets/personas/amanuel.png" +import aseffaAvatar from "../assets/personas/aseffa.png" +import bethelAvatar from "../assets/personas/bethel.png" +import dawitAvatar from "../assets/personas/dawit.png" +import hanaAvatar from "../assets/personas/hana.png" +import liyaAvatar from "../assets/personas/liya.png" +import mahletAvatar from "../assets/personas/mahlet.png" +import nahomAvatar from "../assets/personas/nahom.png" export type PersonaCardModel = { id: string @@ -10,12 +18,57 @@ export type PersonaCardModel = { avatar: string } -/** Soft, professional palette aligned with the admin brand (slate, indigo, violet). */ -const PERSONA_FALLBACK_BACKGROUNDS = "f1f5f9,e0e7ff,ede9fe,fdf4ff,ecfeff" +/** Realistic default portraits bundled with the admin app (see src/assets/personas). */ +const DEFAULT_PERSONA_AVATARS = [ + dawitAvatar, + mahletAvatar, + amanuelAvatar, + bethelAvatar, + liyaAvatar, + aseffaAvatar, + hanaAvatar, + nahomAvatar, +] as const + +const PERSONA_NAME_AVATARS: Record = { + dawit: dawitAvatar, + mahlet: mahletAvatar, + amanuel: amanuelAvatar, + bethel: bethelAvatar, + liya: liyaAvatar, + aseffa: aseffaAvatar, + hana: hanaAvatar, + nahom: nahomAvatar, +} + +function hashString(value: string): number { + let hash = 0 + for (let i = 0; i < value.length; i++) { + hash = (hash * 31 + value.charCodeAt(i)) >>> 0 + } + return hash +} + +function defaultPersonaAvatarUrl( + name: string, + personaId?: number | string, +): string { + const normalizedName = name.trim().toLowerCase() + const byName = PERSONA_NAME_AVATARS[normalizedName] + if (byName) return byName + + const numericId = personaId != null ? Number(personaId) : NaN + const index = + Number.isFinite(numericId) && numericId > 0 + ? (numericId - 1) % DEFAULT_PERSONA_AVATARS.length + : hashString(normalizedName || "persona") % DEFAULT_PERSONA_AVATARS.length + + return DEFAULT_PERSONA_AVATARS[index] +} /** - * Default avatar when `profile_picture` is null: professional illustrated portrait - * (DiceBear personas), not casual cartoon avataaars. + * Default avatar when `profile_picture` is null: realistic bundled portrait, + * matched by persona name when possible. */ export function personaAvatarUrl( profilePicture: string | null | undefined, @@ -24,12 +77,7 @@ export function personaAvatarUrl( ): string { const url = profilePicture?.trim() if (url) return url - const params = new URLSearchParams({ - seed: personaId != null ? `yimaru-persona-${personaId}` : `yimaru-persona-${name}`, - backgroundColor: PERSONA_FALLBACK_BACKGROUNDS, - radius: "50", - }) - return `https://api.dicebear.com/7.x/personas/svg?${params.toString()}` + return defaultPersonaAvatarUrl(name, personaId) } export function mapPersonaToCard(persona: PersonaListItem): PersonaCardModel { diff --git a/src/lib/practiceEditDirty.ts b/src/lib/practiceEditDirty.ts new file mode 100644 index 0000000..01bd83e --- /dev/null +++ b/src/lib/practiceEditDirty.ts @@ -0,0 +1,66 @@ +import type { + PracticeFormState, + PreservedQuestionSetFields, +} from "./practiceFullMapper" +import { dedupeParents } from "./practiceParents" + +export type PracticeEditDirtyInput = { + formData: PracticeFormState + selectedPersona: string | null + preservedQuestionSet: PreservedQuestionSetFields +} + +function normalizeQuestionRow(question: PracticeFormState["questions"][number]) { + return { + serverQuestionId: question.serverQuestionId ?? null, + displayOrder: question.displayOrder, + associatedQuestionId: question.associatedQuestionId ?? null, + associatedAnchorRowId: question.associatedAnchorRowId ?? null, + prerequisiteQuestionIds: question.prerequisiteQuestionIds ?? [], + stimulusBlockKey: question.stimulusBlockKey ?? null, + questionTypeDefinitionId: question.questionTypeDefinitionId ?? null, + text: String(question.text ?? "").trim(), + difficultyLevel: question.difficultyLevel, + points: Number(question.points), + dynamicFieldValues: question.dynamicFieldValues ?? {}, + mcqOptions: (question.mcqOptions ?? []).map((option) => ({ + text: String(option.text ?? "").trim(), + isCorrect: Boolean(option.isCorrect), + })), + trueFalseCorrect: question.trueFalseCorrect !== false, + shortAnswers: (question.shortAnswers ?? []).map((answer) => String(answer).trim()), + } +} + +export function buildPracticeEditSnapshot(input: PracticeEditDirtyInput): string { + const { formData, selectedPersona, preservedQuestionSet } = input + + return JSON.stringify({ + title: formData.title.trim(), + description: formData.description.trim(), + storyImageUrl: formData.storyImageUrl.trim(), + shuffleQuestions: Boolean(formData.shuffleQuestions), + tips: formData.tips.trim(), + authoringProfile: formData.authoringProfile, + stimulusBlocks: formData.stimulusBlocks, + parents: dedupeParents(formData.parents), + questions: [...formData.questions] + .map(normalizeQuestionRow) + .sort((a, b) => a.displayOrder - b.displayOrder), + selectedPersona: selectedPersona?.trim() || null, + preservedQuestionSet: { + timeLimitMinutes: preservedQuestionSet.timeLimitMinutes, + passingScore: preservedQuestionSet.passingScore, + introVideoUrl: preservedQuestionSet.introVideoUrl.trim(), + status: preservedQuestionSet.status, + }, + }) +} + +export function hasPracticeEditChanges( + initialSnapshot: string | null, + current: PracticeEditDirtyInput, +): boolean { + if (!initialSnapshot) return false + return buildPracticeEditSnapshot(current) !== initialSnapshot +} diff --git a/src/lib/practiceFullMapper.ts b/src/lib/practiceFullMapper.ts index d237d12..b3a9e5f 100644 --- a/src/lib/practiceFullMapper.ts +++ b/src/lib/practiceFullMapper.ts @@ -308,6 +308,7 @@ function normalizePracticeFullQuestionSet(raw: unknown): PracticeFullQuestionSet owner_type: pickStr(record, "owner_type", "OwnerType", "ownerType") || undefined, owner_id: pickNum(record, "owner_id", "OwnerId", "ownerId") ?? undefined, persona: pickStr(record, "persona", "Persona") || null, + persona_id: pickNum(record, "persona_id", "PersonaId", "personaId"), shuffle_questions: Boolean( record.shuffle_questions ?? record.ShuffleQuestions ?? false, ), @@ -565,6 +566,25 @@ function mapFullQuestionToFormRow( } } +function parsePersonaIdValue(value: unknown): number | null { + if (value == null) return null + const n = Number(value) + return Number.isFinite(n) && n > 0 ? n : null +} + +export function resolvePracticePersonaId( + practice: PracticeFullPractice, + questionSet: PracticeFullQuestionSet, +): number | null { + const fromPractice = parsePersonaIdValue(practice.persona_id) + if (fromPractice != null) return fromPractice + + const fromQuestionSet = parsePersonaIdValue(questionSet.persona_id) + if (fromQuestionSet != null) return fromQuestionSet + + return parsePersonaIdValue(questionSet.persona) +} + export function mapPracticeFullToFormState( data: PracticeFullData, typeDefinitions: QuestionTypeDefinition[], @@ -618,10 +638,7 @@ export function mapPracticeFullToFormState( parents: parentsFromPractice(practice), questions: formQuestions, }, - personaId: - practice.persona_id != null && Number.isFinite(practice.persona_id) - ? practice.persona_id - : null, + personaId: resolvePracticePersonaId(practice, question_set), preservedQuestionSet: { timeLimitMinutes: question_set.time_limit_minutes ?? null, passingScore: question_set.passing_score ?? null, diff --git a/src/lib/practiceParentTitles.ts b/src/lib/practiceParentTitles.ts index 45ab17c..e7fa253 100644 --- a/src/lib/practiceParentTitles.ts +++ b/src/lib/practiceParentTitles.ts @@ -30,6 +30,8 @@ export function practiceParentKey(parent: PracticeParent): string { } function kindLabel(kind: PracticeParentKind): string { + if (kind === "CATALOG_COURSE") return "Catalog course" + if (kind === "UNIT") return "Unit" if (kind === "COURSE") return "Course" if (kind === "MODULE") return "Module" return "Lesson" @@ -98,12 +100,32 @@ async function resolveExamPrepCourseTitles( const res = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 }) for (const course of res.data?.data?.catalog_courses ?? []) { if (ids.has(course.id)) { - map.set(`COURSE:${course.id}`, course.name?.trim() || `Course #${course.id}`) + const title = course.name?.trim() || `Course #${course.id}` + map.set(`CATALOG_COURSE:${course.id}`, title) + map.set(`COURSE:${course.id}`, title) ids.delete(course.id) } } } +async function resolveExamPrepUnitTitles( + ids: Set, + map: PracticeParentTitleMap, +): Promise { + if (ids.size === 0) return + const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 }) + for (const course of coursesRes.data?.data?.catalog_courses ?? []) { + if (ids.size === 0) break + const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 }) + for (const unit of unitsRes.data?.data?.units ?? []) { + if (ids.has(unit.id)) { + map.set(`UNIT:${unit.id}`, unit.name?.trim() || `Unit #${unit.id}`) + ids.delete(unit.id) + } + } + } +} + async function resolveLearnEnglishModuleTitles( ids: Set, map: PracticeParentTitleMap, @@ -230,18 +252,23 @@ export async function resolvePracticeParentTitles( const normalized = dedupeParents(parents) const unresolvedCourses = new Set() + const unresolvedCatalogCourses = new Set() + const unresolvedUnits = new Set() const unresolvedModules = new Set() const unresolvedLessons = new Set() for (const parent of normalized) { if (map.has(practiceParentKey(parent))) continue if (parent.parent_kind === "COURSE") unresolvedCourses.add(parent.parent_id) + if (parent.parent_kind === "CATALOG_COURSE") unresolvedCatalogCourses.add(parent.parent_id) + if (parent.parent_kind === "UNIT") unresolvedUnits.add(parent.parent_id) if (parent.parent_kind === "MODULE") unresolvedModules.add(parent.parent_id) if (parent.parent_kind === "LESSON") unresolvedLessons.add(parent.parent_id) } await resolveLearnEnglishCourseTitles(unresolvedCourses, map) - await resolveExamPrepCourseTitles(unresolvedCourses, map) + await resolveExamPrepCourseTitles(unresolvedCatalogCourses, map) + await resolveExamPrepUnitTitles(unresolvedUnits, map) await resolveLearnEnglishModuleTitles(unresolvedModules, map) await resolveExamPrepModuleTitles(unresolvedModules, map) await resolveLearnEnglishLessonTitles(unresolvedLessons, map) diff --git a/src/lib/teamRoles.ts b/src/lib/teamRoles.ts index 7971b72..5cf9d80 100644 --- a/src/lib/teamRoles.ts +++ b/src/lib/teamRoles.ts @@ -41,3 +41,26 @@ export function formatTeamRoleLabel(teamRole: string): string { if (found) return found.label return teamRole.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) } + +/** Role name sent to POST /team/members/invite (used in invitation emails). */ +export function teamRoleNameForInvite(teamRole: string, explicitName?: string): string { + const named = explicitName?.trim() + if (named) return named + + const fromOptions = TEAM_ROLE_OPTIONS.find( + (o) => o.value === teamRole || o.value === teamRole.toUpperCase(), + ) + if (fromOptions) return fromOptions.label + + return teamRole.trim() +} + +export type TeamRoleOption = { value: string; label: string } + +export function rbacRolesToTeamRoleOptions(roles: Role[]): TeamRoleOption[] { + const names = Array.from( + new Set(roles.map((role) => role.name.trim()).filter(Boolean)), + ).sort((a, b) => a.localeCompare(b)) + + return names.map((name) => ({ value: name, label: name })) +} diff --git a/src/pages/ProfilePage.tsx b/src/pages/ProfilePage.tsx index 9fb9059..d955d1c 100644 --- a/src/pages/ProfilePage.tsx +++ b/src/pages/ProfilePage.tsx @@ -9,6 +9,7 @@ import { User, } from "lucide-react" import { toast } from "sonner" +import { notifyApiError } from "../lib/apiErrors" import { getTeamMe, updateTeamMe } from "../api/team.api" import { Badge } from "../components/ui/badge" import { Button } from "../components/ui/button" @@ -193,10 +194,7 @@ export function ProfilePage() { toast.success(res.data.message || "Profile updated successfully") } catch (err) { console.error("Failed to update profile", err) - const message = - (err as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update profile" - toast.error(message) + notifyApiError(err, "Failed to update profile") } finally { setSaving(false) } diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index f4eb152..b6b0cc5 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../lib/apiErrors" import React, { useEffect, useState } from "react"; import { Eye, @@ -81,10 +82,7 @@ function SecurityTab({ memberId }: { memberId: number }) { logoutToLogin({ passwordChanged: true }); return; } catch (e: unknown) { - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update password."; - toast.error(msg); + notifyApiError(e, "Failed to update password."); } finally { setSaving(false); } diff --git a/src/pages/auth/AcceptInvitePage.tsx b/src/pages/auth/AcceptInvitePage.tsx index 87be79d..1423ea4 100644 --- a/src/pages/auth/AcceptInvitePage.tsx +++ b/src/pages/auth/AcceptInvitePage.tsx @@ -12,6 +12,7 @@ import { User, } from "lucide-react" import { toast } from "sonner" +import { notifyApiError } from "../../lib/apiErrors" import { acceptTeamInvitation, parseVerifyInvitation, @@ -129,10 +130,7 @@ export function AcceptInvitePage() { toast.success(res.data?.message ?? "Account setup complete. You can sign in now.") navigate("/login", { replace: true }) } catch (e: unknown) { - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to complete setup" - toast.error(msg) + notifyApiError(e, "Failed to complete setup") } finally { setSubmitting(false) } diff --git a/src/pages/content-management/AddNewLessonPage.tsx b/src/pages/content-management/AddNewLessonPage.tsx index e3d29bb..0e8264e 100644 --- a/src/pages/content-management/AddNewLessonPage.tsx +++ b/src/pages/content-management/AddNewLessonPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useMemo, useState, type ChangeEvent } from "react" import { ArrowLeft, ArrowRight, Check, GripVertical, Plus, Rocket, Trash2, Upload } from "lucide-react" import { Link, useLocation, useNavigate, useParams } from "react-router-dom" @@ -161,7 +162,7 @@ export function AddNewLessonPage() { toast.success("Intro video uploaded") } catch (error) { console.error("Failed to upload lesson intro video:", error) - toast.error("Failed to upload intro video") + notifyApiError(error, "Failed to upload intro video") } finally { setUploadingIntroVideo(false) } @@ -193,7 +194,7 @@ export function AddNewLessonPage() { toast.success("Intro video URL imported") } catch (error) { console.error("Failed to import intro video URL:", error) - toast.error("Failed to import intro video URL") + notifyApiError(error, "Failed to import intro video URL") } finally { setUploadingIntroVideo(false) } diff --git a/src/pages/content-management/AddNewPracticePage.tsx b/src/pages/content-management/AddNewPracticePage.tsx index f20cb8b..f824b3c 100644 --- a/src/pages/content-management/AddNewPracticePage.tsx +++ b/src/pages/content-management/AddNewPracticePage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useMemo, useRef, useState, type ChangeEvent } from "react"; import { Link, useLocation, useParams, useNavigate } from "react-router-dom"; import { @@ -228,7 +229,7 @@ export function AddNewPracticePage() { }); } catch (error) { console.error("Failed to upload intro video:", error); - toast.error("Failed to upload intro video"); + notifyApiError(error, "Failed to upload intro video"); } finally { setUploadingIntroVideo(false); } @@ -259,7 +260,7 @@ export function AddNewPracticePage() { }); } catch (error) { console.error("Failed to import intro video URL:", error); - toast.error("Failed to import intro video URL"); + notifyApiError(error, "Failed to import intro video URL"); } finally { setImportingIntroVideoUrl(false); } diff --git a/src/pages/content-management/AddPracticeFlow.tsx b/src/pages/content-management/AddPracticeFlow.tsx index d415b72..9a20fd4 100644 --- a/src/pages/content-management/AddPracticeFlow.tsx +++ b/src/pages/content-management/AddPracticeFlow.tsx @@ -1,11 +1,8 @@ +import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors" import { useEffect, useMemo, useState } from "react"; -import { - Link, - useNavigate, - useParams, - useSearchParams, -} from "react-router-dom"; -import { ArrowLeft } from "lucide-react"; +import { useNavigate, useParams, useSearchParams } from "react-router-dom"; +import { PageBackLink } from "../../components/navigation/PageBackLink"; +import { navigateBack } from "../../lib/navigateBack"; import { toast } from "sonner"; import { Button } from "../../components/ui/button"; import { Stepper } from "../../components/ui/stepper"; @@ -15,7 +12,6 @@ import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition. import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api"; import { emptyDynamicFieldValuesForDefinition } from "../../lib/learnEnglishDefinitionQuestion"; import { - learnEnglishPracticeApiErrorMessage, validateLearnEnglishQuestionsWithDefinitions, } from "../../lib/learnEnglishPracticePublish"; import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator"; @@ -213,6 +209,8 @@ export function AddPracticeFlow() { isFromQuestionType, ]); + const goBack = () => navigateBack(navigate, backPath); + const [currentStep, setCurrentStep] = useState(1); const [isPublished, setIsPublished] = useState(false); const [submitting, setSubmitting] = useState(false); @@ -279,7 +277,7 @@ export function AddPracticeFlow() { if (!cancelled) setTypeDefinitions(list); } catch (e) { if (!cancelled) { - setDefinitionsError(learnEnglishPracticeApiErrorMessage(e)); + setDefinitionsError(getApiErrorMessage(e, "Failed to load question type definitions")); setTypeDefinitions([]); } } finally { @@ -506,9 +504,7 @@ export function AddPracticeFlow() { toast.success("Practice created successfully"); setIsPublished(true); } catch (e) { - toast.error("Could not save practice", { - description: learnEnglishPracticeApiErrorMessage(e), - }); + notifyApiError(e, "Could not save practice"); } finally { setSubmitting(false); } @@ -547,7 +543,7 @@ export function AddPracticeFlow() {

diff --git a/src/pages/content-management/AddQuestionPage.tsx b/src/pages/content-management/AddQuestionPage.tsx index 1f9759b..0ad9934 100644 --- a/src/pages/content-management/AddQuestionPage.tsx +++ b/src/pages/content-management/AddQuestionPage.tsx @@ -1,6 +1,8 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useEffect, useState } from "react" import { useNavigate, useParams } from "react-router-dom" import { ArrowLeft, Plus, X } from "lucide-react" +import { navigateBack } from "../../lib/navigateBack" import { toast } from "sonner" import { Button } from "../../components/ui/button" import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card" @@ -128,7 +130,7 @@ export function AddQuestionPage() { }) } catch (error) { console.error("Failed to load question:", error) - toast.error("Failed to load question details") + notifyApiError(error, "Failed to load question details") } finally { setLoading(false) } @@ -339,7 +341,7 @@ export function AddQuestionPage() { navigate("/content/questions") } catch (error) { console.error("Failed to save question:", error) - toast.error("Failed to save question") + notifyApiError(error, "Failed to save question") } finally { setSubmitting(false) } @@ -351,7 +353,7 @@ export function AddQuestionPage() { diff --git a/src/pages/content-management/AllCoursesPage.tsx b/src/pages/content-management/AllCoursesPage.tsx index 32b6682..022ed8b 100644 --- a/src/pages/content-management/AllCoursesPage.tsx +++ b/src/pages/content-management/AllCoursesPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useEffect, useState } from "react" import { useNavigate } from "react-router-dom" import { Search, Plus, RefreshCw, Edit2, ToggleLeft, ToggleRight, BookOpen, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react" @@ -32,6 +33,7 @@ import { countActiveFilters } from "../../lib/adminFilterUtils" 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" type CourseWithCategory = Course & { category_name: string } @@ -173,9 +175,7 @@ export function AllCoursesPage() { await fetchAllCourses() } catch (err: any) { console.error("Failed to create course:", err) - toast.error("Failed to create sub-category", { - description: err?.response?.data?.message || "Please try again.", - }) + notifyApiError(err, "Failed to create sub-category") } finally { setCreating(false) } @@ -188,7 +188,7 @@ export function AllCoursesPage() { await fetchAllCourses() } catch (err) { console.error("Failed to update course status:", err) - toast.error("Failed to update sub-category status") + notifyApiError(err, "Failed to update sub-category status") } finally { setTogglingId(null) } @@ -222,9 +222,7 @@ export function AllCoursesPage() { await fetchAllCourses() } catch (err: any) { console.error("Failed to update course:", err) - toast.error("Failed to update sub-category", { - description: err?.response?.data?.message || "Please try again.", - }) + notifyApiError(err, "Failed to update sub-category") } finally { setUpdating(false) } @@ -262,6 +260,7 @@ export function AllCoursesPage() { return (
+ {/* Header */}
diff --git a/src/pages/content-management/CourseCategoryPage.tsx b/src/pages/content-management/CourseCategoryPage.tsx index 08f04b5..617b8d5 100644 --- a/src/pages/content-management/CourseCategoryPage.tsx +++ b/src/pages/content-management/CourseCategoryPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useEffect, useState } from "react" import { Link } from "react-router-dom" import { FolderOpen, RefreshCw, BookOpen, Plus, Trash2 } from "lucide-react" @@ -371,13 +372,8 @@ export function CourseCategoryPage() { setPendingSubCategories([]) setCreateOpen(false) fetchCategories() - } catch (err: any) { - const message = - err?.response?.data?.message || - "Failed to create category. Please try again." - toast.error("Could not create category", { - description: message, - }) + } catch (err: unknown) { + notifyApiError(err, "Could not create category") } finally { setCreating(false) } @@ -415,9 +411,8 @@ export function CourseCategoryPage() { toast.success("Category deleted") setDeleteTarget(null) await fetchCategories() - } catch (err: any) { - const message = err?.response?.data?.message || "Failed to delete category." - toast.error("Could not delete category", { description: message }) + } catch (err: unknown) { + notifyApiError(err, "Could not delete category") } finally { setDeleting(false) } diff --git a/src/pages/content-management/CourseDetailPage.tsx b/src/pages/content-management/CourseDetailPage.tsx index e3d3201..11903cc 100644 --- a/src/pages/content-management/CourseDetailPage.tsx +++ b/src/pages/content-management/CourseDetailPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useState } from "react"; import { ArrowLeft, @@ -282,18 +283,14 @@ export function CourseDetailPage() { } else { console.error(modulesOutcome.reason); setModules([]); - toast.error("Could not load modules", { - description: "Check your connection or try again.", - }); + notifyApiError(err, "Could not load modules"); } } catch (e) { console.error(e); setError("Failed to load course"); setCourse(null); setModules([]); - toast.error("Could not load course", { - description: "Check your connection or try again.", - }); + notifyApiError(e, "Could not load course"); } finally { setLoading(false); } @@ -378,10 +375,7 @@ export function CourseDetailPage() { ); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update practice status"; - toast.error(msg); + notifyApiError(e, "Failed to update practice status"); } finally { setPublishStatusPracticeId(null); } @@ -406,10 +400,7 @@ export function CourseDetailPage() { ); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module status"; - toast.error(msg); + notifyApiError(e, "Failed to update module status"); } finally { setPublishStatusModuleId(null); } @@ -434,10 +425,7 @@ export function CourseDetailPage() { ); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module access tier"; - toast.error(msg); + notifyApiError(e, "Failed to update module access tier"); } finally { setAccessTierModuleId(null); } @@ -474,10 +462,7 @@ export function CourseDetailPage() { await loadPage(); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module"; - toast.error(msg); + notifyApiError(e, "Failed to update module"); } finally { setSavingModuleEdit(false); } @@ -493,10 +478,7 @@ export function CourseDetailPage() { await loadPage(); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to delete module"; - toast.error(msg); + notifyApiError(e, "Failed to delete module"); } finally { setDeletingModuleInFlight(false); } diff --git a/src/pages/content-management/CourseFlowBuilderPage.tsx b/src/pages/content-management/CourseFlowBuilderPage.tsx index 69c69f4..cbbd681 100644 --- a/src/pages/content-management/CourseFlowBuilderPage.tsx +++ b/src/pages/content-management/CourseFlowBuilderPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useEffect, useMemo, useState } from "react" import { ChevronDown, @@ -28,6 +29,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca import { Button } from "../../components/ui/button" import { Select } from "../../components/ui/select" import { Badge } from "../../components/ui/badge" +import { PageBackLink } from "../../components/navigation/PageBackLink" import { getCourseCategories, getCoursesByCategory, @@ -226,7 +228,7 @@ export function CourseFlowBuilderPage() { const all = sortByDisplayOrder(res.data.data.categories ?? []) setCategories(all) } catch { - toast.error("Failed to load course categories.") + notifyApiError(err, "Failed to load course categories.") } finally { setLoading(false) } @@ -263,7 +265,7 @@ export function CourseFlowBuilderPage() { setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: items })) setSelectedCourseId(items[0]?.id ?? null) } catch { - toast.error("Failed to load course sub-categories.") + notifyApiError(err, "Failed to load course sub-categories.") } finally { setLoadingCourses(false) } @@ -351,7 +353,7 @@ export function CourseFlowBuilderPage() { }) setVideosBySubCourse(videoMap) } catch { - toast.error("Failed to load course flow detail.") + notifyApiError(err, "Failed to load course flow detail.") setLearningPath(null) } finally { setLoadingPath(false) @@ -402,7 +404,7 @@ export function CourseFlowBuilderPage() { [subCourseId]: videos, })) } catch { - toast.error("Failed to load practice sets for course.") + notifyApiError(err, "Failed to load practice sets for course.") } finally { setLoadingPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: false })) } @@ -429,7 +431,7 @@ export function CourseFlowBuilderPage() { await reorderCategories(toReorderItems(reordered)) } catch (err: any) { setCategories(previous) - toast.error(err?.response?.data?.message || "Failed to reorder categories.") + notifyApiError(err, "Failed to reorder categories.") } finally { setSavingKey(null) } @@ -455,7 +457,7 @@ export function CourseFlowBuilderPage() { await reorderCourses(toReorderItems(reordered)) } catch (err: any) { setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: previous })) - toast.error(err?.response?.data?.message || "Failed to reorder courses.") + notifyApiError(err, "Failed to reorder courses.") } finally { setSavingKey(null) } @@ -481,7 +483,7 @@ export function CourseFlowBuilderPage() { await reorderSubModules(toReorderItems(reordered)) } catch (err: any) { setLearningPath((prev) => (prev ? { ...prev, sub_courses: previous } : prev)) - toast.error(err?.response?.data?.message || "Failed to reorder sub-modules.") + notifyApiError(err, "Failed to reorder sub-modules.") } finally { setSavingKey(null) } @@ -526,7 +528,7 @@ export function CourseFlowBuilderPage() { } : prev, ) - toast.error(err?.response?.data?.message || "Failed to reorder videos.") + notifyApiError(err, "Failed to reorder videos.") } finally { setSavingKey(null) } @@ -552,7 +554,7 @@ export function CourseFlowBuilderPage() { await reorderPractices(toReorderItems(reordered)) } catch (err: any) { setPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: previous })) - toast.error(err?.response?.data?.message || "Failed to reorder practices.") + notifyApiError(err, "Failed to reorder practices.") } finally { setSavingKey(null) } @@ -569,6 +571,7 @@ export function CourseFlowBuilderPage() { return (
+

diff --git a/src/pages/content-management/CourseManagementPage.tsx b/src/pages/content-management/CourseManagementPage.tsx index be634ee..cc35210 100644 --- a/src/pages/content-management/CourseManagementPage.tsx +++ b/src/pages/content-management/CourseManagementPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Link, useParams, useNavigate } from "react-router-dom"; import { @@ -183,7 +184,7 @@ export function CourseManagementPage() { ); } catch (error) { console.error(error); - toast.error("Failed to load units"); + notifyApiError(error, "Failed to load units"); setUnits([]); } finally { setUnitsLoading(false); @@ -212,10 +213,7 @@ export function CourseManagementPage() { nextStatus === "PUBLISHED" ? "Course published" : "Course saved as draft", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course status"; - toast.error(message); + notifyApiError(error, "Failed to update course status"); } finally { setCatalogCoursePublishStatusUpdating(false); } @@ -239,10 +237,7 @@ export function CourseManagementPage() { nextStatus === "PUBLISHED" ? "Unit published" : "Unit saved as draft", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update unit status"; - toast.error(message); + notifyApiError(error, "Failed to update unit status"); } finally { setPublishStatusUpdatingId(null); } @@ -264,10 +259,7 @@ export function CourseManagementPage() { nextTier === "PREMIUM" ? "Unit set to Premium" : "Unit set to Free", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update unit access tier"; - toast.error(message); + notifyApiError(error, "Failed to update unit access tier"); } finally { setAccessTierUpdatingId(null); } @@ -328,10 +320,7 @@ export function CourseManagementPage() { toast.success("Thumbnail uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail"); } finally { setUploadingThumbnail(false); } @@ -373,10 +362,7 @@ export function CourseManagementPage() { setAddUnitOpen(false); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to create unit"; - toast.error(message); + notifyApiError(error, "Failed to create unit"); } finally { setCreating(false); } @@ -394,10 +380,7 @@ export function CourseManagementPage() { } } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload URL to MinIO"; - toast.error(message); + notifyApiError(error, "Failed to upload URL to MinIO"); } finally { setUploadingThumbnail(false); } @@ -415,10 +398,7 @@ export function CourseManagementPage() { } } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload URL to MinIO"; - toast.error(message); + notifyApiError(error, "Failed to upload URL to MinIO"); } finally { setUploadingEditThumbnail(false); } @@ -458,10 +438,7 @@ export function CourseManagementPage() { toast.success("Thumbnail uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail"); } finally { setUploadingEditThumbnail(false); } @@ -504,10 +481,7 @@ export function CourseManagementPage() { closeEditUnit(); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update unit"; - toast.error(message); + notifyApiError(error, "Failed to update unit"); } finally { setSavingEdit(false); } @@ -523,10 +497,7 @@ export function CourseManagementPage() { setDeletingUnitId(null); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to delete unit"; - toast.error(message); + notifyApiError(error, "Failed to delete unit"); } finally { setDeletingUnit(false); } diff --git a/src/pages/content-management/CourseModuleDetailPage.tsx b/src/pages/content-management/CourseModuleDetailPage.tsx index e63a13b..b88d79b 100644 --- a/src/pages/content-management/CourseModuleDetailPage.tsx +++ b/src/pages/content-management/CourseModuleDetailPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ArrowLeft, Plus, Video } from "lucide-react"; import { Link, useNavigate, useParams } from "react-router-dom"; @@ -282,10 +283,7 @@ export function CourseModuleDetailPage() { toast.success("Video uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload video"; - toast.error(message); + notifyApiError(error, "Failed to upload video"); } finally { setUploadingVideo(false); } @@ -310,10 +308,7 @@ export function CourseModuleDetailPage() { toast.success("Thumbnail uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail"); } finally { setUploadingThumbnail(false); } @@ -331,10 +326,7 @@ export function CourseModuleDetailPage() { } } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload URL to MinIO"; - toast.error(message); + notifyApiError(error, "Failed to upload URL to MinIO"); } finally { setUploadingThumbnail(false); } @@ -376,10 +368,7 @@ export function CourseModuleDetailPage() { setCreateLessonOpen(false); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to create lesson"; - toast.error(message); + notifyApiError(error, "Failed to create lesson"); } finally { setCreatingLesson(false); } @@ -427,10 +416,7 @@ export function CourseModuleDetailPage() { toast.success("Video uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload video"; - toast.error(message); + notifyApiError(error, "Failed to upload video"); } finally { setUploadingEditVideo(false); } @@ -455,10 +441,7 @@ export function CourseModuleDetailPage() { toast.success("Thumbnail uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail"); } finally { setUploadingEditThumbnail(false); } @@ -476,10 +459,7 @@ export function CourseModuleDetailPage() { } } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload URL to MinIO"; - toast.error(message); + notifyApiError(error, "Failed to upload URL to MinIO"); } finally { setUploadingEditThumbnail(false); } @@ -513,10 +493,7 @@ export function CourseModuleDetailPage() { closeEditLesson(); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update lesson"; - toast.error(message); + notifyApiError(error, "Failed to update lesson"); } finally { setSavingEdit(false); } @@ -532,10 +509,7 @@ export function CourseModuleDetailPage() { setDeletingLessonId(null); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to delete lesson"; - toast.error(message); + notifyApiError(error, "Failed to delete lesson"); } finally { setDeletingLesson(false); } @@ -556,10 +530,7 @@ export function CourseModuleDetailPage() { ); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module status"; - toast.error(message); + notifyApiError(error, "Failed to update module status"); } finally { setModulePublishStatusUpdating(false); } @@ -586,13 +557,10 @@ export function CourseModuleDetailPage() { ); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? - (nextStatus === "PUBLISHED" - ? "Failed to publish lesson" - : "Failed to save lesson as draft"); - toast.error(message); + notifyApiError( + error, + nextStatus === "PUBLISHED" ? "Failed to publish lesson" : "Failed to save lesson as draft", + ); } finally { setPublishStatusLessonId(null); } @@ -617,10 +585,7 @@ export function CourseModuleDetailPage() { ); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update lesson access tier"; - toast.error(message); + notifyApiError(error, "Failed to update lesson access tier"); } finally { setAccessTierLessonId(null); } diff --git a/src/pages/content-management/CoursesPage.tsx b/src/pages/content-management/CoursesPage.tsx index 0680e01..5f13e05 100644 --- a/src/pages/content-management/CoursesPage.tsx +++ b/src/pages/content-management/CoursesPage.tsx @@ -1,3 +1,4 @@ +import { getApiErrorMessage } from "../../lib/apiErrors" import { useEffect, useMemo, useState } from "react" import { Link, useParams, useNavigate } from "react-router-dom" import { @@ -150,7 +151,7 @@ export function CoursesPage() { await fetchSubCategories() } catch (err: any) { console.error("Failed to create course:", err) - setSaveError(err.response?.data?.message || "Failed to create sub-category") + setSaveError(getApiErrorMessage(err, "Failed to create sub-category")) } finally { setSaving(false) } @@ -230,7 +231,7 @@ export function CoursesPage() { await fetchSubCategories() } catch (err: any) { console.error("Failed to update course:", err) - setUpdateError(err.response?.data?.message || "Failed to update sub-category") + setUpdateError(getApiErrorMessage(err, "Failed to update sub-category")) } finally { setUpdating(false) } diff --git a/src/pages/content-management/CreateQuestionTypeFlow.tsx b/src/pages/content-management/CreateQuestionTypeFlow.tsx index 198275e..0f7fe89 100644 --- a/src/pages/content-management/CreateQuestionTypeFlow.tsx +++ b/src/pages/content-management/CreateQuestionTypeFlow.tsx @@ -1,6 +1,8 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useEffect, useMemo, useState } from "react" -import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom" -import { ArrowLeft, Loader2 } from "lucide-react" +import { useNavigate, useParams, useSearchParams } from "react-router-dom" +import { Loader2 } from "lucide-react" +import { PageBackLink } from "../../components/navigation/PageBackLink" import { toast } from "sonner" import { Button } from "../../components/ui/button" import { Card } from "../../components/ui/card" @@ -129,7 +131,7 @@ export function CreateQuestionTypeFlow() { if (!cancelled) { console.error(e) setCatalogError("Failed to load component catalog.") - toast.error("Failed to load component catalog") + notifyApiError(e, "Failed to load component catalog") } } finally { if (!cancelled) setCatalogLoading(false) @@ -165,7 +167,7 @@ export function CreateQuestionTypeFlow() { } catch (e) { if (!cancelled) { console.error(e) - toast.error("Failed to load definition") + notifyApiError(e, "Failed to load definition") navigate("/new-content/question-types") } } finally { @@ -276,9 +278,7 @@ export function CreateQuestionTypeFlow() { navigate(`/new-content/question-types?updated=${id}`) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string; error?: string } } } - toast.error(String(err.response?.data?.message || "Save failed"), { - description: err.response?.data?.error ? String(err.response.data.error) : undefined, - }) + notifyApiError(err, "Save failed") } finally { setSaving(false) } @@ -326,9 +326,7 @@ export function CreateQuestionTypeFlow() { navigate(`/new-content/question-types?created=${id}`) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string; error?: string } } } - toast.error(String(err.response?.data?.message || "Save failed"), { - description: err.response?.data?.error ? String(err.response.data.error) : undefined, - }) + notifyApiError(err, "Save failed") } } @@ -349,13 +347,11 @@ export function CreateQuestionTypeFlow() {
- - - Back to Question Type Library - +
diff --git a/src/pages/content-management/EditPracticeFlow.tsx b/src/pages/content-management/EditPracticeFlow.tsx index ac78aeb..7acd8fe 100644 --- a/src/pages/content-management/EditPracticeFlow.tsx +++ b/src/pages/content-management/EditPracticeFlow.tsx @@ -1,15 +1,12 @@ +import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors" import { useEffect, useMemo, useRef, useState } from "react"; -import { - Link, - useNavigate, - useParams, - useSearchParams, -} from "react-router-dom"; -import { ArrowLeft, Loader2 } from "lucide-react"; +import { useNavigate, useParams, useSearchParams } from "react-router-dom"; +import { Loader2 } from "lucide-react"; +import { PageBackLink } from "../../components/navigation/PageBackLink"; +import { navigateBack } from "../../lib/navigateBack"; import { toast } from "sonner"; import { Button } from "../../components/ui/button"; import { Stepper } from "../../components/ui/stepper"; -import successIcon from "../../assets/success.svg"; import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"; import { getExamPrepPracticeFull, @@ -17,7 +14,6 @@ import { } from "../../api/courses.api"; import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api"; import { - learnEnglishPracticeApiErrorMessage, validateLearnEnglishQuestionsWithDefinitions, } from "../../lib/learnEnglishPracticePublish"; import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator"; @@ -37,6 +33,10 @@ import { unwrapPracticeFullData, type PreservedQuestionSetFields, } from "../../lib/practiceFullMapper"; +import { + buildPracticeEditSnapshot, + hasPracticeEditChanges, +} from "../../lib/practiceEditDirty"; import { ContextStep } from "./components/practice-steps/ContextStep"; import { ScenarioStep } from "./components/practice-steps/ScenarioStep"; @@ -221,13 +221,15 @@ export function EditPracticeFlow() { level, ]); + const goBack = () => navigateBack(navigate, backPath); + const [currentStep, setCurrentStep] = useState(1); - const [isSaved, setIsSaved] = useState(false); const [submitting, setSubmitting] = useState(false); const [loadingPractice, setLoadingPractice] = useState(true); const [loadError, setLoadError] = useState(null); const [selectedPersona, setSelectedPersona] = useState(null); + const [loadedPersonaId, setLoadedPersonaId] = useState(null); const [preservedQuestionSet, setPreservedQuestionSet] = useState({ timeLimitMinutes: null, @@ -241,7 +243,7 @@ export function EditPracticeFlow() { loading: personasLoading, error: personasError, reload: reloadPersonas, - } = useActivePersonas(); + } = useActivePersonas({ ensurePersonaId: loadedPersonaId }); const [formData, setFormData] = useState({ title: "", @@ -282,6 +284,7 @@ export function EditPracticeFlow() { ); const [definitionsLoading, setDefinitionsLoading] = useState(true); const [definitionsError, setDefinitionsError] = useState(null); + const [initialSnapshot, setInitialSnapshot] = useState(null); const initialParentsRef = useRef([]); useEffect(() => { @@ -297,7 +300,7 @@ export function EditPracticeFlow() { if (!cancelled) setTypeDefinitions(list); } catch (e) { if (!cancelled) { - setDefinitionsError(learnEnglishPracticeApiErrorMessage(e)); + setDefinitionsError(getApiErrorMessage(e, "Failed to load question type definitions")); setTypeDefinitions([]); } } finally { @@ -323,15 +326,23 @@ export function EditPracticeFlow() { if (!full) throw new Error("Practice details were missing from the response."); const mapped = mapPracticeFullToFormState(full, typeDefinitions); if (cancelled) return; + const loadedPersona = + mapped.personaId != null ? String(mapped.personaId) : null; setFormData(mapped.formData); setPreservedQuestionSet(mapped.preservedQuestionSet); initialParentsRef.current = mapped.parents; - if (mapped.personaId != null) { - setSelectedPersona(String(mapped.personaId)); - } + setLoadedPersonaId(mapped.personaId); + setSelectedPersona(loadedPersona); + setInitialSnapshot( + buildPracticeEditSnapshot({ + formData: mapped.formData, + selectedPersona: loadedPersona, + preservedQuestionSet: mapped.preservedQuestionSet, + }), + ); } catch (e) { if (!cancelled) { - setLoadError(learnEnglishPracticeApiErrorMessage(e)); + setLoadError(getApiErrorMessage(e, "Failed to load practice")); } } finally { if (!cancelled) setLoadingPractice(false); @@ -342,6 +353,23 @@ export function EditPracticeFlow() { }; }, [validPracticeId, practiceId, isExamPrep, typeDefinitions, definitionsLoading]); + useEffect(() => { + if (loadedPersonaId == null || personasLoading) return; + const idStr = String(loadedPersonaId); + if (!personas.some((persona) => persona.id === idStr)) return; + setSelectedPersona((current) => (current === idStr ? current : idStr)); + }, [loadedPersonaId, personas, personasLoading]); + + const hasUnsavedChanges = useMemo( + () => + hasPracticeEditChanges(initialSnapshot, { + formData, + selectedPersona, + preservedQuestionSet, + }), + [initialSnapshot, formData, selectedPersona, preservedQuestionSet], + ); + const submitPractice = async (status: "DRAFT" | "PUBLISHED") => { if (!validPracticeId) { toast.error("Invalid practice", { description: "Missing practice id in the URL." }); @@ -448,15 +476,14 @@ export function EditPracticeFlow() { initialParentsRef.current, ), }); + initialParentsRef.current = dedupeParents(formData.parents); + setPreservedQuestionSet((prev) => ({ ...prev, status })); toast.success( status === "PUBLISHED" ? "Practice updated and published" : "Practice saved as draft", ); - initialParentsRef.current = dedupeParents(formData.parents); - setIsSaved(true); + navigate(backPath); } catch (e) { - toast.error("Could not update practice", { - description: learnEnglishPracticeApiErrorMessage(e), - }); + notifyApiError(e, "Could not update practice"); } finally { setSubmitting(false); } @@ -466,11 +493,16 @@ export function EditPracticeFlow() { setCurrentStep((prev) => Math.min(prev + 1, STEP_LABELS.length)); const prevStep = () => setCurrentStep((prev) => Math.max(prev - 1, 1)); + const saveStatus: "DRAFT" | "PUBLISHED" = + preservedQuestionSet.status === "DRAFT" ? "DRAFT" : "PUBLISHED"; + + const handleSaveChanges = () => void submitPractice(saveStatus); + if (!validPracticeId) { return (

Invalid practice link

-
@@ -492,7 +524,7 @@ export function EditPracticeFlow() {

Could not load practice

{loadError}

- @@ -501,33 +533,6 @@ export function EditPracticeFlow() { ); } - if (isSaved) { - return ( -
-
-
- Success -
-

- Practice Updated Successfully! -

-

- Your changes to this practice have been saved. -

- -
- ); - } - const reviewParentSummary = formData.parents.length > 0 ? formatPracticeParentsSummary(formData.parents, { isExamPrep }) @@ -548,7 +553,7 @@ export function EditPracticeFlow() { formData={formData} setFormData={setFormData} nextStep={nextStep} - onCancel={() => navigate(backPath)} + onCancel={() => goBack()} isLessonPractice={isLearnEnglishLessonPractice} lessonTitle={lessonTitleDisplay} parentSummary={reviewParentSummary} @@ -558,8 +563,15 @@ export function EditPracticeFlow() { parentsCollapsedDefault={isExamPrep} practiceId={practiceId} onParentsUnlinked={(parents) => { - setFormData((fd) => ({ ...fd, parents })) - initialParentsRef.current = parents + setFormData((fd) => ({ ...fd, parents })); + initialParentsRef.current = parents; + setInitialSnapshot( + buildPracticeEditSnapshot({ + formData: { ...formData, parents }, + selectedPersona, + preservedQuestionSet, + }), + ); }} /> ); @@ -685,25 +697,36 @@ export function EditPracticeFlow() {
- - - {backLabel} - +
-
+

Edit Practice

- +
+ + +

Update story details, persona, and questions for practice #{practiceId}. diff --git a/src/pages/content-management/HumanLanguageHierarchyPage.tsx b/src/pages/content-management/HumanLanguageHierarchyPage.tsx index 4445242..5c1d83c 100644 --- a/src/pages/content-management/HumanLanguageHierarchyPage.tsx +++ b/src/pages/content-management/HumanLanguageHierarchyPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { type Dispatch, type SetStateAction, useCallback, useEffect, useMemo, useRef, useState } from "react" import { Link } from "react-router-dom" import { BookOpen, ChevronDown, ChevronRight, FolderTree, Languages, Pencil, Plus, Trash2 } from "lucide-react" @@ -10,6 +11,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D import { Input } from "../../components/ui/input" import { Select } from "../../components/ui/select" import { SpinnerIcon } from "../../components/ui/spinner-icon" +import { PageBackLink } from "../../components/navigation/PageBackLink" import { createModule, deleteModule, @@ -303,7 +305,7 @@ export function HumanLanguageHierarchyPage() { console.error(err) setHierarchyRows([]) setHierarchyError("Could not load Human Language hierarchy") - toast.error("Failed to load Human Language hierarchy") + notifyApiError(err, "Failed to load Human Language hierarchy") } finally { setHierarchyLoading(false) } @@ -358,7 +360,7 @@ export function HumanLanguageHierarchyPage() { setCourseRowsByCourseId({}) setLevelPracticesByLevelId({}) setCourseHierarchyError("Could not load hierarchy for selected courses") - toast.error("Failed to load course hierarchy") + notifyApiError(err, "Failed to load course hierarchy") } finally { setCourseHierarchyLoading(false) } @@ -516,7 +518,7 @@ export function HumanLanguageHierarchyPage() { await fetchHierarchiesForCourses(refreshCourseIds) } catch (error) { console.error(error) - toast.error("Failed to create module") + notifyApiError(error, "Failed to create module") } finally { setCreateModuleSaving(false) } @@ -606,7 +608,7 @@ export function HumanLanguageHierarchyPage() { await fetchHierarchiesForCourses(refreshCourseIds) } catch (error) { console.error(error) - toast.error("Failed to update module") + notifyApiError(error, "Failed to update module") } finally { setEditModuleSaving(false) } @@ -633,7 +635,7 @@ export function HumanLanguageHierarchyPage() { await fetchHierarchiesForCourses(refreshCourseIds) } catch (error) { console.error(error) - toast.error("Failed to delete module") + notifyApiError(error, "Failed to delete module") } finally { setDeleteModuleSavingId(null) } @@ -666,6 +668,7 @@ export function HumanLanguageHierarchyPage() { return (

+
@@ -676,9 +679,6 @@ export function HumanLanguageHierarchyPage() {

Hierarchy management

-
+ {/* Header section */}
diff --git a/src/pages/content-management/LessonPracticesPage.tsx b/src/pages/content-management/LessonPracticesPage.tsx index b19d648..eec50f9 100644 --- a/src/pages/content-management/LessonPracticesPage.tsx +++ b/src/pages/content-management/LessonPracticesPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useState } from "react"; import { AlertCircle, @@ -344,7 +345,7 @@ export function LessonPracticesPage() { setPractices([]); setTotalCount(0); setLoadError("Could not load practices for this lesson."); - toast.error("Failed to load practices"); + notifyApiError(err, "Failed to load practices"); } finally { setLoading(false); } @@ -420,7 +421,7 @@ export function LessonPracticesPage() { ); } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } }; - toast.error(err.response?.data?.message || "Failed to update practice status"); + notifyApiError(err, "Failed to update practice status"); } finally { setPublishStatusUpdatingId(null); } @@ -450,9 +451,7 @@ export function LessonPracticesPage() { await load(); return; } - toast.error("Could not remove from lesson", { - description: mapPracticeParentUnlinkError(e), - }); + notifyApiError(err, "Could not remove from lesson"); } finally { setUnlinking(false); } @@ -468,7 +467,7 @@ export function LessonPracticesPage() { await load(); } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } }; - toast.error(err.response?.data?.message || "Failed to delete practice"); + notifyApiError(err, "Failed to delete practice"); } finally { setDeleting(false); } diff --git a/src/pages/content-management/LinkExistingPracticeFlow.tsx b/src/pages/content-management/LinkExistingPracticeFlow.tsx index 5151577..88a7dee 100644 --- a/src/pages/content-management/LinkExistingPracticeFlow.tsx +++ b/src/pages/content-management/LinkExistingPracticeFlow.tsx @@ -1,13 +1,15 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useMemo, useState } from "react" -import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom" -import { ArrowLeft, Link2 } from "lucide-react" +import { useNavigate, useParams, useSearchParams } from "react-router-dom" +import { Link2 } from "lucide-react" +import { PageBackLink } from "../../components/navigation/PageBackLink" +import { navigateBack } from "../../lib/navigateBack" import { toast } from "sonner" import { Button } from "../../components/ui/button" import { Stepper } from "../../components/ui/stepper" import successIcon from "../../assets/success.svg" import type { ParentContextPractice, PracticeParentKind } from "../../types/course.types" import { attachPracticeToParent } from "../../lib/attachPracticeToParent" -import { learnEnglishPracticeApiErrorMessage } from "../../lib/learnEnglishPracticePublish" import { formatPracticeParentLabel } from "../../lib/practiceParents" import type { PracticeParentTitleHints } from "../../lib/practiceParentTitles" import { LinkExistingPracticeReviewStep } from "./components/practice-steps/LinkExistingPracticeReviewStep" @@ -170,6 +172,8 @@ export function LinkExistingPracticeFlow() { level, ]) + const goBack = () => navigateBack(navigate, backPath) + const parentTitleHints = useMemo((): PracticeParentTitleHints => { const hints: PracticeParentTitleHints = {} const lid = lessonId ? Number(lessonId) : NaN @@ -198,7 +202,7 @@ export function LinkExistingPracticeFlow() { @@ -215,9 +219,7 @@ export function LinkExistingPracticeFlow() { toast.success("Practice linked successfully") setIsComplete(true) } catch (e) { - toast.error("Could not link practice", { - description: learnEnglishPracticeApiErrorMessage(e), - }) + notifyApiError(e, "Could not link practice") } finally { setSubmitting(false) } @@ -240,7 +242,7 @@ export function LinkExistingPracticeFlow() { is now attached to {targetSummary}.

@@ -304,7 +300,7 @@ export function LinkExistingPracticeFlow() { selectedPracticeId={selectedPractice?.id ?? null} onSelect={setSelectedPractice} nextStep={() => setCurrentStep(2)} - onCancel={() => navigate(backPath)} + onCancel={goBack} /> ) : selectedPractice ? ( +

Practice Management

diff --git a/src/pages/content-management/PracticeMembersPage.tsx b/src/pages/content-management/PracticeMembersPage.tsx index a25717f..1594cee 100644 --- a/src/pages/content-management/PracticeMembersPage.tsx +++ b/src/pages/content-management/PracticeMembersPage.tsx @@ -1,5 +1,6 @@ import { useState } from "react" import { Plus } from "lucide-react" +import { PageBackLink } from "../../components/navigation/PageBackLink" import { Button } from "../../components/ui/button" import { Card } from "../../components/ui/card" import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar" @@ -29,6 +30,7 @@ export function PracticeMembersPage() { return (
+ {/* Page Header */}

Practice Management

diff --git a/src/pages/content-management/ProgramCoursesPage.tsx b/src/pages/content-management/ProgramCoursesPage.tsx index 017f46f..461ff06 100644 --- a/src/pages/content-management/ProgramCoursesPage.tsx +++ b/src/pages/content-management/ProgramCoursesPage.tsx @@ -1,6 +1,8 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { ArrowLeft, Plus, Pencil, Trash2, X } from "lucide-react"; +import { Plus, Pencil, Trash2, X } from "lucide-react"; import { Link, useNavigate, useParams } from "react-router-dom"; +import { PageBackLink } from "../../components/navigation/PageBackLink"; import { toast } from "sonner"; import { Card, CardContent } from "../../components/ui/card"; import { Button } from "../../components/ui/button"; @@ -121,10 +123,7 @@ export function ProgramCoursesPage() { nextStatus === "PUBLISHED" ? "Course published" : "Course saved as draft", ); } catch (e: unknown) { - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course status"; - toast.error(msg); + notifyApiError(e, "Failed to update course status"); } finally { setPublishStatusUpdatingId(null); } @@ -146,10 +145,7 @@ export function ProgramCoursesPage() { nextTier === "PREMIUM" ? "Course set to Premium" : "Course set to Free", ); } catch (e: unknown) { - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course access tier"; - toast.error(msg); + notifyApiError(e, "Failed to update course access tier"); } finally { setAccessTierUpdatingId(null); } @@ -187,9 +183,7 @@ export function ProgramCoursesPage() { setError("Failed to load courses"); setCourses([]); setProgram(null); - toast.error("Could not load courses", { - description: "Check your connection or try again.", - }); + notifyApiError(e, "Could not load courses"); } finally { setLoading(false); } @@ -209,10 +203,7 @@ export function ProgramCoursesPage() { await loadData(); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to delete course"; - toast.error(msg); + notifyApiError(e, "Failed to delete course"); } finally { setDeleting(false); } @@ -266,10 +257,7 @@ export function ProgramCoursesPage() { toast.success("Thumbnail uploaded"); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(msg); + notifyApiError(e, "Failed to upload thumbnail"); } finally { setUploadingEditThumbnail(false); } @@ -305,10 +293,7 @@ export function ProgramCoursesPage() { await loadData(); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course"; - toast.error(msg); + notifyApiError(e, "Failed to update course"); } finally { setSavingEdit(false); } @@ -357,10 +342,7 @@ export function ProgramCoursesPage() { toast.success("Thumbnail uploaded"); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(msg); + notifyApiError(e, "Failed to upload thumbnail"); } finally { setCreateUploadingThumbnail(false); } @@ -397,10 +379,7 @@ export function ProgramCoursesPage() { await loadData(); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to create course"; - toast.error(msg); + notifyApiError(e, "Failed to create course"); } finally { setCreateSaving(false); } @@ -418,13 +397,7 @@ export function ProgramCoursesPage() { return (
{/* Navigation */} - - - Back to Programs - + {/* Header section */}
diff --git a/src/pages/content-management/ProgramDetailPage.tsx b/src/pages/content-management/ProgramDetailPage.tsx index 28f0c9a..d4e4cf6 100644 --- a/src/pages/content-management/ProgramDetailPage.tsx +++ b/src/pages/content-management/ProgramDetailPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Link, useParams, useNavigate } from "react-router-dom"; import { @@ -127,7 +128,7 @@ export function ProgramDetailPage() { ); } catch (error) { console.error(error); - toast.error("Failed to fetch catalog courses"); + notifyApiError(error, "Failed to fetch catalog courses"); setCreatedCourses([]); } finally { setCatalogLoading(false); @@ -190,10 +191,7 @@ export function ProgramDetailPage() { nextStatus === "PUBLISHED" ? "Course published" : "Course saved as draft", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course status"; - toast.error(message); + notifyApiError(error, "Failed to update course status"); } finally { setPublishStatusUpdatingId(null); } @@ -217,10 +215,7 @@ export function ProgramDetailPage() { nextTier === "PREMIUM" ? "Course set to Premium" : "Course set to Free", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course access tier"; - toast.error(message); + notifyApiError(error, "Failed to update course access tier"); } finally { setAccessTierUpdatingId(null); } @@ -257,10 +252,7 @@ export function ProgramDetailPage() { toast.success("Thumbnail URL uploaded to MinIO"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail URL"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail URL"); } finally { setUploadingThumbnail(false); } @@ -335,10 +327,7 @@ export function ProgramDetailPage() { setCreateOpen(false); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to create course"; - toast.error(message); + notifyApiError(error, "Failed to create course"); } finally { setCreating(false); } @@ -380,10 +369,7 @@ export function ProgramDetailPage() { toast.success("Thumbnail uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail"); } finally { setUploadingEditThumbnail(false); } @@ -438,10 +424,7 @@ export function ProgramDetailPage() { closeEditCourse(); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update course"; - toast.error(message); + notifyApiError(error, "Failed to update course"); } finally { setSavingEdit(false); } @@ -457,10 +440,7 @@ export function ProgramDetailPage() { setDeletingCourseId(null); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to delete course"; - toast.error(message); + notifyApiError(error, "Failed to delete course"); } finally { setDeletingCourse(false); } @@ -493,10 +473,7 @@ export function ProgramDetailPage() { toast.success("Thumbnail uploaded"); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(message); + notifyApiError(error, "Failed to upload thumbnail"); } finally { setUploadingThumbnail(false); } diff --git a/src/pages/content-management/ProgramTypeSelectionPage.tsx b/src/pages/content-management/ProgramTypeSelectionPage.tsx index aa15680..63c5803 100644 --- a/src/pages/content-management/ProgramTypeSelectionPage.tsx +++ b/src/pages/content-management/ProgramTypeSelectionPage.tsx @@ -1,9 +1,11 @@ import { Link } from "react-router-dom"; import { GraduationCap, Brain } from "lucide-react"; +import { PageBackLink } from "../../components/navigation/PageBackLink"; export function ProgramTypeSelectionPage() { return (
+ {/* Header section */}

diff --git a/src/pages/content-management/QuestionTypeGroupDetailPage.tsx b/src/pages/content-management/QuestionTypeGroupDetailPage.tsx index 61301da..bc5528b 100644 --- a/src/pages/content-management/QuestionTypeGroupDetailPage.tsx +++ b/src/pages/content-management/QuestionTypeGroupDetailPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useState } from "react" import { Link, useNavigate, useParams } from "react-router-dom" import { @@ -26,7 +27,6 @@ import { cn } from "../../lib/utils" import { deleteQuestionTypeDefinitionGroup, getQuestionTypeDefinitionGroupById, - groupApiErrorMessage, } from "../../api/questionTypeDefinitionGroups.api" import { assignQuestionTypeDefinitionGroups } from "../../api/questionTypeDefinitions.api" import { removeGroupFromMembership } from "../../lib/questionTypeGroupIds" @@ -67,7 +67,7 @@ export function QuestionTypeGroupDetailPage() { } setGroup(detail) } catch (e) { - toast.error(groupApiErrorMessage(e, "Failed to load group")) + notifyApiError(e, "Failed to load group") setGroup(null) } finally { setLoading(false) @@ -88,7 +88,7 @@ export function QuestionTypeGroupDetailPage() { toast.success("Removed from this group") await load() } catch (e) { - toast.error(groupApiErrorMessage(e, "Could not remove from group")) + notifyApiError(e, "Could not remove from group") } finally { setDetachingId(null) } @@ -102,7 +102,7 @@ export function QuestionTypeGroupDetailPage() { toast.success("Group deleted. Membership links for this group were removed.") navigate("/new-content/question-types") } catch (e) { - toast.error(groupApiErrorMessage(e, "Delete failed")) + notifyApiError(e, "Delete failed") } finally { setDeleteSubmitting(false) } diff --git a/src/pages/content-management/QuestionTypeLibraryPage.tsx b/src/pages/content-management/QuestionTypeLibraryPage.tsx index ca13b07..0cc11c8 100644 --- a/src/pages/content-management/QuestionTypeLibraryPage.tsx +++ b/src/pages/content-management/QuestionTypeLibraryPage.tsx @@ -1,7 +1,7 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useState } from "react" import { Link, useNavigate, useSearchParams } from "react-router-dom" import { - ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, @@ -42,13 +42,13 @@ import { import { deleteQuestionTypeDefinitionGroup, getQuestionTypeDefinitionGroups, - groupApiErrorMessage, } from "../../api/questionTypeDefinitionGroups.api" import type { QuestionTypeDefinition, QuestionTypeDefinitionGroup, } from "../../types/questionTypeDefinition.types" import { QuestionTypeGroupFormDialog } from "./components/QuestionTypeGroupFormDialog" +import { PageBackLink } from "../../components/navigation/PageBackLink" import { definitionBelongsToGroup, isDefinitionUngrouped, @@ -115,7 +115,7 @@ export function QuestionTypeLibraryPage() { setGroups(rows) } catch (e) { console.error(e) - toast.error("Failed to load question type groups") + notifyApiError(e, "Failed to load question type groups") setGroups([]) } finally { setGroupsLoading(false) @@ -134,7 +134,7 @@ export function QuestionTypeLibraryPage() { setDefinitions(visibleRows) } catch (e) { console.error(e) - toast.error("Failed to load question type definitions") + notifyApiError(e, "Failed to load question type definitions") setDefinitions([]) } finally { setLoading(false) @@ -231,7 +231,7 @@ export function QuestionTypeLibraryPage() { if (groupFilter === row.id) setGroupFilter("all") await Promise.all([load(), loadGroups()]) } catch (e) { - toast.error(groupApiErrorMessage(e, "Delete failed")) + notifyApiError(e, "Delete failed") } finally { setGroupDeleteSubmitting(false) } @@ -260,7 +260,7 @@ export function QuestionTypeLibraryPage() { void load() } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } } - toast.error(String(err.response?.data?.message || "Delete failed")) + notifyApiError(err, "Delete failed") } finally { setDeleteSubmitting(false) } @@ -269,13 +269,12 @@ export function QuestionTypeLibraryPage() { return (
- - - Back to Content Management - +
diff --git a/src/pages/content-management/QuestionsPage.tsx b/src/pages/content-management/QuestionsPage.tsx index 6c95f00..1dbd468 100644 --- a/src/pages/content-management/QuestionsPage.tsx +++ b/src/pages/content-management/QuestionsPage.tsx @@ -21,6 +21,7 @@ import { deleteQuestion, getQuestionById, getQuestions, updateQuestion } from ". import { countActiveFilters } from "../../lib/adminFilterUtils" import type { QuestionDetail } from "../../types/course.types" import { cn } from "../../lib/utils" +import { PageBackLink } from "../../components/navigation/PageBackLink" import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" type QuestionTypeFilter = "all" | "MCQ" | "TRUE_FALSE" | "SHORT_ANSWER" | "AUDIO" @@ -338,6 +339,7 @@ export function QuestionsPage() { return (
+ {/* Page Header */}
diff --git a/src/pages/content-management/ReorderContentPage.tsx b/src/pages/content-management/ReorderContentPage.tsx index 5a4c535..4784182 100644 --- a/src/pages/content-management/ReorderContentPage.tsx +++ b/src/pages/content-management/ReorderContentPage.tsx @@ -1,18 +1,11 @@ -import { Link } from "react-router-dom"; -import { ArrowLeft } from "lucide-react"; import { ContentHierarchyList } from "./components/ContentHierarchyList"; +import { PageBackLink } from "../../components/navigation/PageBackLink"; export function ReorderContentPage() { return (
- - - Back to Content Management - +

diff --git a/src/pages/content-management/SpeakingPage.tsx b/src/pages/content-management/SpeakingPage.tsx index af38fb1..b427e6d 100644 --- a/src/pages/content-management/SpeakingPage.tsx +++ b/src/pages/content-management/SpeakingPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from "react" import { ArrowLeft, ChevronDown, ChevronRight, Image as ImageIcon, Mic, Plus, Trash2, Upload } from "lucide-react" import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card" @@ -593,7 +594,7 @@ export function SpeakingPage() { toast.success("Practice created. Continue adding questions.") } catch (error) { console.error("Failed to create speaking practice set:", error) - toast.error("Failed to create practice set") + notifyApiError(error, "Failed to create practice set") } finally { setCreatingSet(false) } @@ -616,7 +617,7 @@ export function SpeakingPage() { toast.success("Intro video uploaded", { description: "The URL has been filled in for you." }) } catch (error) { console.error("Failed to upload intro video:", error) - toast.error("Failed to upload intro video") + notifyApiError(error, "Failed to upload intro video") } finally { setUploadingIntroVideo(false) } @@ -715,7 +716,7 @@ export function SpeakingPage() { toast.success("Audio uploaded successfully") } catch (error) { console.error("Failed to upload audio:", error) - toast.error("Failed to upload audio file") + notifyApiError(error, "Failed to upload audio file") } finally { updateDraft(draftIndex, (draft) => field === "voice_prompt" @@ -768,7 +769,7 @@ export function SpeakingPage() { toast.success("Image uploaded successfully") } catch (error) { console.error("Failed to upload image:", error) - toast.error("Failed to upload image") + notifyApiError(error, "Failed to upload image") } finally { updateDraft(draftIndex, (draft) => ({ ...draft, uploadingImage: false })) event.target.value = "" @@ -839,7 +840,7 @@ export function SpeakingPage() { ) } catch (error) { console.error("Failed to resolve audio preview URL:", error) - toast.error("Could not import/resolve audio URL") + notifyApiError(error, "Could not import/resolve audio URL") } finally { updateDraft(draftIndex, (draft) => field === "voice_prompt" @@ -861,7 +862,7 @@ export function SpeakingPage() { updateDraft(draftIndex, (current) => ({ ...current, imagePreviewUrl: resolved })) } catch (error) { console.error("Failed to resolve image preview URL:", error) - toast.error("Could not resolve image preview URL") + notifyApiError(error, "Could not resolve image preview URL") } } @@ -1093,7 +1094,7 @@ export function SpeakingPage() { await fetchAudioQuestions() } catch (error) { console.error("Failed to create speaking practice:", error) - toast.error("Failed to create speaking practice") + notifyApiError(error, "Failed to create speaking practice") } finally { setSaving(false) } @@ -1138,7 +1139,7 @@ export function SpeakingPage() { } } catch (error) { console.error("Failed to fetch question detail:", error) - toast.error("Failed to load question detail") + notifyApiError(error, "Failed to load question detail") setDetailOpen(false) } finally { setDetailLoading(false) @@ -1199,7 +1200,7 @@ export function SpeakingPage() { toast.success("AUDIO question updated") } catch (error) { console.error("Failed to update AUDIO question:", error) - toast.error("Failed to update AUDIO question") + notifyApiError(error, "Failed to update AUDIO question") } finally { setDetailSaving(false) } @@ -1219,7 +1220,7 @@ export function SpeakingPage() { toast.success("AUDIO question deleted") } catch (error) { console.error("Failed to delete AUDIO question:", error) - toast.error("Failed to delete AUDIO question") + notifyApiError(error, "Failed to delete AUDIO question") } finally { setDetailDeleting(false) } @@ -1254,7 +1255,7 @@ export function SpeakingPage() { toast.success(`Deleted ${selectedQuestionIds.length} AUDIO question(s)`) } catch (error) { console.error("Failed to delete selected AUDIO questions:", error) - toast.error("Failed to delete selected AUDIO questions") + notifyApiError(error, "Failed to delete selected AUDIO questions") } finally { setBulkDeleting(false) } diff --git a/src/pages/content-management/UnitManagementPage.tsx b/src/pages/content-management/UnitManagementPage.tsx index b31267b..070a2a3 100644 --- a/src/pages/content-management/UnitManagementPage.tsx +++ b/src/pages/content-management/UnitManagementPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Link, useParams, useNavigate } from "react-router-dom"; import { @@ -226,7 +227,7 @@ export function UnitManagementPage() { ); } catch (error) { console.error(error); - toast.error("Failed to load modules"); + notifyApiError(error, "Failed to load modules"); setModules([]); } finally { setModulesLoading(false); @@ -253,10 +254,7 @@ export function UnitManagementPage() { nextStatus === "PUBLISHED" ? "Unit published" : "Unit saved as draft", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update unit status"; - toast.error(message); + notifyApiError(error, "Failed to update unit status"); } finally { setUnitPublishStatusUpdating(false); } @@ -280,10 +278,7 @@ export function UnitManagementPage() { nextStatus === "PUBLISHED" ? "Module published" : "Module saved as draft", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module status"; - toast.error(message); + notifyApiError(error, "Failed to update module status"); } finally { setPublishStatusUpdatingId(null); } @@ -305,10 +300,7 @@ export function UnitManagementPage() { nextTier === "PREMIUM" ? "Module set to Premium" : "Module set to Free", ); } catch (error: unknown) { - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module access tier"; - toast.error(message); + notifyApiError(error, "Failed to update module access tier"); } finally { setAccessTierUpdatingId(null); } @@ -355,10 +347,7 @@ export function UnitManagementPage() { toast.success(`${target === "thumbnail" ? "Thumbnail" : "Icon"} uploaded`); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload image"; - toast.error(message); + notifyApiError(error, "Failed to upload image"); } finally { if (target === "thumbnail") { setUploadingThumbnail(false); @@ -391,10 +380,7 @@ export function UnitManagementPage() { } } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload URL to MinIO"; - toast.error(message); + notifyApiError(error, "Failed to upload URL to MinIO"); } finally { if (target === "thumbnail") { setUploadingThumbnail(false); @@ -430,10 +416,7 @@ export function UnitManagementPage() { setAddModuleOpen(false); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to create module"; - toast.error(message); + notifyApiError(error, "Failed to create module"); } finally { setCreating(false); } @@ -484,10 +467,7 @@ export function UnitManagementPage() { toast.success(`${target === "thumbnail" ? "Thumbnail" : "Icon"} uploaded`); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload image"; - toast.error(message); + notifyApiError(error, "Failed to upload image"); } finally { if (target === "thumbnail") { setUploadingEditThumbnail(false); @@ -517,10 +497,7 @@ export function UnitManagementPage() { } } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload URL to MinIO"; - toast.error(message); + notifyApiError(error, "Failed to upload URL to MinIO"); } finally { if (target === "thumbnail") { setUploadingEditThumbnail(false); @@ -564,10 +541,7 @@ export function UnitManagementPage() { closeEditModule(); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to update module"; - toast.error(message); + notifyApiError(error, "Failed to update module"); } finally { setSavingEdit(false); } @@ -583,10 +557,7 @@ export function UnitManagementPage() { setDeletingModuleId(null); } catch (error: unknown) { console.error(error); - const message = - (error as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to delete module"; - toast.error(message); + notifyApiError(error, "Failed to delete module"); } finally { setDeletingModule(false); } diff --git a/src/pages/content-management/components/AddModuleModal.tsx b/src/pages/content-management/components/AddModuleModal.tsx index 6917e7c..31789d0 100644 --- a/src/pages/content-management/components/AddModuleModal.tsx +++ b/src/pages/content-management/components/AddModuleModal.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useEffect, useState, type FormEvent } from "react"; import { Button } from "../../../components/ui/button"; import { @@ -97,10 +98,7 @@ export function AddModuleModal({ resetAndClose(); } catch (err: unknown) { console.error(err); - const msg = - (err as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to create module"; - toast.error(msg); + notifyApiError(err, "Failed to create module"); } finally { setSubmitting(false); } diff --git a/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx b/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx index 8bec2b0..767e8ba 100644 --- a/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx +++ b/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useCallback, useEffect, useMemo, useState } from "react" import { useNavigate } from "react-router-dom" import { BookOpen, Loader2, RefreshCw } from "lucide-react" @@ -95,7 +96,7 @@ export function CatalogCoursePracticesPanel({ setPractices([]) setTotalCount(0) setLoadError("Could not load practices for this catalog course.") - toast.error("Failed to load practices") + notifyApiError(err, "Failed to load practices") } finally { setLoading(false) } @@ -138,7 +139,7 @@ export function CatalogCoursePracticesPanel({ ) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } } - toast.error(err.response?.data?.message || "Failed to update practice status") + notifyApiError(err, "Failed to update practice status") } finally { setPublishStatusUpdatingId(null) } @@ -168,9 +169,7 @@ export function CatalogCoursePracticesPanel({ await load() return } - toast.error("Could not remove location", { - description: mapPracticeParentUnlinkError(e), - }) + notifyApiError(err, "Could not remove location") } finally { setUnlinking(false) } @@ -186,7 +185,7 @@ export function CatalogCoursePracticesPanel({ await load() } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } } - toast.error(err.response?.data?.message || "Failed to delete practice") + notifyApiError(err, "Failed to delete practice") } finally { setDeleting(false) } diff --git a/src/pages/content-management/components/ContentHierarchyList.tsx b/src/pages/content-management/components/ContentHierarchyList.tsx index 7f27222..5647bf5 100644 --- a/src/pages/content-management/components/ContentHierarchyList.tsx +++ b/src/pages/content-management/components/ContentHierarchyList.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import React, { useState, useEffect, useCallback } from "react"; import { DndContext, @@ -439,12 +440,6 @@ export function ContentHierarchyList() { return arrayMove(siblings, oldIndex, newIndex); }; - const reorderErrorMessage = (error: unknown, fallback: string) => { - const message = (error as { response?: { data?: { message?: string } } }) - ?.response?.data?.message; - return typeof message === "string" && message.trim() ? message : fallback; - }; - const handleProgramReorder = async (activeId: string, overId: string) => { const reordered = reorderSiblings(programs, activeId, overId); if (!reordered) return; @@ -456,7 +451,7 @@ export function ContentHierarchyList() { toast.success("Programs reordered"); } catch (error) { setPrograms(previous); - toast.error(reorderErrorMessage(error, "Failed to reorder programs")); + notifyApiError(error, "Failed to reorder programs"); } }; @@ -481,7 +476,7 @@ export function ContentHierarchyList() { toast.success("Courses reordered"); } catch (error) { setCourses(previous); - toast.error(reorderErrorMessage(error, "Failed to reorder courses")); + notifyApiError(error, "Failed to reorder courses"); } }; @@ -506,7 +501,7 @@ export function ContentHierarchyList() { toast.success("Modules reordered"); } catch (error) { setModules(previous); - toast.error(reorderErrorMessage(error, "Failed to reorder modules")); + notifyApiError(error, "Failed to reorder modules"); } }; @@ -531,7 +526,7 @@ export function ContentHierarchyList() { toast.success("Lessons reordered"); } catch (error) { setLessons(previous); - toast.error(reorderErrorMessage(error, "Failed to reorder lessons")); + notifyApiError(error, "Failed to reorder lessons"); } }; diff --git a/src/pages/content-management/components/CreatePracticeWizard.tsx b/src/pages/content-management/components/CreatePracticeWizard.tsx index bac9242..290550f 100644 --- a/src/pages/content-management/components/CreatePracticeWizard.tsx +++ b/src/pages/content-management/components/CreatePracticeWizard.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useCallback, useEffect, useState } from "react" import { Check, ChevronLeft, ChevronRight, ListOrdered, Plus, Trash2 } from "lucide-react" import { toast } from "sonner" @@ -106,7 +107,7 @@ export function CreatePracticeWizard({ parent, onCreated }: Props) { setStep(2) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } }; message?: string } - toast.error(err.response?.data?.message || err.message || "Failed to create question set") + notifyApiError(err, "Failed to create question set") } finally { setSaving(false) } @@ -152,7 +153,7 @@ export function CreatePracticeWizard({ parent, onCreated }: Props) { setStep(3) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } }; message?: string } - toast.error(err.response?.data?.message || err.message || "Failed to create questions") + notifyApiError(err, "Failed to create questions") } finally { setSaving(false) } @@ -172,7 +173,7 @@ export function CreatePracticeWizard({ parent, onCreated }: Props) { setStep(4) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } }; message?: string } - toast.error(err.response?.data?.message || err.message || "Failed to attach questions") + notifyApiError(err, "Failed to attach questions") } finally { setSaving(false) } @@ -205,7 +206,7 @@ export function CreatePracticeWizard({ parent, onCreated }: Props) { onCreated?.() } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } }; message?: string } - toast.error(err.response?.data?.message || err.message || "Failed to create practice") + notifyApiError(err, "Failed to create practice") } finally { setSaving(false) setPendingSaveStatus(null) diff --git a/src/pages/content-management/components/LessonMediaUploadField.tsx b/src/pages/content-management/components/LessonMediaUploadField.tsx index e0deed6..7b1a9d4 100644 --- a/src/pages/content-management/components/LessonMediaUploadField.tsx +++ b/src/pages/content-management/components/LessonMediaUploadField.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useCallback, useRef, useState, type ChangeEvent, type DragEvent } from "react"; import { CloudUpload } from "lucide-react"; import { toast } from "sonner"; @@ -78,10 +79,7 @@ export function LessonMediaUploadField({ toast.success("Thumbnail uploaded"); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload thumbnail"; - toast.error(msg); + notifyApiError(e, "Failed to upload thumbnail"); } finally { setBusy(false); } @@ -107,10 +105,7 @@ export function LessonMediaUploadField({ toast.success("Video uploaded"); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload video"; - toast.error(msg); + notifyApiError(e, "Failed to upload video"); } finally { setBusy(false); } diff --git a/src/pages/content-management/components/ModuleIconUploadField.tsx b/src/pages/content-management/components/ModuleIconUploadField.tsx index 9500718..0d92415 100644 --- a/src/pages/content-management/components/ModuleIconUploadField.tsx +++ b/src/pages/content-management/components/ModuleIconUploadField.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useCallback, useRef, useState, type ChangeEvent, type DragEvent } from "react"; import { CloudUpload } from "lucide-react"; import { toast } from "sonner"; @@ -66,10 +67,7 @@ export function ModuleIconUploadField({ toast.success("Icon uploaded"); } catch (e: unknown) { console.error(e); - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to upload icon"; - toast.error(msg); + notifyApiError(e, "Failed to upload icon"); } finally { setBusy(false); } diff --git a/src/pages/content-management/components/PublishPracticeButton.tsx b/src/pages/content-management/components/PublishPracticeButton.tsx index 8d1e158..349bcc0 100644 --- a/src/pages/content-management/components/PublishPracticeButton.tsx +++ b/src/pages/content-management/components/PublishPracticeButton.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useState } from "react" import { Loader2 } from "lucide-react" import { toast } from "sonner" +import { notifyApiError } from "../../../lib/apiErrors" import { getPracticesByParentCourse, getPracticesByParentModule, @@ -97,10 +98,7 @@ export function PublishPracticeButton({ await loadPractices() onPublished?.() } catch (e: unknown) { - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to publish practice" - toast.error(msg) + notifyApiError(e, "Failed to publish practice") } finally { setActing(false) } @@ -133,10 +131,7 @@ export function PublishPracticeButton({ await loadPractices() onPublished?.() } catch (e: unknown) { - const msg = - (e as { response?: { data?: { message?: string } } })?.response?.data - ?.message ?? "Failed to save practice as draft" - toast.error(msg) + notifyApiError(e, "Failed to save practice as draft") } finally { setActing(false) } diff --git a/src/pages/content-management/components/QuestionTypeDefinitionPracticesDialog.tsx b/src/pages/content-management/components/QuestionTypeDefinitionPracticesDialog.tsx index d48473c..fe4d0c6 100644 --- a/src/pages/content-management/components/QuestionTypeDefinitionPracticesDialog.tsx +++ b/src/pages/content-management/components/QuestionTypeDefinitionPracticesDialog.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useCallback, useEffect, useState } from "react" import { useNavigate } from "react-router-dom" import { ChevronDown, ChevronLeft, ChevronRight, GraduationCap, Pencil, Plus } from "lucide-react" @@ -69,7 +70,7 @@ export function QuestionTypeDefinitionPracticesDialog({ setTotalCount(result.total_count) } catch (e) { console.error(e) - toast.error("Failed to load practices for this definition") + notifyApiError(e, "Failed to load practices for this definition") setPractices([]) setTotalCount(0) } finally { @@ -103,19 +104,14 @@ export function QuestionTypeDefinitionPracticesDialog({ try { const path = await resolveQuestionTypeDefinitionPracticeEditPath(practice) if (!path) { - toast.error("Could not open practice editor", { - description: - practice.practice_kind === "EXAM_PREP" - ? "This exam-prep practice could not be linked to its catalog context." - : "This practice could not be linked to its course context.", - }) + notifyApiError(e, "Could not open practice editor") return } onOpenChange(false) navigate(path) } catch (e) { console.error(e) - toast.error("Failed to open practice editor") + notifyApiError(e, "Failed to open practice editor") } finally { setEditingPracticeId(null) } diff --git a/src/pages/content-management/components/QuestionTypeGroupFormDialog.tsx b/src/pages/content-management/components/QuestionTypeGroupFormDialog.tsx index 57505c6..2d38323 100644 --- a/src/pages/content-management/components/QuestionTypeGroupFormDialog.tsx +++ b/src/pages/content-management/components/QuestionTypeGroupFormDialog.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useEffect, useState } from "react" import { toast } from "sonner" import { Button } from "../../../components/ui/button" @@ -16,7 +17,6 @@ import { SpinnerIcon } from "../../../components/ui/spinner-icon" import { createQuestionTypeDefinitionGroup, extractGroupMutationId, - groupApiErrorMessage, updateQuestionTypeDefinitionGroup, } from "../../../api/questionTypeDefinitionGroups.api" import type { @@ -97,7 +97,7 @@ export function QuestionTypeGroupFormDialog({ } onOpenChange(false) } catch (e) { - toast.error(groupApiErrorMessage(e, isEdit ? "Update failed" : "Create failed")) + notifyApiError(e, isEdit ? "Update failed" : "Create failed") } finally { setSubmitting(false) } diff --git a/src/pages/content-management/components/UnitPracticesPanel.tsx b/src/pages/content-management/components/UnitPracticesPanel.tsx index 8dc9c56..f33b0a9 100644 --- a/src/pages/content-management/components/UnitPracticesPanel.tsx +++ b/src/pages/content-management/components/UnitPracticesPanel.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../lib/apiErrors" import { useCallback, useEffect, useMemo, useState } from "react" import { useNavigate } from "react-router-dom" import { BookOpen, Loader2, RefreshCw } from "lucide-react" @@ -97,7 +98,7 @@ export function UnitPracticesPanel({ setPractices([]) setTotalCount(0) setLoadError("Could not load practices for this unit.") - toast.error("Failed to load practices") + notifyApiError(err, "Failed to load practices") } finally { setLoading(false) } @@ -140,7 +141,7 @@ export function UnitPracticesPanel({ ) } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } } - toast.error(err.response?.data?.message || "Failed to update practice status") + notifyApiError(err, "Failed to update practice status") } finally { setPublishStatusUpdatingId(null) } @@ -170,9 +171,7 @@ export function UnitPracticesPanel({ await load() return } - toast.error("Could not remove location", { - description: mapPracticeParentUnlinkError(e), - }) + notifyApiError(err, "Could not remove location") } finally { setUnlinking(false) } @@ -188,7 +187,7 @@ export function UnitPracticesPanel({ await load() } catch (e: unknown) { const err = e as { response?: { data?: { message?: string } } } - toast.error(err.response?.data?.message || "Failed to delete practice") + notifyApiError(err, "Failed to delete practice") } finally { setDeleting(false) } diff --git a/src/pages/content-management/components/practice-steps/ContextStep.tsx b/src/pages/content-management/components/practice-steps/ContextStep.tsx index a481b7f..b8da8f2 100644 --- a/src/pages/content-management/components/practice-steps/ContextStep.tsx +++ b/src/pages/content-management/components/practice-steps/ContextStep.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../../../lib/apiErrors" import { useRef, useState, type ChangeEvent } from "react"; import { ArrowRight, ChevronDown, ChevronUp, Loader2, Upload } from "lucide-react"; import { Button } from "../../../../components/ui/button"; @@ -75,7 +76,7 @@ export function ContextStep({ setFormData({ ...formData, storyImageUrl: url }); toast.success("Story image uploaded"); } catch { - toast.error("Could not upload story image"); + notifyApiError(err, "Could not upload story image"); } finally { setUploadingStory(false); } diff --git a/src/pages/content-management/components/practice-steps/PersonaStep.tsx b/src/pages/content-management/components/practice-steps/PersonaStep.tsx index 881618a..f570866 100644 --- a/src/pages/content-management/components/practice-steps/PersonaStep.tsx +++ b/src/pages/content-management/components/practice-steps/PersonaStep.tsx @@ -1,11 +1,7 @@ import { Check, ArrowRight, Loader2 } from "lucide-react"; import { Link } from "react-router-dom"; import { Button } from "../../../../components/ui/button"; -import { - Avatar, - AvatarFallback, - AvatarImage, -} from "../../../../components/ui/avatar"; +import { PersonaAvatar } from "../../../../components/personas/PersonaAvatar"; import { cn } from "../../../../lib/utils"; import type { PersonaCardModel } from "../../../../lib/personaDisplay"; @@ -96,19 +92,12 @@ export function PersonaStep({

)}
-
- - - - {persona.name.substring(0, 2).toUpperCase()} - - -
+
{persona.name} diff --git a/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx b/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx index 311871d..dd08394 100644 --- a/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx +++ b/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx @@ -1,16 +1,18 @@ -import { useState } from "react" +import { notifyApiError } from "../../../../lib/apiErrors" +import { useMemo, useState } from "react" import { Loader2, Plus, Trash2 } from "lucide-react" +import { usePracticeParentTitles } from "../../../../hooks/usePracticeParentTitles" import { toast } from "sonner" import { Button } from "../../../../components/ui/button" import { Input } from "../../../../components/ui/input" import type { PracticeParent, PracticeParentKind } from "../../../../types/course.types" import { dedupeParents, - formatPracticeParentLabel, isPracticeParentKind, newParentRow, parentsFromPractice, } from "../../../../lib/practiceParents" +import { formatPracticeParentDisplayLabel } from "../../../../lib/practiceParentTitles" import { isPracticeParentUnlinkNotLinkedError, mapPracticeParentUnlinkError, @@ -62,6 +64,11 @@ export function PracticeParentsField({ }: PracticeParentsFieldProps) { const kindOptions = isExamPrep ? EXAM_PREP_KIND_OPTIONS : LMS_KIND_OPTIONS const rows = parents.length > 0 ? parents : [newParentRow(isExamPrep ? "CATALOG_COURSE" : "LESSON")] + const savedParents = useMemo( + () => dedupeParents(parents.filter((parent) => parent.parent_id > 0)), + [parents], + ) + const { titles, loading: titlesLoading } = usePracticeParentTitles(savedParents) const [unlinkingKey, setUnlinkingKey] = useState(null) const canPersistUnlink = practiceId != null && Number.isFinite(practiceId) && practiceId > 0 @@ -88,7 +95,7 @@ export function PracticeParentsField({ const hasSavedParent = row.parent_id > 0 && isPracticeParentKind(row.parent_kind) if (canPersistUnlink && hasSavedParent) { - const label = formatPracticeParentLabel(row) + const label = formatPracticeParentDisplayLabel(row, titles) const remaining = parentsFromPractice({ parents }).filter( (p) => parentKey(p) !== parentKey(row), ) @@ -125,9 +132,7 @@ export function PracticeParentsField({ toast.info("This location was already removed.") return } - toast.error("Could not remove location", { - description: mapPracticeParentUnlinkError(err), - }) + notifyApiError(err, "Could not remove location") } finally { setUnlinkingKey(null) } @@ -163,39 +168,51 @@ export function PracticeParentsField({ const key = parentKey(row) const isLocked = Boolean(lockedParentKey && key === lockedParentKey && row.parent_id > 0) const isUnlinking = unlinkingKey === key + const isSavedLocation = row.parent_id > 0 && isPracticeParentKind(row.parent_kind) + const locationLabel = isSavedLocation + ? formatPracticeParentDisplayLabel(row, titles) + : null return (
  • - - 0 ? row.parent_id : ""} - onChange={(e) => - updateRow(index, { parent_id: Number(e.target.value) || 0 }) - } - placeholder="Parent id" - className="h-9 w-28 rounded-[8px] border-grayScale-200 font-mono text-sm" - /> - - {row.parent_kind} parent id from the content hierarchy - + {isSavedLocation ? ( + + {titlesLoading ? "Loading location…" : locationLabel} + + ) : ( + <> + + 0 ? row.parent_id : ""} + onChange={(e) => + updateRow(index, { parent_id: Number(e.target.value) || 0 }) + } + placeholder="Parent id" + className="h-9 w-28 rounded-[8px] border-grayScale-200 font-mono text-sm" + /> + + {row.parent_kind} parent id from the content hierarchy + + + )}
  • @@ -387,6 +429,42 @@ export function TeamMemberDetailPage() {
    + + {confirmDialog && ( +
    +
    +
    +

    Confirm Status Change

    + +
    +
    +

    + Are you sure you want to change the status of{" "} + {fullName || "this team member"} to{" "} + {confirmDialog.newStatus}? +

    +
    +
    + + +
    +
    +
    + )}
    ) } diff --git a/src/pages/user-log/components/ActivityLogListPanel.tsx b/src/pages/user-log/components/ActivityLogListPanel.tsx index 886ea46..e7c0bf9 100644 --- a/src/pages/user-log/components/ActivityLogListPanel.tsx +++ b/src/pages/user-log/components/ActivityLogListPanel.tsx @@ -17,8 +17,8 @@ import { User, } from "lucide-react" import { toast } from "sonner" +import { getApiErrorMessage, notifyApiError } from "../../../lib/apiErrors" import { - activityLogApiErrorMessage, getActivityLogById, getActivityLogs, } from "../../../api/activity-logs.api" @@ -151,8 +151,9 @@ export function ActivityLogListPanel({ console.error("Failed to fetch activity logs:", e) setLogs([]) setTotalCount(0) - setError(activityLogApiErrorMessage(e, "Failed to load activity logs")) - toast.error(activityLogApiErrorMessage(e, "Failed to load activity logs")) + const msg = getApiErrorMessage(e, "Failed to load activity logs") + setError(msg) + notifyApiError(e, "Failed to load activity logs") } finally { setLoading(false) } @@ -175,7 +176,7 @@ export function ActivityLogListPanel({ setSelectedLog(log) } catch (e) { console.error("Failed to fetch log detail:", e) - toast.error(activityLogApiErrorMessage(e, "Failed to load log detail")) + notifyApiError(e, "Failed to load log detail") setDialogOpen(false) } finally { setDetailLoading(false) diff --git a/src/pages/user-management/UserDetailPage.tsx b/src/pages/user-management/UserDetailPage.tsx index 5e624ab..556dee0 100644 --- a/src/pages/user-management/UserDetailPage.tsx +++ b/src/pages/user-management/UserDetailPage.tsx @@ -10,6 +10,7 @@ import { PlayCircle, Target, UserPlus, + X, } from "lucide-react"; import { Link, useParams } from "react-router-dom"; import { Badge } from "../../components/ui/badge"; @@ -23,7 +24,11 @@ import { getUserLearningActivity, getUserRecentActivity, getUserSubscriptions, + updateUserStatus, + type UserStatus, } from "../../api/users.api"; +import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"; +import { toast } from "sonner"; import { SpinnerIcon } from "../../components/ui/spinner-icon"; import type { UserProfileData, UserRecentActivityItem } from "../../types/user.types"; import type { UserLearningActivityData, UserSubscriptionsData } from "../../types/userAdmin.types"; @@ -160,6 +165,10 @@ export function UserDetailPage() { const [recentActivityItems, setRecentActivityItems] = useState([]); const [recentActivityLoading, setRecentActivityLoading] = useState(false); const [recentActivityError, setRecentActivityError] = useState(null); + const [updatingStatus, setUpdatingStatus] = useState(false); + const [confirmDialog, setConfirmDialog] = useState<{ + nextStatus: UserStatus; + } | null>(null); useEffect(() => { const userId = Number(id); @@ -201,10 +210,7 @@ export function UserDetailPage() { } catch (err) { console.error("Failed to load learning activity", err); setLearningActivity(null); - const message = - (err as { response?: { data?: { message?: string } } })?.response?.data?.message || - "Failed to load learning activity."; - setLearningActivityError(message); + setLearningActivityError(getApiErrorMessage(err, "Failed to load learning activity.")); } finally { setLearningActivityLoading(false); } @@ -227,10 +233,7 @@ export function UserDetailPage() { } catch (err) { console.error("Failed to load subscriptions", err); setSubscriptions(null); - const message = - (err as { response?: { data?: { message?: string } } })?.response?.data?.message || - "Failed to load subscriptions."; - setSubscriptionsError(message); + setSubscriptionsError(getApiErrorMessage(err, "Failed to load subscriptions.")); } finally { setSubscriptionsLoading(false); } @@ -256,10 +259,7 @@ export function UserDetailPage() { } catch (err) { console.error("Failed to load recent activity", err); setRecentActivityItems([]); - const message = - (err as { response?: { data?: { message?: string } } })?.response?.data?.message || - "Failed to load recent activity."; - setRecentActivityError(message); + setRecentActivityError(getApiErrorMessage(err, "Failed to load recent activity.")); } finally { setRecentActivityLoading(false); } @@ -268,6 +268,33 @@ export function UserDetailPage() { void loadRecent(); }, [id]); + const handleStatusToggleClick = () => { + if (!user || updatingStatus) return; + const isCurrentlyActive = user.status === "ACTIVE"; + const nextStatus: UserStatus = isCurrentlyActive ? "DEACTIVATED" : "ACTIVE"; + setConfirmDialog({ nextStatus }); + }; + + const handleConfirmStatusUpdate = async () => { + if (!user || !confirmDialog) return; + const { nextStatus } = confirmDialog; + const nextActive = nextStatus === "ACTIVE"; + const previousStatus = user.status; + + setUpdatingStatus(true); + setUser((prev) => (prev ? { ...prev, status: nextStatus } : prev)); + try { + await updateUserStatus({ user_id: user.id, status: nextStatus }); + toast.success(`User ${nextActive ? "activated" : "deactivated"} successfully`); + } catch (err: unknown) { + setUser((prev) => (prev ? { ...prev, status: previousStatus } : prev)); + notifyApiError(err, "Failed to update user status"); + } finally { + setUpdatingStatus(false); + setConfirmDialog(null); + } + }; + if (loadingUser) return ; if (userError || !user) { @@ -298,6 +325,7 @@ export function UserDetailPage() { const fullName = `${user.first_name} ${user.last_name}`.trim(); const initials = `${user.first_name?.[0] ?? ""}${user.last_name?.[0] ?? ""}`.toUpperCase(); const profilePicture = user.profile_picture_url?.trim() || undefined; + const isActive = user.status === "ACTIVE"; const contactFields = [ { icon: Mail, label: "Email", value: displayValue(user.email) }, @@ -315,12 +343,21 @@ export function UserDetailPage() { Back to Users -
    -

    Learners

    -

    {fullName}

    -

    - User #{user.id} · {formatRoleLabel(user.role)} -

    +
    +
    +

    Learners

    +

    {fullName}

    +

    + User #{user.id} · {formatRoleLabel(user.role)} +

    +
    +
    @@ -514,6 +551,42 @@ export function UserDetailPage() {
    + + {confirmDialog && ( +
    +
    +
    +

    Confirm Status Change

    + +
    +
    +

    + Are you sure you want to change the status of{" "} + {fullName || "this user"} to{" "} + {confirmDialog.nextStatus.toLowerCase()}? +

    +
    +
    + + +
    +
    +
    + )}
    ); } diff --git a/src/pages/user-management/UsersListPage.tsx b/src/pages/user-management/UsersListPage.tsx index 94b4fbf..864e717 100644 --- a/src/pages/user-management/UsersListPage.tsx +++ b/src/pages/user-management/UsersListPage.tsx @@ -1,3 +1,4 @@ +import { notifyApiError } from "../../lib/apiErrors" import { ChevronDown, ChevronLeft, ChevronRight, Search, TrendingUp, UserCheck, Users, X } from "lucide-react" import { useEffect, useMemo, useState } from "react" import { useNavigate } from "react-router-dom" @@ -300,9 +301,7 @@ export function UsersListPage() { toast.success(`User ${nextActive ? "activated" : "deactivated"} successfully`) } catch (err: any) { setToggledStatuses((prev) => ({ ...prev, [id]: previousActive })) - toast.error("Failed to update user status", { - description: err?.response?.data?.message || "Please try again.", - }) + notifyApiError(err, "Failed to update user status") } finally { setUpdatingStatusIds((prev) => { const next = new Set(prev) diff --git a/src/types/axios.d.ts b/src/types/axios.d.ts new file mode 100644 index 0000000..5e3e203 --- /dev/null +++ b/src/types/axios.d.ts @@ -0,0 +1,8 @@ +import "axios" + +declare module "axios" { + export interface AxiosRequestConfig { + /** When true, failed responses will not trigger a global error toast. */ + skipErrorToast?: boolean + } +} diff --git a/src/types/course.types.ts b/src/types/course.types.ts index b87967f..b8fdc2b 100644 --- a/src/types/course.types.ts +++ b/src/types/course.types.ts @@ -805,6 +805,7 @@ export interface PracticeFullQuestionSet { owner_type?: string owner_id?: number persona?: string | null + persona_id?: number | null shuffle_questions?: boolean status?: PracticePublishStatus | string time_limit_minutes?: number | null