Improve admin UX for practices, personas, navigation, and team management.

Add edit-practice dirty-state save gating, back navigation helpers, realistic persona avatars with circular cropping, global API error toasts, team invite role fixes, user/team block-unblock on detail pages, and related content-management polish.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-03 07:56:43 -07:00
parent 2e59a446e5
commit 31cc7baa32
123 changed files with 1236 additions and 912 deletions

View File

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

View File

@ -10,11 +10,30 @@ import type {
GetPermissionsResponse,
BulkRoleDeactivateResponse,
BulkRoleReactivateResponse,
Role,
} from "../types/rbac.types"
export const getRoles = (params?: GetRolesParams) =>
http.get<GetRolesResponse>("/rbac/roles", { params })
/** Fetch every RBAC role across paginated list responses. */
export async function fetchAllRoles(): Promise<Role[]> {
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<GetRoleDetailResponse>(`/rbac/roles/${roleId}`)

View File

@ -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<InviteTeamMemberResponse>("/team/members/invite", data)
http.post<InviteTeamMemberResponse>("/team/members/invite", data, {
skipErrorToast: true,
})
/** GET /team/invitations/verify?token= — public (accept-invite page). */
export const verifyTeamInvitation = (token: string) =>

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

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

View File

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

View File

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

View File

@ -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 (
<button
type="button"
onClick={() => navigateBack(navigate, fallbackTo)}
className={cn(
"group flex w-fit items-center gap-2 text-[15px] font-medium text-grayScale-600 transition-colors hover:text-brand-500",
className,
)}
>
<ArrowLeft
className={cn(
"h-4 w-4 transition-transform group-hover:-translate-x-0.5",
iconClassName,
)}
/>
{label}
</button>
);
}

View File

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

View File

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

View File

@ -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 (
<div
className={cn(
"inline-flex shrink-0 overflow-hidden rounded-full bg-grayScale-100",
"aspect-square",
SIZE_CLASSES[size],
selected && "ring-[3px] ring-brand-500 ring-offset-2 ring-offset-white",
className,
)}
>
<img
src={src}
alt={alt}
className="h-full w-full object-cover object-center"
draggable={false}
/>
</div>
)
}

View File

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

View File

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

View File

@ -19,7 +19,11 @@ export const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} />
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full object-cover object-center", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName

View File

