diff --git a/src/hooks/usePracticeListSelection.ts b/src/hooks/usePracticeListSelection.ts new file mode 100644 index 0000000..0012090 --- /dev/null +++ b/src/hooks/usePracticeListSelection.ts @@ -0,0 +1,75 @@ +import { useCallback, useEffect, useMemo, useState } from "react" +import type { ParentContextPractice } from "../types/course.types" + +export function usePracticeListSelection( + visiblePractices: ParentContextPractice[], +) { + const [selectedIds, setSelectedIds] = useState>(() => new Set()) + + const visibleIds = useMemo( + () => new Set(visiblePractices.map((practice) => practice.id)), + [visiblePractices], + ) + + useEffect(() => { + setSelectedIds((prev) => { + const next = new Set( + [...prev].filter((id) => visibleIds.has(id)), + ) + return next.size === prev.size ? prev : next + }) + }, [visibleIds]) + + const selectedPractices = useMemo( + () => visiblePractices.filter((practice) => selectedIds.has(practice.id)), + [visiblePractices, selectedIds], + ) + + const allSelected = + visiblePractices.length > 0 && + visiblePractices.every((practice) => selectedIds.has(practice.id)) + + const isSelected = useCallback( + (practiceId: number) => selectedIds.has(practiceId), + [selectedIds], + ) + + const toggle = useCallback((practiceId: number) => { + setSelectedIds((prev) => { + const next = new Set(prev) + if (next.has(practiceId)) { + next.delete(practiceId) + } else { + next.add(practiceId) + } + return next + }) + }, []) + + const toggleAll = useCallback(() => { + setSelectedIds((prev) => { + if ( + visiblePractices.length > 0 && + visiblePractices.every((practice) => prev.has(practice.id)) + ) { + return new Set() + } + return new Set(visiblePractices.map((practice) => practice.id)) + }) + }, [visiblePractices]) + + const clear = useCallback(() => { + setSelectedIds(new Set()) + }, []) + + return { + selectedIds, + selectedCount: selectedIds.size, + selectedPractices, + allSelected, + isSelected, + toggle, + toggleAll, + clear, + } +} diff --git a/src/lib/practiceBulkActions.ts b/src/lib/practiceBulkActions.ts new file mode 100644 index 0000000..14d0b15 --- /dev/null +++ b/src/lib/practiceBulkActions.ts @@ -0,0 +1,174 @@ +import { + deleteExamPrepPractice, + deleteParentLinkedPractice, +} from "../api/courses.api" +import type { ParentContextPractice, PracticeParent } from "../types/course.types" +import { parentsFromPractice } from "./practiceParents" +import { + isPracticeParentUnlinkNotLinkedError, + resolveCourseContextUnlinkParent, + resolveModuleContextUnlinkParent, + unlinkPracticeFromParent, +} from "./practiceParentUnlink" + +export type PracticeUnlinkContext = + | { scope: "course"; courseId: number; moduleIds: number[] } + | { scope: "module"; moduleId: number; lessonIds: number[] } + | { scope: "lesson"; lessonId: number } + | { scope: "unit"; unitId: number } + | { scope: "catalog_course"; catalogCourseId: number } + +export type BulkPracticeActionResult = { + succeeded: number + skipped: number + failed: number +} + +export function resolvePracticeUnlinkParent( + practice: ParentContextPractice, + context: PracticeUnlinkContext, +): PracticeParent | null { + switch (context.scope) { + case "course": + return resolveCourseContextUnlinkParent( + practice, + context.courseId, + context.moduleIds, + ) + case "module": + return resolveModuleContextUnlinkParent( + practice, + context.moduleId, + context.lessonIds, + ) + case "lesson": + return ( + parentsFromPractice(practice).find( + (p) => + p.parent_kind === "LESSON" && p.parent_id === context.lessonId, + ) ?? null + ) + case "unit": + return ( + parentsFromPractice(practice).find( + (p) => p.parent_kind === "UNIT" && p.parent_id === context.unitId, + ) ?? null + ) + case "catalog_course": + return ( + parentsFromPractice(practice).find( + (p) => + p.parent_kind === "CATALOG_COURSE" && + p.parent_id === context.catalogCourseId, + ) ?? null + ) + } +} + +export async function bulkUnlinkPractices(opts: { + practices: ParentContextPractice[] + context: PracticeUnlinkContext + isExamPrep: boolean +}): Promise { + const result: BulkPracticeActionResult = { + succeeded: 0, + skipped: 0, + failed: 0, + } + + for (const practice of opts.practices) { + const parent = resolvePracticeUnlinkParent(practice, opts.context) + if (!parent) { + result.skipped += 1 + continue + } + try { + await unlinkPracticeFromParent({ + practiceId: practice.id, + parent, + isExamPrep: opts.isExamPrep, + }) + result.succeeded += 1 + } catch (error) { + if (isPracticeParentUnlinkNotLinkedError(error)) { + result.skipped += 1 + } else { + result.failed += 1 + } + } + } + + return result +} + +export async function bulkDeletePractices(opts: { + practices: ParentContextPractice[] + isExamPrep: boolean +}): Promise { + const result: BulkPracticeActionResult = { + succeeded: 0, + skipped: 0, + failed: 0, + } + + for (const practice of opts.practices) { + try { + if (opts.isExamPrep) { + await deleteExamPrepPractice(practice.id) + } else { + await deleteParentLinkedPractice(practice.id) + } + result.succeeded += 1 + } catch { + result.failed += 1 + } + } + + return result +} + +export function formatBulkPracticeActionToast( + action: "unlink" | "delete", + locationLabel: string, + result: BulkPracticeActionResult, +): { kind: "success" | "info" | "error"; message: string } { + const { succeeded, skipped, failed } = result + const count = succeeded + skipped + failed + + if (succeeded === 0 && failed === 0 && skipped > 0) { + return { + kind: "info", + message: + action === "unlink" + ? "Selected practices were already removed from this location." + : "No practices were deleted.", + } + } + + if (failed > 0 && succeeded === 0) { + return { + kind: "error", + message: + action === "unlink" + ? `Could not unlink ${failed} of ${count} selected practice${count === 1 ? "" : "s"}.` + : `Could not delete ${failed} of ${count} selected practice${count === 1 ? "" : "s"}.`, + } + } + + if (action === "unlink") { + let message = `Removed ${succeeded} practice${succeeded === 1 ? "" : "s"} from ${locationLabel}.` + if (skipped > 0) { + message += ` ${skipped} ${skipped === 1 ? "was" : "were"} already removed or could not be matched.` + } + if (failed > 0) { + message += ` ${failed} failed.` + } + return { kind: failed > 0 ? "info" : "success", message } + } + + let message = `Deleted ${succeeded} practice${succeeded === 1 ? "" : "s"}.` + if (failed > 0) { + message += ` ${failed} could not be deleted.` + } + return { kind: failed > 0 ? "info" : "success", message } +} diff --git a/src/pages/content-management/CourseDetailPage.tsx b/src/pages/content-management/CourseDetailPage.tsx index 76517e3..935d08d 100644 --- a/src/pages/content-management/CourseDetailPage.tsx +++ b/src/pages/content-management/CourseDetailPage.tsx @@ -62,7 +62,7 @@ import { } from "../../lib/fetchAllOffsetPages"; import { AddModuleModal } from "./components/AddModuleModal"; import { ModuleIconUploadField } from "./components/ModuleIconUploadField"; -import { ModulePracticeCard } from "./components/ModulePracticeCard"; +import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid"; import { PublishPracticeButton } from "./components/PublishPracticeButton"; import { DisplayValue } from "../../lib/displayValue" import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents" @@ -938,32 +938,33 @@ export function CourseDetailPage() { {practicesLoadError} ) : filteredPractices.length > 0 ? ( -
- {filteredPractices.map((practice) => ( - - navigate( - `/new-content/learn-english/${programIdParam}/courses/${courseIdNum}/edit-practice/${practice.id}?backTo=courses`, - ) - } - onPublish={() => - void handlePracticePublishStatus( - practice.id, - "PUBLISHED", - ) - } - onSaveAsDraft={() => - void handlePracticePublishStatus(practice.id, "DRAFT") - } - onUnlink={() => setPracticeToUnlink(practice)} - onDelete={() => setPracticeToDelete(practice)} - /> - ))} -
+ + navigate( + `/new-content/learn-english/${programIdParam}/courses/${courseIdNum}/edit-practice/${practice.id}?backTo=courses`, + ) + } + onPublish={(practiceId) => + void handlePracticePublishStatus(practiceId, "PUBLISHED") + } + onSaveAsDraft={(practiceId) => + void handlePracticePublishStatus(practiceId, "DRAFT") + } + onUnlink={(practice) => setPracticeToUnlink(practice)} + onDelete={(practice) => setPracticeToDelete(practice)} + /> ) : (
diff --git a/src/pages/content-management/LessonPracticesPage.tsx b/src/pages/content-management/LessonPracticesPage.tsx index b6788fe..4f6d94f 100644 --- a/src/pages/content-management/LessonPracticesPage.tsx +++ b/src/pages/content-management/LessonPracticesPage.tsx @@ -21,7 +21,7 @@ import { } from "../../lib/practiceParentUnlink"; import { Button } from "../../components/ui/button"; import { PracticeActionButton } from "./components/PracticeActionButton"; -import { ModulePracticeCard } from "./components/ModulePracticeCard"; +import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid"; import { Dialog, DialogContent, @@ -413,25 +413,26 @@ export function LessonPracticesPage() {

) : ( -
- {filteredPractices.map((p) => ( - void navigate(editPracticeHref(p.id))} - onPublish={() => - void handlePracticePublishStatus(p.id, "PUBLISHED") - } - onSaveAsDraft={() => - void handlePracticePublishStatus(p.id, "DRAFT") - } - onUnlink={() => setPracticeToUnlink(p)} - onDelete={() => setPracticeToDelete(p)} - /> - ))} -
+ void navigate(editPracticeHref(practice.id))} + onPublish={(practiceId) => + void handlePracticePublishStatus(practiceId, "PUBLISHED") + } + onSaveAsDraft={(practiceId) => + void handlePracticePublishStatus(practiceId, "DRAFT") + } + onUnlink={(practice) => setPracticeToUnlink(practice)} + onDelete={(practice) => setPracticeToDelete(practice)} + /> )}
)} diff --git a/src/pages/content-management/ModuleDetailPage.tsx b/src/pages/content-management/ModuleDetailPage.tsx index 76b1637..0e8d689 100644 --- a/src/pages/content-management/ModuleDetailPage.tsx +++ b/src/pages/content-management/ModuleDetailPage.tsx @@ -49,7 +49,7 @@ import { Textarea } from "../../components/ui/textarea"; import { resolveThumbnailForPreview } from "../../lib/videoPreview"; import { cn } from "../../lib/utils"; import { LessonMediaUploadField } from "./components/LessonMediaUploadField"; -import { ModulePracticeCard } from "./components/ModulePracticeCard"; +import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid"; import { VideoCard } from "./components/VideoCard"; import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar"; import { ContentPageDescription } from "./components/ContentPageDescription"; @@ -746,32 +746,33 @@ export function ModuleDetailPage() { {practicesLoadError} ) : filteredPractices.length > 0 ? ( -
- {filteredPractices.map((practice) => ( - - navigate( - `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}/edit-practice/${practice.id}?backTo=module`, - ) - } - onPublish={() => - void handlePracticePublishStatus( - practice.id, - "PUBLISHED", - ) - } - onSaveAsDraft={() => - void handlePracticePublishStatus(practice.id, "DRAFT") - } - onUnlink={() => setPracticeToUnlink(practice)} - onDelete={() => setPracticeToDelete(practice)} - /> - ))} -
+ + navigate( + `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}/edit-practice/${practice.id}?backTo=module`, + ) + } + onPublish={(practiceId) => + void handlePracticePublishStatus(practiceId, "PUBLISHED") + } + onSaveAsDraft={(practiceId) => + void handlePracticePublishStatus(practiceId, "DRAFT") + } + onUnlink={(practice) => setPracticeToUnlink(practice)} + onDelete={(practice) => setPracticeToDelete(practice)} + /> ) : (
diff --git a/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx b/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx index e777ce0..d4f95fb 100644 --- a/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx +++ b/src/pages/content-management/components/CatalogCoursePracticesPanel.tsx @@ -25,7 +25,7 @@ import { DialogTitle, } from "../../../components/ui/dialog" import { ContentListSearchFilterBar } from "./ContentListSearchFilterBar" -import { ModulePracticeCard } from "./ModulePracticeCard" +import { PracticeSelectableGrid } from "./PracticeSelectableGrid" import { filterBySearchAndPublishStatus, type PublishStatusFilter, @@ -249,21 +249,26 @@ export function CatalogCoursePracticesPanel({

) : ( -
- {filteredPractices.map((practice) => ( - navigate(editPracticeHref(practice.id))} - onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} - onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} - onUnlink={() => setPracticeToUnlink(practice)} - onDelete={() => setPracticeToDelete(practice)} - /> - ))} -
+ navigate(editPracticeHref(practice.id))} + onPublish={(practiceId) => + void handlePracticePublishStatus(practiceId, "PUBLISHED") + } + onSaveAsDraft={(practiceId) => + void handlePracticePublishStatus(practiceId, "DRAFT") + } + onUnlink={(practice) => setPracticeToUnlink(practice)} + onDelete={(practice) => setPracticeToDelete(practice)} + /> )} void; onUnlink?: () => void; onDelete?: () => void; + selectable?: boolean; + selected?: boolean; + onSelectedChange?: (selected: boolean) => void; }; export function ModulePracticeCard({ @@ -42,6 +45,9 @@ export function ModulePracticeCard({ onSaveAsDraft, onUnlink, onDelete, + selectable = false, + selected = false, + onSelectedChange, }: ModulePracticeCardProps) { const isPublished = isPracticePublished(practice); const statusLabel = practicePublishStatus(practice) ?? "DRAFT"; @@ -81,8 +87,25 @@ export function ModulePracticeCard({ return ( <> - +
+ {selectable ? ( + + ) : null} {thumbnailSrc && !thumbFailed ? ( Promise + onEdit: (practice: ParentContextPractice) => void + onPublish: (practiceId: number) => void + onSaveAsDraft: (practiceId: number) => void + onUnlink: (practice: ParentContextPractice) => void + onDelete: (practice: ParentContextPractice) => void + unlinkActionLabel?: string + deleteActionLabel?: string +} + +function summarizePracticeTitles(practices: ParentContextPractice[]): string { + const titles = practices + .slice(0, 3) + .map((practice) => practice.title?.trim() || `Practice #${practice.id}`) + if (practices.length <= 3) { + return titles.join(", ") + } + return `${titles.join(", ")}, and ${practices.length - 3} more` +} + +export function PracticeSelectableGrid({ + practices, + searchQuery = "", + locationLabel, + unlinkContext, + isExamPrep = false, + publishStatusUpdatingId = null, + onReload, + onEdit, + onPublish, + onSaveAsDraft, + onUnlink, + onDelete, + unlinkActionLabel = "Remove from location", + deleteActionLabel = "Delete permanently", +}: PracticeSelectableGridProps) { + const selection = usePracticeListSelection(practices) + const [bulkUnlinkOpen, setBulkUnlinkOpen] = useState(false) + const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false) + const [bulkUnlinking, setBulkUnlinking] = useState(false) + const [bulkDeleting, setBulkDeleting] = useState(false) + + const runBulkUnlink = async () => { + if (selection.selectedPractices.length === 0) return + setBulkUnlinking(true) + try { + const result = await bulkUnlinkPractices({ + practices: selection.selectedPractices, + context: unlinkContext, + isExamPrep, + }) + const toastResult = formatBulkPracticeActionToast( + "unlink", + locationLabel, + result, + ) + if (toastResult.kind === "success") { + toast.success(toastResult.message) + } else if (toastResult.kind === "info") { + toast.info(toastResult.message) + } else { + toast.error(toastResult.message) + } + setBulkUnlinkOpen(false) + selection.clear() + await onReload() + } catch (error) { + notifyApiError(error, "Could not unlink selected practices") + } finally { + setBulkUnlinking(false) + } + } + + const runBulkDelete = async () => { + if (selection.selectedPractices.length === 0) return + setBulkDeleting(true) + try { + const result = await bulkDeletePractices({ + practices: selection.selectedPractices, + isExamPrep, + }) + const toastResult = formatBulkPracticeActionToast( + "delete", + locationLabel, + result, + ) + if (toastResult.kind === "success") { + toast.success(toastResult.message) + } else if (toastResult.kind === "info") { + toast.info(toastResult.message) + } else { + toast.error(toastResult.message) + } + setBulkDeleteOpen(false) + selection.clear() + await onReload() + } catch (error) { + notifyApiError(error, "Could not delete selected practices") + } finally { + setBulkDeleting(false) + } + } + + return ( +
+
+ + + +
+ +
+ {practices.map((practice) => ( + selection.toggle(practice.id)} + onEdit={() => onEdit(practice)} + onPublish={() => onPublish(practice.id)} + onSaveAsDraft={() => onSaveAsDraft(practice.id)} + onUnlink={() => onUnlink(practice)} + onDelete={() => onDelete(practice)} + /> + ))} +
+ + { + if (!open && !bulkUnlinking) setBulkUnlinkOpen(false) + }} + > + + + + Remove {selection.selectedCount} practice + {selection.selectedCount === 1 ? "" : "s"} from {locationLabel}? + + + {summarizePracticeTitles(selection.selectedPractices)} will be + detached from this location. Questions are kept unless you delete + the practices afterward. + + + + + + + + + + { + if (!open && !bulkDeleting) setBulkDeleteOpen(false) + }} + > + + + + Delete {selection.selectedCount} practice + {selection.selectedCount === 1 ? "" : "s"} permanently? + + + {summarizePracticeTitles(selection.selectedPractices)} and all of + their questions will be deleted. This cannot be undone. + + + + + + + + +
+ ) +} diff --git a/src/pages/content-management/components/UnitPracticesPanel.tsx b/src/pages/content-management/components/UnitPracticesPanel.tsx index 3ca47eb..d11e700 100644 --- a/src/pages/content-management/components/UnitPracticesPanel.tsx +++ b/src/pages/content-management/components/UnitPracticesPanel.tsx @@ -25,7 +25,7 @@ import { DialogTitle, } from "../../../components/ui/dialog" import { ContentListSearchFilterBar } from "./ContentListSearchFilterBar" -import { ModulePracticeCard } from "./ModulePracticeCard" +import { PracticeSelectableGrid } from "./PracticeSelectableGrid" import { filterBySearchAndPublishStatus, type PublishStatusFilter, @@ -248,21 +248,26 @@ export function UnitPracticesPanel({

) : ( -
- {filteredPractices.map((practice) => ( - navigate(editPracticeHref(practice.id))} - onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} - onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} - onUnlink={() => setPracticeToUnlink(practice)} - onDelete={() => setPracticeToDelete(practice)} - /> - ))} -
+ navigate(editPracticeHref(practice.id))} + onPublish={(practiceId) => + void handlePracticePublishStatus(practiceId, "PUBLISHED") + } + onSaveAsDraft={(practiceId) => + void handlePracticePublishStatus(practiceId, "DRAFT") + } + onUnlink={(practice) => setPracticeToUnlink(practice)} + onDelete={(practice) => setPracticeToDelete(practice)} + /> )}