diff --git a/src/App.tsx b/src/App.tsx index 9c036fe..6ce0f59 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,3 @@ -import { useEffect } from 'react' import { Toaster } from 'sonner' import { AppRoutes } from './app/AppRoutes' import { useTheme } from './contexts/ThemeContext' @@ -6,6 +5,24 @@ import { clearTeamSession } from './lib/teamAuthStorage' const SESSION_KEY = 'yimaru_session_active' +/** + * Clear persisted team tokens when this browser tab session is new. + * Must run before the first render so AppLayout/Login never mount protected + * fetches against a stale localStorage session and toast "Authorization header missing". + */ +function bootstrapBrowserSession() { + try { + if (!sessionStorage.getItem(SESSION_KEY)) { + clearTeamSession() + sessionStorage.setItem(SESSION_KEY, '1') + } + } catch { + // sessionStorage unavailable (private mode quirks) — leave tokens alone + } +} + +bootstrapBrowserSession() + function AppToaster() { const { resolvedTheme } = useTheme() return ( @@ -26,13 +43,6 @@ function AppToaster() { } export default function App() { - useEffect(() => { - if (!sessionStorage.getItem(SESSION_KEY)) { - clearTeamSession() - sessionStorage.setItem(SESSION_KEY, '1') - } - }, []) - return ( <> diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index 0293b13..f2bb359 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -510,6 +510,32 @@ export const reorderModuleLessons = ( data: ReorderOrderedIdsRequest, ) => http.put(`/modules/${moduleId}/lessons/reorder`, data) +/** PUT /exam-prep/catalog-courses/reorder */ +export const reorderExamPrepCatalogCourses = (data: ReorderOrderedIdsRequest) => + http.put("/exam-prep/catalog-courses/reorder", data) + +/** PUT /exam-prep/catalog-courses/:catalogCourseId/units/reorder */ +export const reorderExamPrepUnitsInCatalogCourse = ( + catalogCourseId: number, + data: ReorderOrderedIdsRequest, +) => + http.put( + `/exam-prep/catalog-courses/${catalogCourseId}/units/reorder`, + data, + ) + +/** PUT /exam-prep/units/:unitId/modules/reorder */ +export const reorderExamPrepModulesInUnit = ( + unitId: number, + data: ReorderOrderedIdsRequest, +) => http.put(`/exam-prep/units/${unitId}/modules/reorder`, data) + +/** PUT /exam-prep/modules/:moduleId/lessons/reorder */ +export const reorderExamPrepLessonsInModule = ( + moduleId: number, + data: ReorderOrderedIdsRequest, +) => http.put(`/exam-prep/modules/${moduleId}/lessons/reorder`, data) + export const createProgramCourse = ( programId: number, data: CreateProgramCourseRequest, diff --git a/src/api/http.ts b/src/api/http.ts index cb07deb..6520110 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -104,6 +104,17 @@ function isRefreshableAccessTokenError(error: AxiosError): boolean { ); } +/** 401s that mean "not logged in" — redirect/silent, never toast on login. */ +function isUnauthenticatedClientError(error: AxiosError): boolean { + if (error.response?.status !== 401) return false; + const message = readApiResponseMessage(error.response.data).toLowerCase(); + return ( + message.includes("authorization header missing") || + message.includes("missing authorization") || + (!getAccessToken() && !getRefreshToken()) + ); +} + const refreshAccessToken = async (): Promise => { const refreshToken = getRefreshToken(); if (!refreshToken) { @@ -198,7 +209,9 @@ http.interceptors.response.use( } const skipErrorToast = - originalRequest.skipErrorToast || isAuthEndpointRequest(originalRequest.url); + originalRequest.skipErrorToast || + isAuthEndpointRequest(originalRequest.url) || + isUnauthenticatedClientError(error); if (!skipErrorToast && error.response) { const message = readApiResponseMessage(error.response.data); if (message) { diff --git a/src/pages/content-management/ReorderContentPage.tsx b/src/pages/content-management/ReorderContentPage.tsx index 4784182..22bb6fb 100644 --- a/src/pages/content-management/ReorderContentPage.tsx +++ b/src/pages/content-management/ReorderContentPage.tsx @@ -1,7 +1,14 @@ +import { useState } from "react"; import { ContentHierarchyList } from "./components/ContentHierarchyList"; +import { ExamPrepContentHierarchyList } from "./components/ExamPrepContentHierarchyList"; import { PageBackLink } from "../../components/navigation/PageBackLink"; +import { cn } from "../../lib/utils"; + +type ReorderTab = "learn_english" | "exam_prep"; export function ReorderContentPage() { + const [tab, setTab] = useState("learn_english"); + return (
@@ -12,14 +19,44 @@ export function ReorderContentPage() { Reorder Content

- Drag and drop programs, courses, modules, and lessons to change - their display order. Changes are saved automatically when you drop an - item. + Drag and drop items to change their display order. Changes are saved + automatically when you drop an item.

+ +
+ + +
- + {tab === "learn_english" ? ( + + ) : ( + + )} ); } diff --git a/src/pages/content-management/components/ContentHierarchyList.tsx b/src/pages/content-management/components/ContentHierarchyList.tsx index 81f5156..c2721d6 100644 --- a/src/pages/content-management/components/ContentHierarchyList.tsx +++ b/src/pages/content-management/components/ContentHierarchyList.tsx @@ -49,7 +49,7 @@ import { reorderModuleLessons, } from "../../../api/courses.api"; -function sortBySortOrder(items: T[]): T[] { +export function sortBySortOrder(items: T[]): T[] { return [...items].sort( (a, b) => Number(a.sort_order ?? 0) - Number(b.sort_order ?? 0), ); @@ -179,7 +179,7 @@ interface DraggableListProps { onDelete?: (id: string) => void; } -function DraggableList({ +export function DraggableList({ items, onReorder, icon, @@ -269,7 +269,7 @@ interface SectionProps { children: React.ReactNode; } -function HierarchySection({ +export function HierarchySection({ title, icon, isOpen, diff --git a/src/pages/content-management/components/ExamPrepContentHierarchyList.tsx b/src/pages/content-management/components/ExamPrepContentHierarchyList.tsx new file mode 100644 index 0000000..5d38ab6 --- /dev/null +++ b/src/pages/content-management/components/ExamPrepContentHierarchyList.tsx @@ -0,0 +1,391 @@ +import { notifyApiError } from "../../../lib/apiErrors" +import { useCallback, useEffect, useState } from "react" +import { + BookOpen, + GraduationCap, + Layers, + Loader2, + PlayCircle, + RotateCcw, +} from "lucide-react" +import { toast } from "sonner" +import { + getExamPrepCatalogCourses, + getExamPrepCatalogUnits, + getExamPrepModuleLessons, + getExamPrepUnitModules, + reorderExamPrepCatalogCourses, + reorderExamPrepLessonsInModule, + reorderExamPrepModulesInUnit, + reorderExamPrepUnitsInCatalogCourse, +} from "../../../api/courses.api" +import { + DraggableList, + HierarchySection, + sortBySortOrder, + type BaseItem, +} from "./ContentHierarchyList" + +interface CatalogCourse extends BaseItem {} +interface Unit extends BaseItem { + catalogCourseId: string +} +interface UnitModule extends BaseItem { + unitId: string +} +interface ModuleLesson extends BaseItem { + moduleId: string +} + +const FETCH_LIMIT = 500 + +export function ExamPrepContentHierarchyList() { + const [catalogCourses, setCatalogCourses] = useState([]) + const [units, setUnits] = useState([]) + const [modules, setModules] = useState([]) + const [lessons, setLessons] = useState([]) + const [loading, setLoading] = useState>({}) + const [openSections, setOpenSections] = useState>({ + catalogCourse: true, + }) + + const fetchHierarchy = useCallback(async () => { + setLoading({ catalogCourse: true }) + try { + const coursesRes = await getExamPrepCatalogCourses({ + limit: FETCH_LIMIT, + offset: 0, + }) + const fetchedCourses: CatalogCourse[] = sortBySortOrder( + coursesRes.data?.data?.catalog_courses ?? [], + ).map((c) => ({ + id: String(c.id), + name: c.name, + thumbnail: c.thumbnail ?? undefined, + })) + setCatalogCourses(fetchedCourses) + setLoading((prev) => ({ ...prev, catalogCourse: false })) + + if (fetchedCourses.length === 0) { + setUnits([]) + setModules([]) + setLessons([]) + return + } + + setLoading((prev) => ({ ...prev, unit: true })) + const unitsResults = await Promise.all( + fetchedCourses.map((c) => + getExamPrepCatalogUnits(Number(c.id), { limit: FETCH_LIMIT, offset: 0 }), + ), + ) + const fetchedUnits: Unit[] = unitsResults.flatMap((res, idx) => + sortBySortOrder(res.data?.data?.units ?? []).map((u) => ({ + id: String(u.id), + name: u.name, + thumbnail: u.thumbnail ?? undefined, + catalogCourseId: fetchedCourses[idx].id, + })), + ) + setUnits(fetchedUnits) + setLoading((prev) => ({ ...prev, unit: false })) + + if (fetchedUnits.length === 0) { + setModules([]) + setLessons([]) + return + } + + setLoading((prev) => ({ ...prev, module: true })) + const modulesResults = await Promise.all( + fetchedUnits.map((u) => + getExamPrepUnitModules(Number(u.id), { limit: FETCH_LIMIT, offset: 0 }), + ), + ) + const fetchedModules: UnitModule[] = modulesResults.flatMap((res, idx) => + sortBySortOrder(res.data?.data?.modules ?? []).map((m) => ({ + id: String(m.id), + name: m.name, + thumbnail: m.thumbnail ?? m.icon ?? undefined, + unitId: fetchedUnits[idx].id, + })), + ) + setModules(fetchedModules) + setLoading((prev) => ({ ...prev, module: false })) + + if (fetchedModules.length === 0) { + setLessons([]) + return + } + + setLoading((prev) => ({ ...prev, lesson: true })) + const lessonsResults = await Promise.all( + fetchedModules.map((m) => + getExamPrepModuleLessons(Number(m.id), { limit: FETCH_LIMIT, offset: 0 }), + ), + ) + const fetchedLessons: ModuleLesson[] = lessonsResults.flatMap((res, idx) => + sortBySortOrder(res.data?.data?.lessons ?? []).map((l) => ({ + id: String(l.id), + name: l.title, + thumbnail: l.thumbnail ?? undefined, + moduleId: fetchedModules[idx].id, + })), + ) + setLessons(fetchedLessons) + } catch (error) { + console.error("Failed to fetch exam prep hierarchy:", error) + notifyApiError(error, "Failed to load exam prep content") + } finally { + setLoading({}) + } + }, []) + + useEffect(() => { + void fetchHierarchy() + }, [fetchHierarchy]) + + const toggleSection = (id: string) => { + setOpenSections((prev) => ({ ...prev, [id]: !prev[id] })) + } + + const toOrderedIds = (items: BaseItem[]) => items.map((item) => Number(item.id)) + + const reorderSiblings = ( + siblings: T[], + activeId: string, + overId: string, + ): T[] | null => { + const oldIndex = siblings.findIndex((i) => i.id === activeId) + const newIndex = siblings.findIndex((i) => i.id === overId) + if (oldIndex === -1 || newIndex === -1 || oldIndex === newIndex) { + return null + } + const next = [...siblings] + const [moved] = next.splice(oldIndex, 1) + next.splice(newIndex, 0, moved) + return next + } + + const handleCatalogCourseReorder = async (activeId: string, overId: string) => { + const reordered = reorderSiblings(catalogCourses, activeId, overId) + if (!reordered) return + const previous = catalogCourses + setCatalogCourses(reordered) + try { + await reorderExamPrepCatalogCourses({ ordered_ids: toOrderedIds(reordered) }) + toast.success("Catalog courses reordered") + } catch (error) { + setCatalogCourses(previous) + notifyApiError(error, "Failed to reorder catalog courses") + } + } + + const handleUnitReorder = async ( + catalogCourseId: string, + activeId: string, + overId: string, + ) => { + const siblings = units.filter((u) => u.catalogCourseId === catalogCourseId) + const reordered = reorderSiblings(siblings, activeId, overId) + if (!reordered) return + const previous = units + setUnits((prev) => [ + ...prev.filter((u) => u.catalogCourseId !== catalogCourseId), + ...reordered, + ]) + try { + await reorderExamPrepUnitsInCatalogCourse(Number(catalogCourseId), { + ordered_ids: toOrderedIds(reordered), + }) + toast.success("Units reordered") + } catch (error) { + setUnits(previous) + notifyApiError(error, "Failed to reorder units") + } + } + + const handleModuleReorder = async (unitId: string, activeId: string, overId: string) => { + const siblings = modules.filter((m) => m.unitId === unitId) + const reordered = reorderSiblings(siblings, activeId, overId) + if (!reordered) return + const previous = modules + setModules((prev) => [ + ...prev.filter((m) => m.unitId !== unitId), + ...reordered, + ]) + try { + await reorderExamPrepModulesInUnit(Number(unitId), { + ordered_ids: toOrderedIds(reordered), + }) + toast.success("Modules reordered") + } catch (error) { + setModules(previous) + notifyApiError(error, "Failed to reorder modules") + } + } + + const handleLessonReorder = async ( + moduleId: string, + activeId: string, + overId: string, + ) => { + const siblings = lessons.filter((l) => l.moduleId === moduleId) + const reordered = reorderSiblings(siblings, activeId, overId) + if (!reordered) return + const previous = lessons + setLessons((prev) => [ + ...prev.filter((l) => l.moduleId !== moduleId), + ...reordered, + ]) + try { + await reorderExamPrepLessonsInModule(Number(moduleId), { + ordered_ids: toOrderedIds(reordered), + }) + toast.success("Lessons reordered") + } catch (error) { + setLessons(previous) + notifyApiError(error, "Failed to reorder lessons") + } + } + + return ( +
+
+
+

+ Exam prep hierarchy +

+

+ Catalog courses, units, modules, and lessons (IELTS, Duolingo, etc.) +

+
+ +
+ +
+ } + isOpen={openSections.catalogCourse} + onToggle={() => toggleSection("catalogCourse")} + > + {loading.catalogCourse ? ( +
+ +
+ ) : ( + void handleCatalogCourseReorder(active, over)} + icon={} + /> + )} +
+ + } + isOpen={openSections.unit} + onToggle={() => toggleSection("unit")} + > + {loading.unit ? ( +
+ +
+ ) : ( + catalogCourses.map((course) => { + const courseUnits = units.filter((u) => u.catalogCourseId === course.id) + if (courseUnits.length === 0) return null + return ( +
+

+ {course.name} +

+ + void handleUnitReorder(course.id, active, over) + } + icon={} + /> +
+ ) + }) + )} +
+ + } + isOpen={openSections.module} + onToggle={() => toggleSection("module")} + > + {loading.module ? ( +
+ +
+ ) : ( + units.map((unit) => { + const unitModules = modules.filter((m) => m.unitId === unit.id) + if (unitModules.length === 0) return null + return ( +
+

+ {unit.name} +

+ + void handleModuleReorder(unit.id, active, over) + } + icon={} + /> +
+ ) + }) + )} +
+ + } + isOpen={openSections.lesson} + onToggle={() => toggleSection("lesson")} + > + {loading.lesson ? ( +
+ +
+ ) : ( + modules.map((module) => { + const moduleLessons = lessons.filter((l) => l.moduleId === module.id) + if (moduleLessons.length === 0) return null + return ( +
+

+ {module.name} +

+ + void handleLessonReorder(module.id, active, over) + } + icon={} + /> +
+ ) + }) + )} +
+
+
+ ) +} diff --git a/src/pages/issues/IssuesPage.tsx b/src/pages/issues/IssuesPage.tsx index 1c8fafe..5a817ed 100644 --- a/src/pages/issues/IssuesPage.tsx +++ b/src/pages/issues/IssuesPage.tsx @@ -53,7 +53,7 @@ import { import type { Issue } from "../../types/issue.types"; // ── Status configuration ─────────────────────────────────────────── -const STATUSES = ["pending", "in_progress", "resolved", "closed"] as const; +const STATUSES = ["pending", "in_progress", "resolved", "rejected"] as const; const ISSUE_TYPES = ["bug", "video", "course", "account", "payment", "other"] as const; @@ -81,9 +81,10 @@ function getStatusConfig(status: string): { classes: "bg-emerald-50 text-emerald-700 border-emerald-200", icon: CheckCircle2, }; - case "closed": + case "rejected": + case "closed": // legacy label; API status is rejected return { - label: "Closed", + label: status === "closed" ? "Closed" : "Rejected", classes: "bg-grayScale-100 text-grayScale-500 border-grayScale-200", icon: XCircle, };