@ -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<PersonaCardModel[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(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()

45
src/lib/apiErrors.ts Normal file
View File

@ -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<string, unknown>
if (typeof record.message === "string" && record.message.trim()) {
return record.message.trim()
}
if (typeof record.error === "string" && record.error.trim()) {
return record.error.trim()
}
}
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<string, unknown>)[API_ERROR_NOTIFIED] = true
}
}
export function wasApiErrorNotified(error: unknown): boolean {
return Boolean(
error && typeof error === "object" && (error as Record<string, unknown>)[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)
}

14
src/lib/navigateBack.ts Normal file
View File

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

View File

@ -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<string, string> = {
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 {

View File

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

View File

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

View File

@ -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<number>,
map: PracticeParentTitleMap,
): Promise<void> {
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<number>,
map: PracticeParentTitleMap,
@ -230,18 +252,23 @@ export async function resolvePracticeParentTitles(
const normalized = dedupeParents(parents)
const unresolvedCourses = new Set<number>()
const unresolvedCatalogCourses = new Set<number>()
const unresolvedUnits = new Set<number>()
const unresolvedModules = new Set<number>()
const unresolvedLessons = new Set<number>()
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)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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() {
</p>
<div className="flex flex-col gap-4 w-full max-w-[400px]">
<Button
onClick={() => navigate(backPath)}
onClick={goBack}
className="h-14 rounded-[6px] bg-[#9E2891] font-bold shadow-xl shadow-brand-500/20 text-[16px] text-white "
>
{backLabel}
@ -626,7 +622,7 @@ export function AddPracticeFlow() {
formData={formData}
setFormData={setFormData}
nextStep={nextStep}
onCancel={() => navigate(backPath)}
onCancel={goBack}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay}
parentSummary={parentSummary}
@ -755,13 +751,7 @@ export function AddPracticeFlow() {
<div className="space-y-8 px-6 pb-16 pt-6">
<div className="mx-auto max-w-7xl w-full">
<div className="flex items-center justify-between mb-8">
<Link
to={backPath}
className="flex items-center gap-2 text-[15px] font-medium text-grayScale-600 transition-colors hover:text-brand-500 decoration-none"
>
<ArrowLeft className="h-4 w-4" />
{backLabel}
</Link>
<PageBackLink fallbackTo={backPath} label={backLabel} />
</div>
<div className=" mb-10">
@ -772,7 +762,7 @@ export function AddPracticeFlow() {
<Button
variant="outline"
className="rounded-[8px] border-grayScale-200 text-grayScale-600 h-10 px-6 font-bold bg-white hover:bg-grayScale-50"
onClick={() => navigate(backPath)}
onClick={goBack}
>
Cancel
</Button>

View File

@ -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() {
<Button
variant="ghost"
size="icon"
onClick={() => navigate("/content/questions")}
onClick={() => navigateBack(navigate, "/content/questions")}
className="h-9 w-9 shrink-0 rounded-lg bg-grayScale-50 hover:bg-brand-500/10 hover:text-brand-500"
>
<ArrowLeft className="h-4 w-4" />

View File

@ -1,7 +1,9 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import { ArrowLeft } from "lucide-react";
import { PageBackLink } from "../../components/navigation/PageBackLink";
import { navigateBack } from "../../lib/navigateBack";
import { Button } from "../../components/ui/button";
import { Stepper } from "../../components/ui/stepper";
import { createModuleLesson } from "../../api/courses.api";
@ -62,6 +64,7 @@ export function AddVideoFlow() {
const prevStep = () => setCurrentStep((prev) => Math.max(prev - 1, 1));
const backPath = `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}`;
const goBack = () => navigateBack(navigate, backPath);
const handleCreateLesson = async (publishStatus: PracticePublishStatus) => {
const mid = Number(moduleId);
@ -118,10 +121,7 @@ export function AddVideoFlow() {
setIsPublished(true);
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to create lesson";
toast.error(msg);
notifyApiError(e, "Failed to create lesson");
} finally {
setPublishing(false);
}
@ -155,7 +155,7 @@ export function AddVideoFlow() {
<div className="flex flex-col gap-4 w-full max-w-[400px]">
<Button
onClick={() => navigate(backPath)}
onClick={goBack}
className="h-12 rounded-[6px] bg-brand-500 font-bold text-[17px] text-white transition-all active:scale-95"
>
View module
@ -189,17 +189,11 @@ export function AddVideoFlow() {
<div className="space-y-8 pb-32 px-6 pt-6 min-h-screen ">
<div className="mx-auto max-w-7xl w-full">
<div className="flex items-center justify-between mb-8">
<Link
to={backPath}
className="flex items-center gap-2 text-[15px] font-medium text-grayScale-500 transition-colors hover:text-brand-500 decoration-none"
>
<ArrowLeft className="h-4 w-4" />
Back to module
</Link>
<PageBackLink fallbackTo={backPath} label="Back to module" className="text-grayScale-500" />
<Button
variant="outline"
className="rounded-[8px] border-grayScale-200 text-grayScale-600 h-10 px-6 font-bold bg-white hover:bg-grayScale-50"
onClick={() => navigate(backPath)}
onClick={goBack}
>
Cancel
</Button>

View File

@ -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 (
<div className="space-y-6">
<PageBackLink fallbackTo="/content" label="Back" />
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>

View File

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

View File

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

View File

@ -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 (
<div className="space-y-6">
<PageBackLink fallbackTo="/content" label="Back" />
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">

View File

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

View File

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

View File

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

View File

@ -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() {
<div className=" border-b border-grayScale-100 sticky top-0 z-50 bg-white/95 backdrop-blur">
<div className="max-w-[1440px] mx-auto py-6 px-4 sm:px-6">
<div className="flex items-center justify-between mb-8">
<Link
to="/new-content/question-types"
className="flex items-center gap-2 text-[15px] font-medium text-grayScale-600 transition-colors hover:text-brand-500 group"
>
<ArrowLeft className="h-5 w-5 transition-transform group-hover:-translate-x-1" />
Back to Question Type Library
</Link>
<PageBackLink
fallbackTo="/new-content/question-types"
label="Back to Question Type Library"
iconClassName="h-5 w-5 group-hover:-translate-x-1"
/>
</div>
<div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-6">

View File

@ -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<string | null>(null);
const [selectedPersona, setSelectedPersona] = useState<string | null>(null);
const [loadedPersonaId, setLoadedPersonaId] = useState<number | null>(null);
const [preservedQuestionSet, setPreservedQuestionSet] =
useState<PreservedQuestionSetFields>({
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<string | null>(null);
const [initialSnapshot, setInitialSnapshot] = useState<string | null>(null);
const initialParentsRef = useRef<PracticeParent[]>([]);
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 (
<div className="flex min-h-screen flex-col items-center justify-center px-6 text-center">
<p className="text-lg font-semibold text-grayScale-800">Invalid practice link</p>
<Button className="mt-6" variant="outline" onClick={() => navigate(-1)}>
<Button className="mt-6" variant="outline" onClick={goBack}>
Go back
</Button>
</div>
@ -492,7 +524,7 @@ export function EditPracticeFlow() {
<p className="text-lg font-semibold text-grayScale-800">Could not load practice</p>
<p className="mt-2 max-w-md text-sm text-grayScale-600">{loadError}</p>
<div className="mt-6 flex gap-3">
<Button variant="outline" onClick={() => navigate(backPath)}>
<Button variant="outline" onClick={() => goBack()}>
{backLabel}
</Button>
<Button onClick={() => window.location.reload()}>Try again</Button>
@ -501,33 +533,6 @@ export function EditPracticeFlow() {
);
}
if (isSaved) {
return (
<div className="flex flex-col items-center justify-center min-h-screen px-4 text-center pb-20 animate-in fade-in zoom-in duration-500">
<div className="mb-10 relative">
<div className="absolute inset-0 bg-brand-500/10 blur-3xl rounded-full" />
<img
src={successIcon}
alt="Success"
className="h-[128px] w-[128px] relative"
/>
</div>
<h1 className="text-[28px] font-bold text-grayScale-900 mb-2">
Practice Updated Successfully!
</h1>
<p className="text-grayScale-600 text-md mb-14 max-w-lg font-medium leading-relaxed">
Your changes to this practice have been saved.
</p>
<Button
onClick={() => navigate(backPath)}
className="h-14 rounded-[6px] bg-[#9E2891] font-bold shadow-xl shadow-brand-500/20 text-[16px] text-white w-full max-w-[400px]"
>
{backLabel}
</Button>
</div>
);
}
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() {
<div className="space-y-8 px-6 pb-16 pt-6">
<div className="mx-auto max-w-7xl w-full">
<div className="flex items-center justify-between mb-8">
<Link
to={backPath}
className="flex items-center gap-2 text-[15px] font-medium text-grayScale-600 transition-colors hover:text-brand-500 decoration-none"
>
<ArrowLeft className="h-4 w-4" />
{backLabel}
</Link>
<PageBackLink fallbackTo={backPath} label={backLabel} />
</div>
<div className="mb-10">
<div className="flex items-center justify-between">
<div className="flex items-center justify-between gap-4">
<h1 className="text-3xl font-bold text-[#0F172A]">Edit Practice</h1>
<Button
variant="outline"
className="rounded-[8px] border-grayScale-200 text-grayScale-600 h-10 px-6 font-bold bg-white hover:bg-grayScale-50"
onClick={() => navigate(backPath)}
>
Cancel
</Button>
<div className="flex shrink-0 items-center gap-3">
<Button
className="h-10 rounded-[8px] bg-brand-500 px-6 font-bold text-white shadow-md shadow-brand-500/20 hover:bg-brand-600 disabled:opacity-50"
disabled={submitting || !hasUnsavedChanges}
onClick={handleSaveChanges}
>
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving…
</>
) : (
"Save changes"
)}
</Button>
<Button
variant="outline"
className="h-10 rounded-[8px] border-grayScale-200 bg-white px-6 font-bold text-grayScale-600 hover:bg-grayScale-50"
disabled={submitting}
onClick={() => goBack()}
>
Cancel
</Button>
</div>
</div>
<p className="text-grayScale-400 text-base">
Update story details, persona, and questions for practice #{practiceId}.

View File

@ -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 (
<div className="mx-auto max-w-6xl space-y-6">
<PageBackLink fallbackTo="/content" label="Back to Content Management" />
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-700 ring-1 ring-inset ring-brand-100">
@ -676,9 +679,6 @@ export function HumanLanguageHierarchyPage() {
<p className="text-sm text-grayScale-500">Hierarchy management</p>
</div>
</div>
<Button type="button" variant="outline" asChild>
<Link to="/content">Back to Content Management</Link>
</Button>
</div>
<AdminFiltersPanel

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Link, useLocation, useNavigate, useParams } from "react-router-dom"
import { ArrowLeft, BookOpen, Eye, FileText, Plus, Search, Trophy, Video } from "lucide-react"
@ -184,7 +185,7 @@ export function HumanLanguageSubModulePage() {
console.error(e)
setMetaError("Failed to load sub-module")
setSubCourse(null)
toast.error("Failed to load sub-module")
notifyApiError(e, "Failed to load sub-module")
} finally {
setLoadingMeta(false)
}
@ -202,7 +203,7 @@ export function HumanLanguageSubModulePage() {
setSets(list)
} catch (e) {
console.error(e)
toast.error("Failed to load question sets")
notifyApiError(e, "Failed to load question sets")
setSets([])
} finally {
setSetsLoading(false)
@ -217,7 +218,7 @@ export function HumanLanguageSubModulePage() {
setVideos(res.data?.data?.videos ?? [])
} catch (e) {
console.error(e)
toast.error("Failed to load videos")
notifyApiError(e, "Failed to load videos")
setVideos([])
} finally {
setVideosLoading(false)
@ -233,7 +234,7 @@ export function HumanLanguageSubModulePage() {
setLessons(list)
} catch (e) {
console.error(e)
toast.error("Failed to load lessons")
notifyApiError(e, "Failed to load lessons")
setLessons([])
} finally {
setLessonsLoading(false)
@ -250,7 +251,7 @@ export function HumanLanguageSubModulePage() {
setLessonDetail(res.data?.data ?? null)
} catch (e) {
console.error(e)
toast.error("Failed to load lesson detail")
notifyApiError(e, "Failed to load lesson detail")
} finally {
setLessonDetailLoading(false)
}
@ -298,7 +299,7 @@ export function HumanLanguageSubModulePage() {
await fetchLessons()
} catch (error) {
console.error(error)
toast.error("Failed to update lesson")
notifyApiError(error, "Failed to update lesson")
} finally {
setLessonUpdateSaving(false)
}
@ -317,7 +318,7 @@ export function HumanLanguageSubModulePage() {
await fetchLessons()
} catch (error) {
console.error(error)
toast.error("Failed to soft delete lesson")
notifyApiError(error, "Failed to soft delete lesson")
} finally {
setLessonSoftDeleteSaving(false)
}

View File

@ -1,6 +1,8 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Plus, ArrowRight, Pencil, Trash2, X } from "lucide-react";
import { Link } 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";
@ -147,10 +149,7 @@ export function LearnEnglishPage() {
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);
}
@ -198,10 +197,7 @@ export function LearnEnglishPage() {
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);
}
@ -238,10 +234,7 @@ export function LearnEnglishPage() {
await fetchPrograms();
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to create program";
toast.error(msg);
notifyApiError(e, "Failed to create program");
} finally {
setCreateSaving(false);
}
@ -277,10 +270,7 @@ export function LearnEnglishPage() {
await fetchPrograms();
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update program";
toast.error(msg);
notifyApiError(e, "Failed to update program");
} finally {
setSavingEdit(false);
}
@ -304,10 +294,7 @@ export function LearnEnglishPage() {
nextStatus === "PUBLISHED" ? "Program published" : "Program saved as draft",
);
} catch (e: unknown) {
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update program status";
toast.error(msg);
notifyApiError(e, "Failed to update program status");
} finally {
setPublishStatusUpdatingId(null);
}
@ -329,10 +316,7 @@ export function LearnEnglishPage() {
nextTier === "PREMIUM" ? "Program set to Premium" : "Program set to Free",
);
} catch (e: unknown) {
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update program access tier";
toast.error(msg);
notifyApiError(e, "Failed to update program access tier");
} finally {
setAccessTierUpdatingId(null);
}
@ -348,10 +332,7 @@ export function LearnEnglishPage() {
await fetchPrograms();
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to delete program";
toast.error(msg);
notifyApiError(e, "Failed to delete program");
} finally {
setDeleting(false);
}
@ -401,9 +382,7 @@ export function LearnEnglishPage() {
console.error(e);
setError("Failed to load programs");
setPrograms([]);
toast.error("Could not load programs", {
description: "Check your connection or try again.",
});
notifyApiError(e, "Could not load programs");
} finally {
setLoading(false);
}
@ -415,6 +394,7 @@ export function LearnEnglishPage() {
return (
<div className="space-y-8">
<PageBackLink fallbackTo="/new-content" label="Back to Content Management" />
{/* Header section */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>

View File

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

View File

@ -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() {
<Button
className="mt-6 rounded-[6px]"
variant="outline"
onClick={() => navigate(backPath)}
onClick={goBack}
>
{backLabel}
</Button>
@ -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}.
</p>
<Button
onClick={() => navigate(backPath)}
onClick={goBack}
className="h-14 rounded-[6px] bg-brand-500 px-10 text-[16px] font-bold text-white shadow-xl shadow-brand-500/20"
>
{backLabel}
@ -253,13 +255,7 @@ export function LinkExistingPracticeFlow() {
<div className="space-y-8 px-6 pb-16 pt-6">
<div className="mx-auto w-full max-w-7xl">
<div className="mb-8 flex items-center justify-between">
<Link
to={backPath}
className="flex items-center gap-2 text-[15px] font-medium text-grayScale-600 decoration-none transition-colors hover:text-brand-500"
>
<ArrowLeft className="h-4 w-4" />
{backLabel}
</Link>
<PageBackLink fallbackTo={backPath} label={backLabel} />
</div>
<div className="mb-10">
@ -268,7 +264,7 @@ export function LinkExistingPracticeFlow() {
<Button
variant="outline"
className="h-10 rounded-[8px] border-grayScale-200 bg-white px-6 font-bold text-grayScale-600 hover:bg-grayScale-50"
onClick={() => navigate(backPath)}
onClick={goBack}
>
Cancel
</Button>
@ -304,7 +300,7 @@ export function LinkExistingPracticeFlow() {
selectedPracticeId={selectedPractice?.id ?? null}
onSelect={setSelectedPractice}
nextStep={() => setCurrentStep(2)}
onCancel={() => navigate(backPath)}
onCancel={goBack}
/>
) : selectedPractice ? (
<LinkExistingPracticeReviewStep

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react";
import { ArrowLeft, Video, Calendar, Trash2, X } from "lucide-react";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
@ -246,7 +247,7 @@ export function ModuleDetailPage() {
setLessons([]);
setLessonsLoadError("Failed to load lessons. Please try again.");
} else {
toast.error("Failed to refresh lessons");
notifyApiError(err, "Failed to refresh lessons");
}
} finally {
if (showPageLoading) {
@ -337,7 +338,7 @@ export function ModuleDetailPage() {
);
} 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 {
setPublishStatusPracticeId(null);
}
@ -368,9 +369,7 @@ export function ModuleDetailPage() {
await loadModulePractices();
return;
}
toast.error("Could not remove from module", {
description: mapPracticeParentUnlinkError(e),
});
notifyApiError(err, "Could not remove from module");
} finally {
setUnlinkingPractice(false);
}
@ -421,10 +420,7 @@ export function ModuleDetailPage() {
await loadModuleLessons({ showPageLoading: false });
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update lesson";
toast.error(msg);
notifyApiError(e, "Failed to update lesson");
} finally {
setSavingLessonEdit(false);
}
@ -451,13 +447,10 @@ export function ModuleDetailPage() {
);
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ??
(nextStatus === "PUBLISHED"
? "Failed to publish lesson"
: "Failed to save lesson as draft");
toast.error(msg);
notifyApiError(
e,
nextStatus === "PUBLISHED" ? "Failed to publish lesson" : "Failed to save lesson as draft",
);
} finally {
setPublishStatusLessonId(null);
}
@ -482,10 +475,7 @@ export function ModuleDetailPage() {
);
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update lesson access tier";
toast.error(msg);
notifyApiError(e, "Failed to update lesson access tier");
} finally {
setAccessTierLessonId(null);
}
@ -501,10 +491,7 @@ export function ModuleDetailPage() {
await loadModuleLessons({ showPageLoading: false });
} catch (e: unknown) {
console.error(e);
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to delete lesson";
toast.error(msg);
notifyApiError(e, "Failed to delete lesson");
} finally {
setDeletingLessonInFlight(false);
}

View File

@ -1,3 +1,4 @@
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { BookOpen, GraduationCap, Layers, PlayCircle, RefreshCw, Pencil, Search, Trash2 } from "lucide-react"
import { useSearchParams } from "react-router-dom"
@ -39,6 +40,7 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
import { CreatePracticeWizard } from "./components/CreatePracticeWizard"
import type { PracticeParentKind } from "../../types/course.types"
import { cn } from "../../lib/utils"
import { PageBackLink } from "../../components/navigation/PageBackLink"
type ParentTab = "course" | "module" | "lesson"
@ -336,7 +338,7 @@ export function PracticeDetailsPage() {
setPractice(list[0] ?? null)
} catch (e: unknown) {
const err = e as { response?: { data?: { message?: string } } }
setLoadError(err.response?.data?.message || "Failed to load practices for this parent.")
setLoadError(getApiErrorMessage(err, "Failed to load practices for this parent."))
setPractice(null)
setTotalCount(0)
} finally {
@ -609,7 +611,7 @@ export function PracticeDetailsPage() {
setEditOpen(false)
} catch (e: unknown) {
const err = e as { response?: { data?: { message?: string } } }
toast.error(err.response?.data?.message || "Failed to update practice")
notifyApiError(err, "Failed to update practice")
} finally {
setSavePracticeLoading(false)
}
@ -632,7 +634,7 @@ export function PracticeDetailsPage() {
}
} 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 {
setDeletePracticeLoading(false)
}
@ -658,6 +660,7 @@ export function PracticeDetailsPage() {
return (
<div className="space-y-6">
<PageBackLink fallbackTo="/content" label="Back" />
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight text-grayScale-600">Practice Management</h1>

View File

@ -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 (
<div className="space-y-8">
<PageBackLink fallbackTo="/content/practices" label="Back to Practice Management" />
{/* Page Header */}
<div>
<h1 className="text-2xl font-bold tracking-tight text-grayScale-600">Practice Management</h1>

View File

@ -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 (
<div className="space-y-8 pt-10">
{/* Navigation */}
<Link
to="/new-content/learn-english"
className="flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-500"
>
<ArrowLeft className="h-4 w-4" />
Back to Programs
</Link>
<PageBackLink fallbackTo="/new-content/learn-english" label="Back to Programs" className="text-sm text-grayScale-500" />
{/* Header section */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">

View File

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

View File

@ -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 (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageBackLink fallbackTo="/new-content" label="Back to Content Management" />
{/* Header section */}
<div className="space-y-1.5 pt-2">
<h1 className="text-[28px] font-bold tracking-tight text-grayScale-900">

View File

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

View File

@ -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 (
<div className="space-y-8 animate-in fade-in duration-500 pb-20">
<div className="space-y-6">
<Link
to="/new-content"
className="flex items-center gap-2 text-[15px] font-bold text-grayScale-600 transition-colors hover:text-brand-500 group w-fit"
>
<ArrowLeft className="h-5 w-5 transition-transform group-hover:-translate-x-1" />
Back to Content Management
</Link>
<PageBackLink
fallbackTo="/new-content"
label="Back to Content Management"
className="font-bold"
iconClassName="h-5 w-5 group-hover:-translate-x-1"
/>
<div className="flex items-start justify-between gap-4 flex-wrap">
<div className="space-y-1">

View File

@ -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 (
<div className="space-y-8">
<PageBackLink fallbackTo="/content" label="Back" />
{/* Page Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>

View File

@ -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 (
<div className="space-y-8 animate-in fade-in duration-500 pb-20">
<div className="space-y-6">
<Link
to="/new-content"
className="flex items-center gap-2 text-[15px] font-bold text-grayScale-600 transition-colors hover:text-brand-500 group w-fit"
>
<ArrowLeft className="h-5 w-5 transition-transform group-hover:-translate-x-1" />
Back to Content Management
</Link>
<PageBackLink fallbackTo="/new-content" label="Back to Content Management" iconClassName="h-5 w-5 group-hover:-translate-x-1" />
<div className="space-y-1">
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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({
</div>
)}
<div className="flex flex-col items-center gap-4">
<div
className={cn(
"rounded-full p-[3px] transition-all duration-300",
isSelected ? "bg-brand-500" : "bg-transparent",
)}
>
<Avatar className="h-24 w-24 border-2 border-white">
<AvatarImage src={persona.avatar} alt={persona.name} />
<AvatarFallback>
{persona.name.substring(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
</div>
<PersonaAvatar
src={persona.avatar}
alt={persona.name}
size="xl"
selected={isSelected}
/>
<div className="space-y-1 text-center">
<span className="block text-lg font-bold text-grayScale-700">
{persona.name}

View File

@ -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<string | null>(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 (
<li
key={`${index}-${row.parent_kind}`}
className="flex flex-wrap items-center gap-2 rounded-xl border border-grayScale-200 bg-grayScale-50/50 px-3 py-2.5"
>
<select
value={row.parent_kind}
disabled={disabled || isLocked || isUnlinking}
onChange={(e) =>
updateRow(index, { parent_kind: e.target.value as PracticeParentKind })
}
className="h-9 rounded-[8px] border border-grayScale-200 bg-white px-2.5 text-sm font-medium text-grayScale-700 focus:outline-none focus:ring-2 focus:ring-brand-200"
>
{kindOptions.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
<Input
type="number"
min={1}
disabled={disabled || isLocked || isUnlinking}
value={row.parent_id > 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"
/>
<span className="text-xs text-grayScale-400 hidden sm:inline">
{row.parent_kind} parent id from the content hierarchy
</span>
{isSavedLocation ? (
<span className="min-w-0 flex-1 text-sm font-medium text-grayScale-800">
{titlesLoading ? "Loading location…" : locationLabel}
</span>
) : (
<>
<select
value={row.parent_kind}
disabled={disabled || isLocked || isUnlinking}
onChange={(e) =>
updateRow(index, { parent_kind: e.target.value as PracticeParentKind })
}
className="h-9 rounded-[8px] border border-grayScale-200 bg-white px-2.5 text-sm font-medium text-grayScale-700 focus:outline-none focus:ring-2 focus:ring-brand-200"
>
{kindOptions.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
<Input
type="number"
min={1}
disabled={disabled || isLocked || isUnlinking}
value={row.parent_id > 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"
/>
<span className="text-xs text-grayScale-400 hidden sm:inline">
{row.parent_kind} parent id from the content hierarchy
</span>
</>
)}
<Button
type="button"
variant="ghost"

View File

@ -1,5 +1,6 @@
import { useState } from "react";
import { Edit, Info, Loader2, Play, Rocket } from "lucide-react";
import { PersonaAvatar } from "../../../../components/personas/PersonaAvatar";
import { Button } from "../../../../components/ui/button";
import { Card } from "../../../../components/ui/card";
import { cn } from "../../../../lib/utils";
@ -221,11 +222,7 @@ export function PracticeSequentialReview({
className="h-full w-full object-cover"
/>
) : persona?.avatar ? (
<img
src={persona.avatar}
alt=""
className="h-full w-full object-cover"
/>
<PersonaAvatar src={persona.avatar} alt={persona.name} size="md" />
) : (
<div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-[#E0F2FE] to-[#BFDBFE]" />
)}
@ -260,13 +257,7 @@ export function PracticeSequentialReview({
</span>
{persona ? (
<div className="flex flex-col items-center gap-1.5">
<div className="h-12 w-12 overflow-hidden rounded-full bg-grayScale-100 ring-2 ring-brand-100">
<img
src={persona.avatar}
alt=""
className="h-full w-full object-cover"
/>
</div>
<PersonaAvatar src={persona.avatar} alt={persona.name} size="md" />
<span className="text-sm font-semibold text-grayScale-900">
{persona.name}
</span>

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../../../lib/apiErrors"
import { useRef, useState, type ChangeEvent } from "react";
import { Link } from "react-router-dom";
import { Upload, ArrowRight, Loader2 } from "lucide-react";
@ -35,7 +36,7 @@ export function ScenarioStep({
setFormData({ ...formData, storyImageUrl: url });
toast.success("Story image uploaded");
} catch {
toast.error("Could not upload image");
notifyApiError(err, "Could not upload image");
} finally {
setUploadingBanner(false);
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react"
import { ArrowRight, ChevronLeft, ChevronRight, Search } from "lucide-react"
import { toast } from "sonner"
@ -7,7 +8,6 @@ import { Input } from "../../../../components/ui/input"
import { SpinnerIcon } from "../../../../components/ui/spinner-icon"
import { practiceAlreadyLinkedToParent } from "../../../../lib/attachPracticeToParent"
import { fetchAllPractices } from "../../../../lib/fetchAllPractices"
import { learnEnglishPracticeApiErrorMessage } from "../../../../lib/learnEnglishPracticePublish"
import { formatPracticeParentsSummary } from "../../../../lib/practiceParents"
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../../../lib/tablePagination"
import type { ParentContextPractice, PracticeParent } from "../../../../types/course.types"
@ -74,9 +74,7 @@ export function SelectPracticeToAttachStep({
const practices = await fetchAllPractices(unlinkedOnly, { isExamPrep })
setAllPractices(practices)
} catch (e) {
toast.error("Could not load practices", {
description: learnEnglishPracticeApiErrorMessage(e),
})
notifyApiError(e, "Could not load practices")
setAllPractices([])
} finally {
setLoading(false)

View File

@ -2,6 +2,7 @@ import { useEffect, useState } from "react"
import { ArrowLeft, Loader2 } from "lucide-react"
import { useNavigate } from "react-router-dom"
import { toast } from "sonner"
import { notifyApiError } from "../../../../lib/apiErrors"
import { Button } from "../../../../components/ui/button"
import { Card } from "../../../../components/ui/card"
import {
@ -94,12 +95,7 @@ export function QuestionTypeReviewPublishStep({
})
navigate(`/new-content/question-types?created=${id}`)
} catch (e: unknown) {
const err = e as { response?: { data?: { message?: string; error?: string } } }
const msg =
err.response?.data?.message ||
(e instanceof Error ? e.message : isEdit ? "Update failed" : "Create failed")
const detail = err.response?.data?.error
toast.error(String(msg), { description: detail ? String(detail) : undefined })
notifyApiError(e, isEdit ? "Update failed" : "Create failed")
} finally {
setSubmitting(false)
}

View File

@ -7,7 +7,8 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca
import { SpinnerIcon } from "../../components/ui/spinner-icon"
import { useFaqPermissions } from "../../hooks/useFaqPermissions"
import { deriveFaqCategories } from "../../lib/faqDisplay"
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
import { notifyApiError } from "../../lib/apiErrors"
import { isFaqForbiddenError } from "../../lib/faqErrors"
import type { FAQ, FAQStatus } from "../../types/faq.types"
import { FaqAccessDenied } from "./components/FaqAccessDenied"
import {
@ -79,10 +80,10 @@ export function EditFaqPage() {
}
if (isFaqForbiddenError(e)) {
setPermissionDenied(true)
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view this FAQ"))
notifyApiError(e, "You do not have permission to view this FAQ")
return
}
toast.error(getFaqApiErrorMessage(e, "Failed to load FAQ"))
notifyApiError(e, "Failed to load FAQ")
} finally {
setLoading(false)
}
@ -121,7 +122,7 @@ export function EditFaqPage() {
)
} catch (e: unknown) {
console.error(e)
toast.error(getFaqApiErrorMessage(e, "Failed to update FAQ"))
notifyApiError(e, "Failed to update FAQ")
} finally {
setSaving(false)
setSavingAction(null)

View File

@ -37,7 +37,8 @@ import {
formatFaqDate,
suggestNextDisplayOrder,
} from "../../lib/faqDisplay"
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
import { notifyApiError } from "../../lib/apiErrors"
import { isFaqForbiddenError } from "../../lib/faqErrors"
import { countActiveFilters } from "../../lib/adminFilterUtils"
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
@ -103,9 +104,9 @@ export function FaqsPage() {
setFaqs([])
if (isFaqForbiddenError(e)) {
setPermissionDenied(true)
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view FAQs"))
notifyApiError(e, "You do not have permission to view FAQs")
} else {
toast.error(getFaqApiErrorMessage(e, "Failed to load FAQs"))
notifyApiError(e, "Failed to load FAQs")
}
} finally {
setLoading(false)
@ -168,8 +169,7 @@ export function FaqsPage() {
)
} catch (e: unknown) {
console.error(e)
const msg = getFaqApiErrorMessage(e, "Failed to update FAQ status")
toast.error(msg)
notifyApiError(e, "Failed to update FAQ status")
} finally {
setTogglingId(null)
}

View File

@ -9,7 +9,7 @@ import {
DialogHeader,
DialogTitle,
} from "../../../components/ui/dialog"
import { getFaqApiErrorMessage } from "../../../lib/faqErrors"
import { notifyApiError } from "../../../lib/apiErrors"
import {
draftToCreatePayload,
EMPTY_FAQ_FORM_DRAFT,
@ -75,7 +75,7 @@ export function CreateFaqDialog({
onCreated?.()
} catch (e: unknown) {
console.error(e)
toast.error(getFaqApiErrorMessage(e, "Failed to create FAQ"))
notifyApiError(e, "Failed to create FAQ")
} finally {
setSaving(false)
setSavingAction(null)

View File

@ -7,6 +7,7 @@ import { Button } from "../../../components/ui/button"
import { Card, CardContent } from "../../../components/ui/card"
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
import { getSessionTeamRole, hasFaqRoleBypass } from "../../../lib/faqPermissions"
import { notifyApiError } from "../../../lib/apiErrors"
import { FAQ_FORBIDDEN_MESSAGE } from "../../../lib/faqErrors"
type FaqAccessDeniedProps = {
@ -25,10 +26,7 @@ export function FaqAccessDenied({ apiForbidden = false }: FaqAccessDeniedProps)
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
} catch (e: unknown) {
console.error(e)
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
"Failed to sync RBAC permissions"
toast.error(msg)
notifyApiError(e, "Failed to sync RBAC permissions")
} finally {
setSyncing(false)
}

View File

@ -3,7 +3,7 @@ import { Trash2 } from "lucide-react"
import { toast } from "sonner"
import { deleteFAQ } from "../../../api/faq.api"
import { Button } from "../../../components/ui/button"
import { getFaqApiErrorMessage } from "../../../lib/faqErrors"
import { notifyApiError } from "../../../lib/apiErrors"
import {
Dialog,
DialogContent,
@ -44,8 +44,7 @@ export function FaqDeleteDialog({
onDeleted?.()
} catch (e: unknown) {
console.error(e)
const msg = getFaqApiErrorMessage(e, "Failed to delete FAQ")
toast.error(msg)
notifyApiError(e, "Failed to delete FAQ")
} finally {
setDeleting(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../../lib/apiErrors"
import { useCallback, useEffect, useState } from "react"
import { Eye } from "lucide-react"
import { toast } from "sonner"
@ -36,7 +37,7 @@ export function FaqPublicPreviewDialog({
} catch (e) {
console.error(e)
setFaqs([])
toast.error("Failed to load public FAQ preview")
notifyApiError(e, "Failed to load public FAQ preview")
} finally {
setLoading(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import { Bell, List, RefreshCw } from "lucide-react"
@ -132,7 +133,7 @@ export function AllNotificationsPage() {
setError(true)
setRows([])
setTotalCount(0)
toast.error("Failed to load notifications")
notifyApiError(err, "Failed to load notifications")
} finally {
setLoading(false)
}
@ -192,7 +193,7 @@ export function AllNotificationsPage() {
setSelectedNotification(notification)
} else {
setDetailError(true)
toast.error("Failed to load notification details")
notifyApiError(err, "Failed to load notification details")
}
} finally {
setDetailLoading(false)

View File

@ -2,6 +2,7 @@ import { useMemo, useState } from "react"
import { Link, useNavigate } from "react-router-dom"
import { ArrowLeft } from "lucide-react"
import { toast } from "sonner"
import { notifyApiError } from "../../lib/apiErrors"
import {
createEmailTemplate,
parseEmailTemplateResponse,
@ -94,10 +95,7 @@ export function CreateEmailTemplatePage() {
navigate(`/notifications/email-templates/${created.slug}`)
} catch (e: unknown) {
console.error(e)
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to create email template"
toast.error(msg)
notifyApiError(e, "Failed to create email template")
} finally {
setSaving(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useEffect, useMemo, useState } from "react"
import { Link, useNavigate } from "react-router-dom"
import { Bell, CalendarClock, Mail, MailOpen, Megaphone, Search, Smartphone } from "lucide-react"
@ -24,7 +25,6 @@ import {
validateEmailComposeInput,
} from "../../lib/notificationEmailCompose"
import {
extractApiErrorMessage,
fetchAllPlatformUsers,
fetchAllTeamMembers,
formatScheduledAtLabel,
@ -507,9 +507,7 @@ export function CreateNotificationPage() {
resetForm()
} catch (err) {
toast.error("Failed to send notification", {
description: extractApiErrorMessage(err, "Please try again."),
})
notifyApiError(err, "Failed to send notification")
} finally {
setSending(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Link, useNavigate, useParams } from "react-router-dom"
import { ArrowLeft, RefreshCw, Shield, Trash2 } from "lucide-react"
@ -65,7 +66,7 @@ export function EmailTemplateDetailPage() {
console.error(e)
setError(true)
setTemplate(null)
toast.error("Failed to load email template")
notifyApiError(e, "Failed to load email template")
} finally {
setLoading(false)
}
@ -104,10 +105,7 @@ export function EmailTemplateDetailPage() {
toast.success("Email template updated")
} catch (e: unknown) {
console.error(e)
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update email template"
toast.error(msg)
notifyApiError(e, "Failed to update email template")
} finally {
setSaving(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import { Eye, Mail, Plus, RefreshCw, Search, Shield, Trash2 } from "lucide-react"
@ -45,7 +46,7 @@ export function EmailTemplatesPage() {
setError(true)
setTemplates([])
setTotalCount(0)
toast.error("Failed to load email templates")
notifyApiError(e, "Failed to load email templates")
} finally {
setLoading(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useEffect, useState, useCallback } from "react"
import {
Bell,
@ -396,7 +397,7 @@ export function NotificationsPage() {
}
} else {
setDetailError(true)
toast.error("Failed to load notification details")
notifyApiError(err, "Failed to load notification details")
}
} finally {
setDetailLoading(false)

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import {
@ -91,7 +92,7 @@ export function ScheduledNotificationsPage() {
setError(true)
setRows([])
setTotalCount(0)
toast.error("Failed to load scheduled notifications")
notifyApiError(err, "Failed to load scheduled notifications")
} finally {
setLoading(false)
}
@ -115,7 +116,7 @@ export function ScheduledNotificationsPage() {
})
await load()
} catch {
toast.error("Failed to cancel scheduled notification")
notifyApiError(err, "Failed to cancel scheduled notification")
} finally {
setCancellingId(null)
}

View File

@ -1,6 +1,7 @@
import { useState } from "react"
import { Trash2 } from "lucide-react"
import { toast } from "sonner"
import { notifyApiError } from "../../../lib/apiErrors"
import { deleteEmailTemplate } from "../../../api/emailTemplates.api"
import { Button } from "../../../components/ui/button"
import {
@ -47,10 +48,7 @@ export function EmailTemplateDeleteDialog({
onDeleted?.()
} catch (e: unknown) {
console.error(e)
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to delete email template"
toast.error(msg)
notifyApiError(e, "Failed to delete email template")
} finally {
setDeleting(false)
}

View File

@ -1,3 +1,4 @@
import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
import {
ChevronDown,
@ -168,7 +169,7 @@ export function PaymentsPage() {
setError(true)
setPayments([])
setTotalCount(0)
toast.error("Failed to load payments")
notifyApiError(e, "Failed to load payments")
} finally {
setLoading(false)
}
@ -190,7 +191,7 @@ export function PaymentsPage() {
} catch (e) {
console.error(e)
setPaymentStats(EMPTY_PAYMENT_STATS)
toast.error("Failed to load payment summary")
notifyApiError(e, "Failed to load payment summary")
} finally {
setStatsLoading(false)
}

View File

@ -30,16 +30,15 @@ import {
import { usePersonaPermissions } from "../../hooks/usePersonaPermissions"
import { countActiveFilters } from "../../lib/adminFilterUtils"
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
import { PersonaAvatar } from "../../components/personas/PersonaAvatar"
import {
formatPersonaDate,
personaAvatarUrl,
personaGenderLabel,
personaStatusLabel,
} from "../../lib/personaDisplay"
import {
getPersonaApiErrorMessage,
isPersonaForbiddenError,
} from "../../lib/personasErrors"
import { notifyApiError } from "../../lib/apiErrors"
import { isPersonaForbiddenError } from "../../lib/personasErrors"
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
import type { LmsPersona } from "../../types/persona.types"
import { CreatePersonaDialog } from "./components/CreatePersonaDialog"
@ -100,9 +99,9 @@ export function PersonasPage() {
setPersonas([])
if (isPersonaForbiddenError(e)) {
setPermissionDenied(true)
toast.error(getPersonaApiErrorMessage(e, "You do not have permission to view personas"))
notifyApiError(e, "You do not have permission to view personas")
} else {
toast.error(getPersonaApiErrorMessage(e, "Failed to load personas"))
notifyApiError(e, "Failed to load personas")
}
} finally {
setLoading(false)
@ -173,7 +172,7 @@ export function PersonasPage() {
}
} catch (e) {
console.error(e)
toast.error(getPersonaApiErrorMessage(e, "Failed to update persona status"))
notifyApiError(e, "Failed to update persona status")
} finally {
setTogglingId(null)
}
@ -299,14 +298,14 @@ export function PersonasPage() {
paginated.map((persona) => (
<TableRow key={persona.id}>
<TableCell className="py-3.5">
<img
<PersonaAvatar
src={personaAvatarUrl(
persona.profile_picture,
persona.name,
persona.id,
)}
alt=""
className="h-10 w-10 rounded-full border border-grayScale-200 bg-grayScale-50 object-cover"
alt={persona.name}
size="sm"
/>
</TableCell>
<TableCell className="py-3.5">

View File

@ -9,7 +9,7 @@ import {
DialogHeader,
DialogTitle,
} from "../../../components/ui/dialog"
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
import { notifyApiError } from "../../../lib/apiErrors"
import {
draftToCreatePayload,
EMPTY_PERSONA_FORM_DRAFT,
@ -62,7 +62,7 @@ export function CreatePersonaDialog({
onCreated?.()
} catch (e: unknown) {
console.error(e)
toast.error(getPersonaApiErrorMessage(e, "Failed to create persona"))
notifyApiError(e, "Failed to create persona")
} finally {
setSaving(false)
}

View File

@ -10,7 +10,7 @@ import {
DialogTitle,
} from "../../../components/ui/dialog"
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
import { notifyApiError } from "../../../lib/apiErrors"
import type { LmsPersona } from "../../../types/persona.types"
import {
draftToUpdatePayload,
@ -54,7 +54,7 @@ export function EditPersonaDialog({
if (status === 404) {
toast.error("Persona not found")
} else {
toast.error(getPersonaApiErrorMessage(e, "Failed to load persona"))
notifyApiError(e, "Failed to load persona")
}
onOpenChange(false)
} finally {
@ -95,7 +95,7 @@ export function EditPersonaDialog({
onUpdated?.()
} catch (e: unknown) {
console.error(e)
toast.error(getPersonaApiErrorMessage(e, "Failed to update persona"))
notifyApiError(e, "Failed to update persona")
} finally {
setSaving(false)
}

View File

@ -6,6 +6,7 @@ import { syncRbacPermissions } from "../../../api/rbac.api"
import { Button } from "../../../components/ui/button"
import { Card, CardContent } from "../../../components/ui/card"
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
import { notifyApiError } from "../../../lib/apiErrors"
import { PERSONAS_FORBIDDEN_MESSAGE } from "../../../lib/personasErrors"
import {
getSessionTeamRole,
@ -28,10 +29,7 @@ export function PersonaAccessDenied({ apiForbidden = false }: PersonaAccessDenie
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
} catch (e: unknown) {
console.error(e)
const msg =
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
"Failed to sync RBAC permissions"
toast.error(msg)
notifyApiError(e, "Failed to sync RBAC permissions")
} finally {
setSyncing(false)
}

View File

@ -3,7 +3,7 @@ import { Trash2 } from "lucide-react"
import { toast } from "sonner"
import { deletePersona } from "../../../api/personas.api"
import { Button } from "../../../components/ui/button"
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
import { notifyApiError } from "../../../lib/apiErrors"
import {
Dialog,
DialogContent,
@ -44,7 +44,7 @@ export function PersonaDeleteDialog({
onDeleted?.()
} catch (e: unknown) {
console.error(e)
toast.error(getPersonaApiErrorMessage(e, "Failed to delete persona"))
notifyApiError(e, "Failed to delete persona")
} finally {
setDeleting(false)
}

Some files were not shown because too many files have changed in this diff Show More