diff --git a/src/api/http.ts b/src/api/http.ts
index fea7cea..f690b0a 100644
--- a/src/api/http.ts
+++ b/src/api/http.ts
@@ -1,4 +1,5 @@
import axios, { type AxiosInstance, type AxiosError, type InternalAxiosRequestConfig } from "axios";
+import { toast } from "sonner";
import { teamRefresh } from "./teamRefresh.api";
import { TeamAuthError } from "../types/auth.types";
import {
@@ -7,6 +8,7 @@ import {
getRefreshToken,
saveTeamSession,
} from "../lib/teamAuthStorage";
+import { markApiErrorNotified, readApiResponseMessage } from "../lib/apiErrors";
const http: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
@@ -90,19 +92,9 @@ const shouldAttachApiAuth = (url?: string): boolean => {
return requestOrigin === API_BASE_ORIGIN;
};
-function readErrorMessage(data: unknown): string {
- if (typeof data === "string") return data;
- if (data && typeof data === "object") {
- const record = data as Record;
- if (typeof record.error === "string") return record.error;
- if (typeof record.message === "string") return record.message;
- }
- return "";
-}
-
function isRefreshableAccessTokenError(error: AxiosError): boolean {
if (error.response?.status !== 401) return false;
- const message = readErrorMessage(error.response.data).toLowerCase();
+ const message = readApiResponseMessage(error.response.data).toLowerCase();
return (
message.includes("access token expired") ||
message.includes("invalid access token")
@@ -202,6 +194,16 @@ http.interceptors.response.use(
}
}
+ const skipErrorToast =
+ originalRequest.skipErrorToast || isAuthEndpointRequest(originalRequest.url);
+ if (!skipErrorToast && error.response) {
+ const message = readApiResponseMessage(error.response.data);
+ if (message) {
+ toast.error(message);
+ markApiErrorNotified(error);
+ }
+ }
+
return Promise.reject(error);
},
);
diff --git a/src/api/rbac.api.ts b/src/api/rbac.api.ts
index 2fc88ef..c0e1f55 100644
--- a/src/api/rbac.api.ts
+++ b/src/api/rbac.api.ts
@@ -10,11 +10,30 @@ import type {
GetPermissionsResponse,
BulkRoleDeactivateResponse,
BulkRoleReactivateResponse,
+ Role,
} from "../types/rbac.types"
export const getRoles = (params?: GetRolesParams) =>
http.get("/rbac/roles", { params })
+/** Fetch every RBAC role across paginated list responses. */
+export async function fetchAllRoles(): Promise {
+ const pageSize = 50
+ const firstRes = await getRoles({ page: 1, page_size: pageSize })
+ const firstBatch = firstRes.data?.data?.roles ?? []
+ const total = firstRes.data?.data?.total ?? firstBatch.length
+ const totalPages = Math.max(1, Math.ceil(total / pageSize))
+
+ if (totalPages === 1) return firstBatch
+
+ const remaining = await Promise.all(
+ Array.from({ length: totalPages - 1 }, (_, idx) =>
+ getRoles({ page: idx + 2, page_size: pageSize }),
+ ),
+ )
+ return [...firstBatch, ...remaining.flatMap((res) => res.data?.data?.roles ?? [])]
+}
+
export const getRoleDetail = (roleId: number) =>
http.get(`/rbac/roles/${roleId}`)
diff --git a/src/api/team.api.ts b/src/api/team.api.ts
index 4d7afc3..bda1ebe 100644
--- a/src/api/team.api.ts
+++ b/src/api/team.api.ts
@@ -155,7 +155,9 @@ export const changeTeamMemberPassword = (id: number, data: ChangeTeamMemberPassw
/** POST /team/members/invite — send invitation email (permission: team.members.invite). */
export const inviteTeamMember = (data: InviteTeamMemberRequest) =>
- http.post("/team/members/invite", data)
+ http.post("/team/members/invite", data, {
+ skipErrorToast: true,
+ })
/** GET /team/invitations/verify?token= — public (accept-invite page). */
export const verifyTeamInvitation = (token: string) =>
diff --git a/src/assets/personas/amanuel.png b/src/assets/personas/amanuel.png
new file mode 100644
index 0000000..91b42d1
Binary files /dev/null and b/src/assets/personas/amanuel.png differ
diff --git a/src/assets/personas/aseffa.png b/src/assets/personas/aseffa.png
new file mode 100644
index 0000000..afb75bf
Binary files /dev/null and b/src/assets/personas/aseffa.png differ
diff --git a/src/assets/personas/bethel.png b/src/assets/personas/bethel.png
new file mode 100644
index 0000000..1461c76
Binary files /dev/null and b/src/assets/personas/bethel.png differ
diff --git a/src/assets/personas/dawit.png b/src/assets/personas/dawit.png
new file mode 100644
index 0000000..15b38c8
Binary files /dev/null and b/src/assets/personas/dawit.png differ
diff --git a/src/assets/personas/hana.png b/src/assets/personas/hana.png
new file mode 100644
index 0000000..c238cb6
Binary files /dev/null and b/src/assets/personas/hana.png differ
diff --git a/src/assets/personas/liya.png b/src/assets/personas/liya.png
new file mode 100644
index 0000000..77a0aae
Binary files /dev/null and b/src/assets/personas/liya.png differ
diff --git a/src/assets/personas/mahlet.png b/src/assets/personas/mahlet.png
new file mode 100644
index 0000000..c8e20c0
Binary files /dev/null and b/src/assets/personas/mahlet.png differ
diff --git a/src/assets/personas/nahom.png b/src/assets/personas/nahom.png
new file mode 100644
index 0000000..92ee9d5
Binary files /dev/null and b/src/assets/personas/nahom.png differ
diff --git a/src/components/content-management/DynamicSchemaSlotField.tsx b/src/components/content-management/DynamicSchemaSlotField.tsx
index 319f6d7..3825d95 100644
--- a/src/components/content-management/DynamicSchemaSlotField.tsx
+++ b/src/components/content-management/DynamicSchemaSlotField.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../../lib/apiErrors"
import {
useCallback,
useEffect,
@@ -199,7 +200,7 @@ function DynamicImageSlot({
toast.success("Image uploaded")
} catch (e) {
console.error(e)
- toast.error("Failed to upload image")
+ notifyApiError(e, "Failed to upload image")
} finally {
setUploading(false)
}
@@ -220,7 +221,7 @@ function DynamicImageSlot({
toast.success("Image URL imported to storage")
} catch (e) {
console.error(e)
- toast.error("Could not import image from URL")
+ notifyApiError(e, "Could not import image from URL")
} finally {
setUploading(false)
}
@@ -454,7 +455,7 @@ function DynamicAudioSlot({
toast.success("Audio uploaded")
} catch (e) {
console.error(e)
- toast.error("Failed to upload audio")
+ notifyApiError(e, "Failed to upload audio")
} finally {
setUploading(false)
}
@@ -477,7 +478,7 @@ function DynamicAudioSlot({
toast.success("Audio URL imported to storage")
} catch (e) {
console.error(e)
- toast.error("Could not import audio from URL")
+ notifyApiError(e, "Could not import audio from URL")
} finally {
setUploading(false)
}
@@ -783,7 +784,7 @@ function DynamicPdfSlot({
toast.success("PDF uploaded")
} catch (e) {
console.error(e)
- toast.error("Failed to upload PDF")
+ notifyApiError(e, "Failed to upload PDF")
} finally {
setUploading(false)
}
diff --git a/src/components/content-management/PracticeQuestionEditorFields.tsx b/src/components/content-management/PracticeQuestionEditorFields.tsx
index af67909..475960c 100644
--- a/src/components/content-management/PracticeQuestionEditorFields.tsx
+++ b/src/components/content-management/PracticeQuestionEditorFields.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../../lib/apiErrors"
import {
useCallback,
useEffect,
@@ -330,7 +331,7 @@ export function PracticeQuestionEditorFields({
toast.success("Audio uploaded successfully")
} catch (error) {
console.error("Failed to upload audio:", error)
- toast.error("Failed to upload audio file")
+ notifyApiError(error, "Failed to upload audio file")
} finally {
if (field === "voice_prompt") setUploadingVoice(false)
else setUploadingSample(false)
@@ -387,7 +388,7 @@ export function PracticeQuestionEditorFields({
else setSamplePreviewUrl(url)
} catch (error) {
console.error("Failed to resolve audio:", error)
- toast.error("Could not import/resolve audio URL")
+ notifyApiError(error, "Could not import/resolve audio URL")
} finally {
if (field === "voice_prompt") setUploadingVoice(false)
else setUploadingSample(false)
@@ -419,7 +420,7 @@ export function PracticeQuestionEditorFields({
toast.success("Image uploaded successfully")
} catch (error) {
console.error("Failed to upload image:", error)
- toast.error("Failed to upload image")
+ notifyApiError(error, "Failed to upload image")
} finally {
setUploadingImage(false)
}
@@ -435,7 +436,7 @@ export function PracticeQuestionEditorFields({
setImagePreviewUrl(resolved)
} catch (error) {
console.error("Failed to resolve image preview URL:", error)
- toast.error("Could not resolve image preview URL")
+ notifyApiError(error, "Could not resolve image preview URL")
}
}
@@ -704,7 +705,7 @@ export function PracticeQuestionEditorFields({
})
} catch (e) {
console.error(e)
- toast.error("Failed to load definition details")
+ notifyApiError(e, "Failed to load definition details")
} finally {
setDefinitionDetailLoading(false)
}
diff --git a/src/components/export/ExportCsvButton.tsx b/src/components/export/ExportCsvButton.tsx
index 746f67e..28da5ff 100644
--- a/src/components/export/ExportCsvButton.tsx
+++ b/src/components/export/ExportCsvButton.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../../lib/apiErrors"
import { Download } from "lucide-react"
import { useState } from "react"
import { toast } from "sonner"
@@ -43,7 +44,7 @@ export function ExportCsvButton({
const filename = await downloadCsvExport(exportPath, params, { resourceName })
toast.success(`Downloaded ${filename}`)
} catch (e) {
- toast.error(e instanceof Error ? e.message : "Export failed")
+ notifyApiError(e, "Export failed")
} finally {
setExporting(false)
}
diff --git a/src/components/navigation/PageBackLink.tsx b/src/components/navigation/PageBackLink.tsx
new file mode 100644
index 0000000..321c3cb
--- /dev/null
+++ b/src/components/navigation/PageBackLink.tsx
@@ -0,0 +1,39 @@
+import { ArrowLeft } from "lucide-react";
+import { useNavigate } from "react-router-dom";
+import { navigateBack } from "../../lib/navigateBack";
+import { cn } from "../../lib/utils";
+
+type PageBackLinkProps = {
+ fallbackTo: string;
+ label?: string;
+ className?: string;
+ iconClassName?: string;
+};
+
+export function PageBackLink({
+ fallbackTo,
+ label = "Back",
+ className,
+ iconClassName,
+}: PageBackLinkProps) {
+ const navigate = useNavigate();
+
+ return (
+
+ );
+}
diff --git a/src/components/notifications/EmailComposeFields.tsx b/src/components/notifications/EmailComposeFields.tsx
index 2bc5641..84559b6 100644
--- a/src/components/notifications/EmailComposeFields.tsx
+++ b/src/components/notifications/EmailComposeFields.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import { Eye, ExternalLink, RefreshCw } from "lucide-react"
import { toast } from "sonner"
+import { notifyApiError } from "../../lib/apiErrors"
import {
parseEmailTemplatePreviewResponse,
previewEmailTemplate,
@@ -123,10 +124,7 @@ export function EmailComposeFields({
if (!result) throw new Error("Empty preview response")
setPreview(result)
} catch (err: unknown) {
- const msg =
- (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
- "Failed to preview email template"
- toast.error(msg)
+ notifyApiError(err, "Failed to preview email template")
} finally {
setPreviewLoading(false)
}
diff --git a/src/components/notifications/NotificationDeleteDialog.tsx b/src/components/notifications/NotificationDeleteDialog.tsx
index 034cade..902bcaa 100644
--- a/src/components/notifications/NotificationDeleteDialog.tsx
+++ b/src/components/notifications/NotificationDeleteDialog.tsx
@@ -1,6 +1,7 @@
import { useState } from "react"
import { Trash2 } from "lucide-react"
import { toast } from "sonner"
+import { notifyApiError } from "../../lib/apiErrors"
import { deleteNotification } from "../../api/notifications.api"
import { Button } from "../ui/button"
import {
@@ -43,12 +44,7 @@ export function NotificationDeleteDialog({
onDeleted?.(notification.id)
} catch (e: unknown) {
console.error(e)
- const msg =
- (e as { response?: { data?: { message?: string; error?: string } } })?.response
- ?.data?.error ??
- (e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
- "Failed to delete notification"
- toast.error(msg)
+ notifyApiError(e, "Failed to delete notification")
} finally {
setDeleting(false)
}
diff --git a/src/components/personas/PersonaAvatar.tsx b/src/components/personas/PersonaAvatar.tsx
new file mode 100644
index 0000000..5ff8155
--- /dev/null
+++ b/src/components/personas/PersonaAvatar.tsx
@@ -0,0 +1,43 @@
+import { cn } from "../../lib/utils"
+
+const SIZE_CLASSES = {
+ sm: "size-10",
+ md: "size-12",
+ lg: "size-16",
+ xl: "size-24",
+} as const
+
+type PersonaAvatarProps = {
+ src: string
+ alt?: string
+ size?: keyof typeof SIZE_CLASSES
+ selected?: boolean
+ className?: string
+}
+
+export function PersonaAvatar({
+ src,
+ alt = "",
+ size = "md",
+ selected = false,
+ className,
+}: PersonaAvatarProps) {
+ return (
+
+

+
+ )
+}
diff --git a/src/components/profile/ProfileAvatarUpload.tsx b/src/components/profile/ProfileAvatarUpload.tsx
index f35691e..cd45d3a 100644
--- a/src/components/profile/ProfileAvatarUpload.tsx
+++ b/src/components/profile/ProfileAvatarUpload.tsx
@@ -1,6 +1,7 @@
import { useCallback, useRef, useState, type ChangeEvent } from "react"
import { Camera } from "lucide-react"
import { toast } from "sonner"
+import { notifyApiError } from "../../lib/apiErrors"
import { uploadImageFile } from "../../api/files.api"
import { updateTeamMe } from "../../api/team.api"
import { SpinnerIcon } from "../ui/spinner-icon"
@@ -53,10 +54,7 @@ export function ProfileAvatarUpload({
toast.success(updateRes.data.message || "Profile picture updated")
} catch (err: unknown) {
console.error(err)
- const uploadMsg =
- (err as { response?: { data?: { message?: string } } })?.response?.data
- ?.message
- toast.error(uploadMsg ?? "Failed to update profile picture")
+ notifyApiError(err, "Failed to update profile picture")
} finally {
setUploading(false)
}
diff --git a/src/components/topbar/NotificationDropdown.tsx b/src/components/topbar/NotificationDropdown.tsx
index 5a419cf..4e5ab31 100644
--- a/src/components/topbar/NotificationDropdown.tsx
+++ b/src/components/topbar/NotificationDropdown.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../../lib/apiErrors"
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
import { useNavigate } from "react-router-dom"
import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react"
@@ -207,7 +208,7 @@ export function NotificationDropdown() {
next.delete(pending.notification.id)
return next
})
- toast.error("Failed to delete notification")
+ notifyApiError(err, "Failed to delete notification")
}
}, [commitDeleteNotification, selectedNotificationId])
@@ -282,7 +283,7 @@ export function NotificationDropdown() {
}
} else {
setDetailError(true)
- toast.error("Failed to load notification details")
+ notifyApiError(err, "Failed to load notification details")
}
} finally {
setDetailLoading(false)
diff --git a/src/components/ui/avatar.tsx b/src/components/ui/avatar.tsx
index 45941df..2b2de9c 100644
--- a/src/components/ui/avatar.tsx
+++ b/src/components/ui/avatar.tsx
@@ -19,7 +19,11 @@ export const AvatarImage = React.forwardRef<
React.ElementRef,
React.ComponentPropsWithoutRef
>(({ className, ...props }, ref) => (
-
+
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
diff --git a/src/hooks/useActivePersonas.ts b/src/hooks/useActivePersonas.ts
index b7db317..688ca78 100644
--- a/src/hooks/useActivePersonas.ts
+++ b/src/hooks/useActivePersonas.ts
@@ -1,13 +1,15 @@
import { useCallback, useEffect, useState } from "react"
-import { listActivePersonasForPicker } from "../api/personas.api"
+import { getPersonaById, listActivePersonasForPicker } from "../api/personas.api"
import { mapPersonaToCard, type PersonaCardModel } from "../lib/personaDisplay"
type UseActivePersonasOptions = {
limit?: number
+ /** Include this persona in the picker even when inactive or missing from the active list. */
+ ensurePersonaId?: number | null
}
export function useActivePersonas(options: UseActivePersonasOptions = {}) {
- const { limit = 200 } = options
+ const { limit = 200, ensurePersonaId = null } = options
const [personas, setPersonas] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
@@ -16,7 +18,23 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) {
setLoading(true)
setError(null)
try {
- const list = await listActivePersonasForPicker(limit)
+ let list = await listActivePersonasForPicker(limit)
+ const ensureId =
+ ensurePersonaId != null &&
+ Number.isFinite(ensurePersonaId) &&
+ ensurePersonaId > 0
+ ? ensurePersonaId
+ : null
+ if (ensureId != null && !list.some((persona) => persona.id === ensureId)) {
+ try {
+ const res = await getPersonaById(ensureId)
+ if (res.data) {
+ list = [res.data, ...list]
+ }
+ } catch {
+ // Keep active list only if the saved persona cannot be loaded.
+ }
+ }
setPersonas(list.map(mapPersonaToCard))
} catch (e: unknown) {
const msg =
@@ -27,7 +45,7 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) {
} finally {
setLoading(false)
}
- }, [limit])
+ }, [limit, ensurePersonaId])
useEffect(() => {
void load()
diff --git a/src/lib/apiErrors.ts b/src/lib/apiErrors.ts
new file mode 100644
index 0000000..9193050
--- /dev/null
+++ b/src/lib/apiErrors.ts
@@ -0,0 +1,45 @@
+import axios from "axios"
+import { toast } from "sonner"
+
+const API_ERROR_NOTIFIED = "__apiErrorNotified"
+
+export function readApiResponseMessage(data: unknown): string {
+ if (typeof data === "string") return data.trim()
+ if (data && typeof data === "object") {
+ const record = data as Record
+ if (typeof record.message === "string" && record.message.trim()) {
+ return record.message.trim()
+ }
+ if (typeof record.error === "string" && record.error.trim()) {
+ return record.error.trim()
+ }
+ }
+ return ""
+}
+
+export function getApiErrorMessage(error: unknown, fallback: string): string {
+ if (axios.isAxiosError(error)) {
+ const message = readApiResponseMessage(error.response?.data)
+ if (message) return message
+ }
+ return fallback
+}
+
+export function markApiErrorNotified(error: unknown): void {
+ if (error && typeof error === "object") {
+ ;(error as Record)[API_ERROR_NOTIFIED] = true
+ }
+}
+
+export function wasApiErrorNotified(error: unknown): boolean {
+ return Boolean(
+ error && typeof error === "object" && (error as Record)[API_ERROR_NOTIFIED],
+ )
+}
+
+/** Show API `message`/`error` from failed requests, or a fallback when absent. */
+export function notifyApiError(error: unknown, fallback: string): void {
+ if (wasApiErrorNotified(error)) return
+ toast.error(getApiErrorMessage(error, fallback))
+ markApiErrorNotified(error)
+}
diff --git a/src/lib/navigateBack.ts b/src/lib/navigateBack.ts
new file mode 100644
index 0000000..b21c0dd
--- /dev/null
+++ b/src/lib/navigateBack.ts
@@ -0,0 +1,14 @@
+import type { NavigateFunction } from "react-router-dom";
+
+export function canNavigateBack(): boolean {
+ const idx = (window.history.state as { idx?: number } | null)?.idx;
+ return typeof idx === "number" && idx > 0;
+}
+
+export function navigateBack(navigate: NavigateFunction, fallbackTo: string): void {
+ if (canNavigateBack()) {
+ navigate(-1);
+ return;
+ }
+ navigate(fallbackTo);
+}
diff --git a/src/lib/personaDisplay.ts b/src/lib/personaDisplay.ts
index 449fb0c..923f365 100644
--- a/src/lib/personaDisplay.ts
+++ b/src/lib/personaDisplay.ts
@@ -2,6 +2,14 @@ import type {
GetPersonasResponse,
PersonaListItem,
} from "../types/persona.types"
+import amanuelAvatar from "../assets/personas/amanuel.png"
+import aseffaAvatar from "../assets/personas/aseffa.png"
+import bethelAvatar from "../assets/personas/bethel.png"
+import dawitAvatar from "../assets/personas/dawit.png"
+import hanaAvatar from "../assets/personas/hana.png"
+import liyaAvatar from "../assets/personas/liya.png"
+import mahletAvatar from "../assets/personas/mahlet.png"
+import nahomAvatar from "../assets/personas/nahom.png"
export type PersonaCardModel = {
id: string
@@ -10,12 +18,57 @@ export type PersonaCardModel = {
avatar: string
}
-/** Soft, professional palette aligned with the admin brand (slate, indigo, violet). */
-const PERSONA_FALLBACK_BACKGROUNDS = "f1f5f9,e0e7ff,ede9fe,fdf4ff,ecfeff"
+/** Realistic default portraits bundled with the admin app (see src/assets/personas). */
+const DEFAULT_PERSONA_AVATARS = [
+ dawitAvatar,
+ mahletAvatar,
+ amanuelAvatar,
+ bethelAvatar,
+ liyaAvatar,
+ aseffaAvatar,
+ hanaAvatar,
+ nahomAvatar,
+] as const
+
+const PERSONA_NAME_AVATARS: Record = {
+ dawit: dawitAvatar,
+ mahlet: mahletAvatar,
+ amanuel: amanuelAvatar,
+ bethel: bethelAvatar,
+ liya: liyaAvatar,
+ aseffa: aseffaAvatar,
+ hana: hanaAvatar,
+ nahom: nahomAvatar,
+}
+
+function hashString(value: string): number {
+ let hash = 0
+ for (let i = 0; i < value.length; i++) {
+ hash = (hash * 31 + value.charCodeAt(i)) >>> 0
+ }
+ return hash
+}
+
+function defaultPersonaAvatarUrl(
+ name: string,
+ personaId?: number | string,
+): string {
+ const normalizedName = name.trim().toLowerCase()
+ const byName = PERSONA_NAME_AVATARS[normalizedName]
+ if (byName) return byName
+
+ const numericId = personaId != null ? Number(personaId) : NaN
+ const index =
+ Number.isFinite(numericId) && numericId > 0
+ ? (numericId - 1) % DEFAULT_PERSONA_AVATARS.length
+ : hashString(normalizedName || "persona") % DEFAULT_PERSONA_AVATARS.length
+
+ return DEFAULT_PERSONA_AVATARS[index]
+}
/**
- * Default avatar when `profile_picture` is null: professional illustrated portrait
- * (DiceBear personas), not casual cartoon avataaars.
+ * Default avatar when `profile_picture` is null: realistic bundled portrait,
+ * matched by persona name when possible.
*/
export function personaAvatarUrl(
profilePicture: string | null | undefined,
@@ -24,12 +77,7 @@ export function personaAvatarUrl(
): string {
const url = profilePicture?.trim()
if (url) return url
- const params = new URLSearchParams({
- seed: personaId != null ? `yimaru-persona-${personaId}` : `yimaru-persona-${name}`,
- backgroundColor: PERSONA_FALLBACK_BACKGROUNDS,
- radius: "50",
- })
- return `https://api.dicebear.com/7.x/personas/svg?${params.toString()}`
+ return defaultPersonaAvatarUrl(name, personaId)
}
export function mapPersonaToCard(persona: PersonaListItem): PersonaCardModel {
diff --git a/src/lib/practiceEditDirty.ts b/src/lib/practiceEditDirty.ts
new file mode 100644
index 0000000..01bd83e
--- /dev/null
+++ b/src/lib/practiceEditDirty.ts
@@ -0,0 +1,66 @@
+import type {
+ PracticeFormState,
+ PreservedQuestionSetFields,
+} from "./practiceFullMapper"
+import { dedupeParents } from "./practiceParents"
+
+export type PracticeEditDirtyInput = {
+ formData: PracticeFormState
+ selectedPersona: string | null
+ preservedQuestionSet: PreservedQuestionSetFields
+}
+
+function normalizeQuestionRow(question: PracticeFormState["questions"][number]) {
+ return {
+ serverQuestionId: question.serverQuestionId ?? null,
+ displayOrder: question.displayOrder,
+ associatedQuestionId: question.associatedQuestionId ?? null,
+ associatedAnchorRowId: question.associatedAnchorRowId ?? null,
+ prerequisiteQuestionIds: question.prerequisiteQuestionIds ?? [],
+ stimulusBlockKey: question.stimulusBlockKey ?? null,
+ questionTypeDefinitionId: question.questionTypeDefinitionId ?? null,
+ text: String(question.text ?? "").trim(),
+ difficultyLevel: question.difficultyLevel,
+ points: Number(question.points),
+ dynamicFieldValues: question.dynamicFieldValues ?? {},
+ mcqOptions: (question.mcqOptions ?? []).map((option) => ({
+ text: String(option.text ?? "").trim(),
+ isCorrect: Boolean(option.isCorrect),
+ })),
+ trueFalseCorrect: question.trueFalseCorrect !== false,
+ shortAnswers: (question.shortAnswers ?? []).map((answer) => String(answer).trim()),
+ }
+}
+
+export function buildPracticeEditSnapshot(input: PracticeEditDirtyInput): string {
+ const { formData, selectedPersona, preservedQuestionSet } = input
+
+ return JSON.stringify({
+ title: formData.title.trim(),
+ description: formData.description.trim(),
+ storyImageUrl: formData.storyImageUrl.trim(),
+ shuffleQuestions: Boolean(formData.shuffleQuestions),
+ tips: formData.tips.trim(),
+ authoringProfile: formData.authoringProfile,
+ stimulusBlocks: formData.stimulusBlocks,
+ parents: dedupeParents(formData.parents),
+ questions: [...formData.questions]
+ .map(normalizeQuestionRow)
+ .sort((a, b) => a.displayOrder - b.displayOrder),
+ selectedPersona: selectedPersona?.trim() || null,
+ preservedQuestionSet: {
+ timeLimitMinutes: preservedQuestionSet.timeLimitMinutes,
+ passingScore: preservedQuestionSet.passingScore,
+ introVideoUrl: preservedQuestionSet.introVideoUrl.trim(),
+ status: preservedQuestionSet.status,
+ },
+ })
+}
+
+export function hasPracticeEditChanges(
+ initialSnapshot: string | null,
+ current: PracticeEditDirtyInput,
+): boolean {
+ if (!initialSnapshot) return false
+ return buildPracticeEditSnapshot(current) !== initialSnapshot
+}
diff --git a/src/lib/practiceFullMapper.ts b/src/lib/practiceFullMapper.ts
index d237d12..b3a9e5f 100644
--- a/src/lib/practiceFullMapper.ts
+++ b/src/lib/practiceFullMapper.ts
@@ -308,6 +308,7 @@ function normalizePracticeFullQuestionSet(raw: unknown): PracticeFullQuestionSet
owner_type: pickStr(record, "owner_type", "OwnerType", "ownerType") || undefined,
owner_id: pickNum(record, "owner_id", "OwnerId", "ownerId") ?? undefined,
persona: pickStr(record, "persona", "Persona") || null,
+ persona_id: pickNum(record, "persona_id", "PersonaId", "personaId"),
shuffle_questions: Boolean(
record.shuffle_questions ?? record.ShuffleQuestions ?? false,
),
@@ -565,6 +566,25 @@ function mapFullQuestionToFormRow(
}
}
+function parsePersonaIdValue(value: unknown): number | null {
+ if (value == null) return null
+ const n = Number(value)
+ return Number.isFinite(n) && n > 0 ? n : null
+}
+
+export function resolvePracticePersonaId(
+ practice: PracticeFullPractice,
+ questionSet: PracticeFullQuestionSet,
+): number | null {
+ const fromPractice = parsePersonaIdValue(practice.persona_id)
+ if (fromPractice != null) return fromPractice
+
+ const fromQuestionSet = parsePersonaIdValue(questionSet.persona_id)
+ if (fromQuestionSet != null) return fromQuestionSet
+
+ return parsePersonaIdValue(questionSet.persona)
+}
+
export function mapPracticeFullToFormState(
data: PracticeFullData,
typeDefinitions: QuestionTypeDefinition[],
@@ -618,10 +638,7 @@ export function mapPracticeFullToFormState(
parents: parentsFromPractice(practice),
questions: formQuestions,
},
- personaId:
- practice.persona_id != null && Number.isFinite(practice.persona_id)
- ? practice.persona_id
- : null,
+ personaId: resolvePracticePersonaId(practice, question_set),
preservedQuestionSet: {
timeLimitMinutes: question_set.time_limit_minutes ?? null,
passingScore: question_set.passing_score ?? null,
diff --git a/src/lib/practiceParentTitles.ts b/src/lib/practiceParentTitles.ts
index 45ab17c..e7fa253 100644
--- a/src/lib/practiceParentTitles.ts
+++ b/src/lib/practiceParentTitles.ts
@@ -30,6 +30,8 @@ export function practiceParentKey(parent: PracticeParent): string {
}
function kindLabel(kind: PracticeParentKind): string {
+ if (kind === "CATALOG_COURSE") return "Catalog course"
+ if (kind === "UNIT") return "Unit"
if (kind === "COURSE") return "Course"
if (kind === "MODULE") return "Module"
return "Lesson"
@@ -98,12 +100,32 @@ async function resolveExamPrepCourseTitles(
const res = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 })
for (const course of res.data?.data?.catalog_courses ?? []) {
if (ids.has(course.id)) {
- map.set(`COURSE:${course.id}`, course.name?.trim() || `Course #${course.id}`)
+ const title = course.name?.trim() || `Course #${course.id}`
+ map.set(`CATALOG_COURSE:${course.id}`, title)
+ map.set(`COURSE:${course.id}`, title)
ids.delete(course.id)
}
}
}
+async function resolveExamPrepUnitTitles(
+ ids: Set,
+ map: PracticeParentTitleMap,
+): Promise {
+ if (ids.size === 0) return
+ const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 })
+ for (const course of coursesRes.data?.data?.catalog_courses ?? []) {
+ if (ids.size === 0) break
+ const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 })
+ for (const unit of unitsRes.data?.data?.units ?? []) {
+ if (ids.has(unit.id)) {
+ map.set(`UNIT:${unit.id}`, unit.name?.trim() || `Unit #${unit.id}`)
+ ids.delete(unit.id)
+ }
+ }
+ }
+}
+
async function resolveLearnEnglishModuleTitles(
ids: Set,
map: PracticeParentTitleMap,
@@ -230,18 +252,23 @@ export async function resolvePracticeParentTitles(
const normalized = dedupeParents(parents)
const unresolvedCourses = new Set()
+ const unresolvedCatalogCourses = new Set()
+ const unresolvedUnits = new Set()
const unresolvedModules = new Set()
const unresolvedLessons = new Set()
for (const parent of normalized) {
if (map.has(practiceParentKey(parent))) continue
if (parent.parent_kind === "COURSE") unresolvedCourses.add(parent.parent_id)
+ if (parent.parent_kind === "CATALOG_COURSE") unresolvedCatalogCourses.add(parent.parent_id)
+ if (parent.parent_kind === "UNIT") unresolvedUnits.add(parent.parent_id)
if (parent.parent_kind === "MODULE") unresolvedModules.add(parent.parent_id)
if (parent.parent_kind === "LESSON") unresolvedLessons.add(parent.parent_id)
}
await resolveLearnEnglishCourseTitles(unresolvedCourses, map)
- await resolveExamPrepCourseTitles(unresolvedCourses, map)
+ await resolveExamPrepCourseTitles(unresolvedCatalogCourses, map)
+ await resolveExamPrepUnitTitles(unresolvedUnits, map)
await resolveLearnEnglishModuleTitles(unresolvedModules, map)
await resolveExamPrepModuleTitles(unresolvedModules, map)
await resolveLearnEnglishLessonTitles(unresolvedLessons, map)
diff --git a/src/lib/teamRoles.ts b/src/lib/teamRoles.ts
index 7971b72..5cf9d80 100644
--- a/src/lib/teamRoles.ts
+++ b/src/lib/teamRoles.ts
@@ -41,3 +41,26 @@ export function formatTeamRoleLabel(teamRole: string): string {
if (found) return found.label
return teamRole.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
}
+
+/** Role name sent to POST /team/members/invite (used in invitation emails). */
+export function teamRoleNameForInvite(teamRole: string, explicitName?: string): string {
+ const named = explicitName?.trim()
+ if (named) return named
+
+ const fromOptions = TEAM_ROLE_OPTIONS.find(
+ (o) => o.value === teamRole || o.value === teamRole.toUpperCase(),
+ )
+ if (fromOptions) return fromOptions.label
+
+ return teamRole.trim()
+}
+
+export type TeamRoleOption = { value: string; label: string }
+
+export function rbacRolesToTeamRoleOptions(roles: Role[]): TeamRoleOption[] {
+ const names = Array.from(
+ new Set(roles.map((role) => role.name.trim()).filter(Boolean)),
+ ).sort((a, b) => a.localeCompare(b))
+
+ return names.map((name) => ({ value: name, label: name }))
+}
diff --git a/src/pages/ProfilePage.tsx b/src/pages/ProfilePage.tsx
index 9fb9059..d955d1c 100644
--- a/src/pages/ProfilePage.tsx
+++ b/src/pages/ProfilePage.tsx
@@ -9,6 +9,7 @@ import {
User,
} from "lucide-react"
import { toast } from "sonner"
+import { notifyApiError } from "../lib/apiErrors"
import { getTeamMe, updateTeamMe } from "../api/team.api"
import { Badge } from "../components/ui/badge"
import { Button } from "../components/ui/button"
@@ -193,10 +194,7 @@ export function ProfilePage() {
toast.success(res.data.message || "Profile updated successfully")
} catch (err) {
console.error("Failed to update profile", err)
- const message =
- (err as { response?: { data?: { message?: string } } })?.response?.data
- ?.message ?? "Failed to update profile"
- toast.error(message)
+ notifyApiError(err, "Failed to update profile")
} finally {
setSaving(false)
}
diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx
index f4eb152..b6b0cc5 100644
--- a/src/pages/SettingsPage.tsx
+++ b/src/pages/SettingsPage.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../lib/apiErrors"
import React, { useEffect, useState } from "react";
import {
Eye,
@@ -81,10 +82,7 @@ function SecurityTab({ memberId }: { memberId: number }) {
logoutToLogin({ passwordChanged: true });
return;
} catch (e: unknown) {
- const msg =
- (e as { response?: { data?: { message?: string } } })?.response?.data
- ?.message ?? "Failed to update password.";
- toast.error(msg);
+ notifyApiError(e, "Failed to update password.");
} finally {
setSaving(false);
}
diff --git a/src/pages/auth/AcceptInvitePage.tsx b/src/pages/auth/AcceptInvitePage.tsx
index 87be79d..1423ea4 100644
--- a/src/pages/auth/AcceptInvitePage.tsx
+++ b/src/pages/auth/AcceptInvitePage.tsx
@@ -12,6 +12,7 @@ import {
User,
} from "lucide-react"
import { toast } from "sonner"
+import { notifyApiError } from "../../lib/apiErrors"
import {
acceptTeamInvitation,
parseVerifyInvitation,
@@ -129,10 +130,7 @@ export function AcceptInvitePage() {
toast.success(res.data?.message ?? "Account setup complete. You can sign in now.")
navigate("/login", { replace: true })
} catch (e: unknown) {
- const msg =
- (e as { response?: { data?: { message?: string } } })?.response?.data
- ?.message ?? "Failed to complete setup"
- toast.error(msg)
+ notifyApiError(e, "Failed to complete setup")
} finally {
setSubmitting(false)
}
diff --git a/src/pages/content-management/AddNewLessonPage.tsx b/src/pages/content-management/AddNewLessonPage.tsx
index e3d29bb..0e8264e 100644
--- a/src/pages/content-management/AddNewLessonPage.tsx
+++ b/src/pages/content-management/AddNewLessonPage.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../../lib/apiErrors"
import { useMemo, useState, type ChangeEvent } from "react"
import { ArrowLeft, ArrowRight, Check, GripVertical, Plus, Rocket, Trash2, Upload } from "lucide-react"
import { Link, useLocation, useNavigate, useParams } from "react-router-dom"
@@ -161,7 +162,7 @@ export function AddNewLessonPage() {
toast.success("Intro video uploaded")
} catch (error) {
console.error("Failed to upload lesson intro video:", error)
- toast.error("Failed to upload intro video")
+ notifyApiError(error, "Failed to upload intro video")
} finally {
setUploadingIntroVideo(false)
}
@@ -193,7 +194,7 @@ export function AddNewLessonPage() {
toast.success("Intro video URL imported")
} catch (error) {
console.error("Failed to import intro video URL:", error)
- toast.error("Failed to import intro video URL")
+ notifyApiError(error, "Failed to import intro video URL")
} finally {
setUploadingIntroVideo(false)
}
diff --git a/src/pages/content-management/AddNewPracticePage.tsx b/src/pages/content-management/AddNewPracticePage.tsx
index f20cb8b..f824b3c 100644
--- a/src/pages/content-management/AddNewPracticePage.tsx
+++ b/src/pages/content-management/AddNewPracticePage.tsx
@@ -1,3 +1,4 @@
+import { notifyApiError } from "../../lib/apiErrors"
import { useMemo, useRef, useState, type ChangeEvent } from "react";
import { Link, useLocation, useParams, useNavigate } from "react-router-dom";
import {
@@ -228,7 +229,7 @@ export function AddNewPracticePage() {
});
} catch (error) {
console.error("Failed to upload intro video:", error);
- toast.error("Failed to upload intro video");
+ notifyApiError(error, "Failed to upload intro video");
} finally {
setUploadingIntroVideo(false);
}
@@ -259,7 +260,7 @@ export function AddNewPracticePage() {
});
} catch (error) {
console.error("Failed to import intro video URL:", error);
- toast.error("Failed to import intro video URL");
+ notifyApiError(error, "Failed to import intro video URL");
} finally {
setImportingIntroVideoUrl(false);
}
diff --git a/src/pages/content-management/AddPracticeFlow.tsx b/src/pages/content-management/AddPracticeFlow.tsx
index d415b72..9a20fd4 100644
--- a/src/pages/content-management/AddPracticeFlow.tsx
+++ b/src/pages/content-management/AddPracticeFlow.tsx
@@ -1,11 +1,8 @@
+import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"
import { useEffect, useMemo, useState } from "react";
-import {
- Link,
- useNavigate,
- useParams,
- useSearchParams,
-} from "react-router-dom";
-import { ArrowLeft } from "lucide-react";
+import { useNavigate, useParams, useSearchParams } from "react-router-dom";
+import { PageBackLink } from "../../components/navigation/PageBackLink";
+import { navigateBack } from "../../lib/navigateBack";
import { toast } from "sonner";
import { Button } from "../../components/ui/button";
import { Stepper } from "../../components/ui/stepper";
@@ -15,7 +12,6 @@ import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.
import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api";
import { emptyDynamicFieldValuesForDefinition } from "../../lib/learnEnglishDefinitionQuestion";
import {
- learnEnglishPracticeApiErrorMessage,
validateLearnEnglishQuestionsWithDefinitions,
} from "../../lib/learnEnglishPracticePublish";
import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator";
@@ -213,6 +209,8 @@ export function AddPracticeFlow() {
isFromQuestionType,
]);
+ const goBack = () => navigateBack(navigate, backPath);
+
const [currentStep, setCurrentStep] = useState(1);
const [isPublished, setIsPublished] = useState(false);
const [submitting, setSubmitting] = useState(false);
@@ -279,7 +277,7 @@ export function AddPracticeFlow() {
if (!cancelled) setTypeDefinitions(list);
} catch (e) {
if (!cancelled) {
- setDefinitionsError(learnEnglishPracticeApiErrorMessage(e));
+ setDefinitionsError(getApiErrorMessage(e, "Failed to load question type definitions"));
setTypeDefinitions([]);
}
} finally {
@@ -506,9 +504,7 @@ export function AddPracticeFlow() {
toast.success("Practice created successfully");
setIsPublished(true);
} catch (e) {
- toast.error("Could not save practice", {
- description: learnEnglishPracticeApiErrorMessage(e),
- });
+ notifyApiError(e, "Could not save practice");
} finally {
setSubmitting(false);
}
@@ -547,7 +543,7 @@ export function AddPracticeFlow() {