Fix practice unlink to remove only direct parent links across Learn English and Exam Prep.

Use server-side pagination and search for activity logs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-08-19 18:23:06 +03:00
parent 620670cf0c
commit c98efdc6c9
10 changed files with 398 additions and 254 deletions

View File

@ -114,6 +114,7 @@ function buildQueryParams(filters?: ActivityLogFilters): Record<string, string |
if (filters?.resource_id != null) params.resource_id = filters.resource_id if (filters?.resource_id != null) params.resource_id = filters.resource_id
if (filters?.after?.trim()) params.after = filters.after.trim() if (filters?.after?.trim()) params.after = filters.after.trim()
if (filters?.before?.trim()) params.before = filters.before.trim() if (filters?.before?.trim()) params.before = filters.before.trim()
if (filters?.search?.trim()) params.search = filters.search.trim()
return params return params
} }

View File

@ -2,23 +2,15 @@ import {
deleteExamPrepPractice, deleteExamPrepPractice,
deleteParentLinkedPractice, deleteParentLinkedPractice,
} from "../api/courses.api" } from "../api/courses.api"
import type { ParentContextPractice, PracticeParent } from "../types/course.types" import type { ParentContextPractice } from "../types/course.types"
import { parentsFromPractice } from "./practiceParents"
import { import {
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listCourseContextUnlinkParents, listPracticeUnlinkParentsForScope,
listModuleContextUnlinkParents, type PracticeUnlinkScope,
resolveCourseContextUnlinkParent,
resolveModuleContextUnlinkParent,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "./practiceParentUnlink" } from "./practiceParentUnlink"
export type PracticeUnlinkContext = export type PracticeUnlinkContext = PracticeUnlinkScope
| { scope: "course"; courseId: number; moduleIds: number[]; lessonIds?: number[] }
| { scope: "module"; moduleId: number; lessonIds: number[] }
| { scope: "lesson"; lessonId: number }
| { scope: "unit"; unitId: number }
| { scope: "catalog_course"; catalogCourseId: number }
export type BulkPracticeActionResult = { export type BulkPracticeActionResult = {
succeeded: number succeeded: number
@ -26,76 +18,11 @@ export type BulkPracticeActionResult = {
failed: number failed: number
} }
export function resolvePracticeUnlinkParent(
practice: ParentContextPractice,
context: PracticeUnlinkContext,
): PracticeParent | null {
switch (context.scope) {
case "course":
return resolveCourseContextUnlinkParent(
practice,
context.courseId,
context.moduleIds,
context.lessonIds ?? [],
)
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 function listPracticeUnlinkParents( export function listPracticeUnlinkParents(
practice: ParentContextPractice, practice: ParentContextPractice,
context: PracticeUnlinkContext, context: PracticeUnlinkContext,
): PracticeParent[] { ) {
switch (context.scope) { return listPracticeUnlinkParentsForScope(practice, context)
case "course":
return listCourseContextUnlinkParents(
practice,
context.courseId,
context.moduleIds,
context.lessonIds ?? [],
)
case "module":
return listModuleContextUnlinkParents(
practice,
context.moduleId,
context.lessonIds,
)
case "lesson": {
const parent = resolvePracticeUnlinkParent(practice, context)
return parent ? [parent] : []
}
case "unit":
case "catalog_course": {
const parent = resolvePracticeUnlinkParent(practice, context)
return parent ? [parent] : []
}
}
} }
export async function bulkUnlinkPractices(opts: { export async function bulkUnlinkPractices(opts: {
@ -188,7 +115,7 @@ export function formatBulkPracticeActionToast(
kind: "info", kind: "info",
message: message:
action === "unlink" action === "unlink"
? "Selected practices were already removed from this location." ? "Selected practices are not directly linked to this location (they may appear via a child module or lesson)."
: "No practices were deleted.", : "No practices were deleted.",
} }
} }
@ -206,7 +133,7 @@ export function formatBulkPracticeActionToast(
if (action === "unlink") { if (action === "unlink") {
let message = `Removed ${succeeded} practice${succeeded === 1 ? "" : "s"} from ${locationLabel}.` let message = `Removed ${succeeded} practice${succeeded === 1 ? "" : "s"} from ${locationLabel}.`
if (skipped > 0) { if (skipped > 0) {
message += ` ${skipped} ${skipped === 1 ? "was" : "were"} already removed or could not be matched.` message += ` ${skipped} ${skipped === 1 ? "was" : "were"} not directly linked here.`
} }
if (failed > 0) { if (failed > 0) {
message += ` ${failed} failed.` message += ` ${failed} failed.`

View File

@ -45,91 +45,210 @@ export function isPracticeParentUnlinkNotLinkedError(err: unknown): boolean {
return msg.includes("not linked") return msg.includes("not linked")
} }
/** Parent row to DELETE when removing a practice from a module's practice tab. */ function directParentsMatching(
export function resolveModuleContextUnlinkParent(
practice: ParentContextPractice, practice: ParentContextPractice,
moduleId: number, kind: PracticeParent["parent_kind"],
lessonIdsInModule: number[], parentId: number,
): PracticeParent | null {
return (
listModuleContextUnlinkParents(practice, moduleId, lessonIdsInModule)[0] ??
null
)
}
/** All parent rows to remove when detaching a practice from a module practice tab. */
export function listModuleContextUnlinkParents(
practice: ParentContextPractice,
moduleId: number,
lessonIdsInModule: number[],
): PracticeParent[] { ): PracticeParent[] {
const parents = parentsFromPractice(practice) return dedupeParents(
const lessonIds = new Set(lessonIdsInModule.filter((id) => id > 0)) parentsFromPractice(practice).filter(
const targets: PracticeParent[] = [] (parent) => parent.parent_kind === kind && parent.parent_id === parentId,
),
for (const parent of parents) {
if (parent.parent_kind === "COURSE") continue
if (parent.parent_kind === "MODULE" && parent.parent_id === moduleId) {
targets.push(parent)
} else if (
parent.parent_kind === "LESSON" &&
lessonIds.has(parent.parent_id)
) {
targets.push(parent)
}
}
return dedupeParents(targets)
}
/** Parent row to DELETE when removing a practice from a course's practice tab. */
export function resolveCourseContextUnlinkParent(
practice: ParentContextPractice,
courseId: number,
moduleIdsInCourse: number[],
lessonIdsInCourse: number[] = [],
): PracticeParent | null {
return (
listCourseContextUnlinkParents(
practice,
courseId,
moduleIdsInCourse,
lessonIdsInCourse,
)[0] ?? null
) )
} }
/** All parent rows to remove when detaching a practice from a course practice tab. */ /** Learn English — course practice tab (direct COURSE link only). */
export function listCourseContextUnlinkParents( export function listCourseContextUnlinkParents(
practice: ParentContextPractice, practice: ParentContextPractice,
courseId: number, courseId: number,
moduleIdsInCourse: number[],
lessonIdsInCourse: number[] = [],
): PracticeParent[] { ): PracticeParent[] {
const parents = parentsFromPractice(practice) return directParentsMatching(practice, "COURSE", courseId)
}
export function resolveCourseContextUnlinkParent(
practice: ParentContextPractice,
courseId: number,
): PracticeParent | null {
return listCourseContextUnlinkParents(practice, courseId)[0] ?? null
}
export function hasCourseDirectPracticeLink(
practice: ParentContextPractice,
courseId: number,
): boolean {
return listCourseContextUnlinkParents(practice, courseId).length > 0
}
/** Learn English — module practice tab (direct MODULE link only). */
export function listModuleContextUnlinkParents(
practice: ParentContextPractice,
moduleId: number,
): PracticeParent[] {
return directParentsMatching(practice, "MODULE", moduleId)
}
export function resolveModuleContextUnlinkParent(
practice: ParentContextPractice,
moduleId: number,
): PracticeParent | null {
return listModuleContextUnlinkParents(practice, moduleId)[0] ?? null
}
export function hasModuleDirectPracticeLink(
practice: ParentContextPractice,
moduleId: number,
): boolean {
return listModuleContextUnlinkParents(practice, moduleId).length > 0
}
/** Learn English / Exam Prep — lesson practice tab (direct LESSON link only). */
export function listLessonContextUnlinkParents(
practice: ParentContextPractice,
lessonId: number,
): PracticeParent[] {
return directParentsMatching(practice, "LESSON", lessonId)
}
export function hasLessonDirectPracticeLink(
practice: ParentContextPractice,
lessonId: number,
): boolean {
return listLessonContextUnlinkParents(practice, lessonId).length > 0
}
/** Exam Prep — unit practice tab (direct UNIT link only). */
export function listUnitContextUnlinkParents(
practice: ParentContextPractice,
unitId: number,
): PracticeParent[] {
return directParentsMatching(practice, "UNIT", unitId)
}
export function hasUnitDirectPracticeLink(
practice: ParentContextPractice,
unitId: number,
): boolean {
return listUnitContextUnlinkParents(practice, unitId).length > 0
}
/** Exam Prep — catalog course practice tab (direct CATALOG_COURSE link only). */
export function listCatalogCourseContextUnlinkParents(
practice: ParentContextPractice,
catalogCourseId: number,
): PracticeParent[] {
return directParentsMatching(practice, "CATALOG_COURSE", catalogCourseId)
}
export function hasCatalogCourseDirectPracticeLink(
practice: ParentContextPractice,
catalogCourseId: number,
): boolean {
return listCatalogCourseContextUnlinkParents(practice, catalogCourseId).length > 0
}
export function isPracticeLinkedViaDescendantInCourse(
practice: ParentContextPractice,
courseId: number,
moduleIdsInCourse: number[],
lessonIdsInCourse: number[],
): boolean {
if (hasCourseDirectPracticeLink(practice, courseId)) return false
const moduleIds = new Set(moduleIdsInCourse.filter((id) => id > 0)) const moduleIds = new Set(moduleIdsInCourse.filter((id) => id > 0))
const lessonIds = new Set(lessonIdsInCourse.filter((id) => id > 0)) const lessonIds = new Set(lessonIdsInCourse.filter((id) => id > 0))
const targets: PracticeParent[] = [] return parentsFromPractice(practice).some(
(parent) =>
(parent.parent_kind === "MODULE" && moduleIds.has(parent.parent_id)) ||
(parent.parent_kind === "LESSON" && lessonIds.has(parent.parent_id)),
)
}
for (const parent of parents) { export function isPracticeLinkedViaLessonInModule(
if (parent.parent_kind === "COURSE" && parent.parent_id === courseId) { practice: ParentContextPractice,
targets.push(parent) moduleId: number,
} else if ( lessonIdsInModule: number[],
parent.parent_kind === "MODULE" && ): boolean {
moduleIds.has(parent.parent_id) if (hasModuleDirectPracticeLink(practice, moduleId)) return false
) { const lessonIds = new Set(lessonIdsInModule.filter((id) => id > 0))
targets.push(parent) return parentsFromPractice(practice).some(
} else if ( (parent) =>
parent.parent_kind === "LESSON" && parent.parent_kind === "LESSON" && lessonIds.has(parent.parent_id),
(lessonIds.size === 0 || lessonIds.has(parent.parent_id)) )
) { }
if (lessonIds.size > 0) {
targets.push(parent) export type PracticeUnlinkScope =
} | { scope: "course"; courseId: number; moduleIds?: number[]; lessonIds?: number[] }
} | { scope: "module"; moduleId: number; lessonIds?: number[] }
| { scope: "lesson"; lessonId: number }
| { scope: "unit"; unitId: number }
| { scope: "catalog_course"; catalogCourseId: number }
export function listPracticeUnlinkParentsForScope(
practice: ParentContextPractice,
context: PracticeUnlinkScope,
): PracticeParent[] {
switch (context.scope) {
case "course":
return listCourseContextUnlinkParents(practice, context.courseId)
case "module":
return listModuleContextUnlinkParents(practice, context.moduleId)
case "lesson":
return listLessonContextUnlinkParents(practice, context.lessonId)
case "unit":
return listUnitContextUnlinkParents(practice, context.unitId)
case "catalog_course":
return listCatalogCourseContextUnlinkParents(
practice,
context.catalogCourseId,
)
} }
}
return dedupeParents(targets) export function hasDirectPracticeLinkForScope(
practice: ParentContextPractice,
context: PracticeUnlinkScope,
): boolean {
return listPracticeUnlinkParentsForScope(practice, context).length > 0
}
export function practiceUnlinkBlockedMessage(
practice: ParentContextPractice,
context: PracticeUnlinkScope,
): string | null {
if (hasDirectPracticeLinkForScope(practice, context)) return null
switch (context.scope) {
case "course": {
if (
isPracticeLinkedViaDescendantInCourse(
practice,
context.courseId,
context.moduleIds ?? [],
context.lessonIds ?? [],
)
) {
return "This practice is linked to a module or lesson, not this course. Open that location to unlink it."
}
return "This practice is not linked to this course."
}
case "module": {
if (
isPracticeLinkedViaLessonInModule(
practice,
context.moduleId,
context.lessonIds ?? [],
)
) {
return "This practice is linked to a lesson, not this module. Open the lesson to unlink it."
}
return "This practice is not linked to this module."
}
case "lesson":
return "This practice is not linked to this lesson."
case "unit":
return "This practice is not linked to this unit."
case "catalog_course":
return "This practice is not linked to this catalog course."
}
} }
export async function unlinkPracticeFromParent(opts: { export async function unlinkPracticeFromParent(opts: {

View File

@ -69,8 +69,10 @@ import { PublishPracticeButton } from "./components/PublishPracticeButton";
import { DisplayValue } from "../../lib/displayValue" import { DisplayValue } from "../../lib/displayValue"
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents" import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents"
import { import {
hasCourseDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listCourseContextUnlinkParents, listCourseContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink" } from "../../lib/practiceParentUnlink"
import { SearchHighlight } from "../../components/SearchHighlight" import { SearchHighlight } from "../../components/SearchHighlight"
@ -453,22 +455,27 @@ export function CourseDetailPage() {
if (!practiceToUnlink || !Number.isFinite(courseIdNum) || courseIdNum < 1) { if (!practiceToUnlink || !Number.isFinite(courseIdNum) || courseIdNum < 1) {
return []; return [];
} }
return listCourseContextUnlinkParents( return listCourseContextUnlinkParents(practiceToUnlink, courseIdNum);
practiceToUnlink, }, [courseIdNum, practiceToUnlink]);
courseIdNum,
courseModuleIds, const courseUnlinkContext = useMemo(
courseLessonIds, () => ({
); scope: "course" as const,
}, [ courseId: courseIdNum,
courseIdNum, moduleIds: courseModuleIds,
courseLessonIds, lessonIds: courseLessonIds,
courseModuleIds, }),
practiceToUnlink, [courseIdNum, courseLessonIds, courseModuleIds],
]); );
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink || practiceUnlinkParents.length === 0) { if (!practiceToUnlink || practiceUnlinkParents.length === 0) {
toast.error("This practice is not linked to this course."); toast.error(
practiceToUnlink
? practiceUnlinkBlockedMessage(practiceToUnlink, courseUnlinkContext) ??
"This practice is not linked to this course."
: "This practice is not linked to this course.",
);
return; return;
} }
setUnlinkingPractice(true); setUnlinkingPractice(true);
@ -984,12 +991,7 @@ export function CourseDetailPage() {
practices={filteredPractices} practices={filteredPractices}
searchQuery={practiceSearch} searchQuery={practiceSearch}
locationLabel={displayTitle} locationLabel={displayTitle}
unlinkContext={{ unlinkContext={courseUnlinkContext}
scope: "course",
courseId: courseIdNum,
moduleIds: courseModuleIds,
lessonIds: courseLessonIds,
}}
publishStatusUpdatingId={publishStatusPracticeId} publishStatusUpdatingId={publishStatusPracticeId}
onReload={loadCoursePractices} onReload={loadCoursePractices}
unlinkActionLabel="Remove from course" unlinkActionLabel="Remove from course"
@ -1005,7 +1007,16 @@ export function CourseDetailPage() {
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasCourseDirectPracticeLink(practice, courseIdNum)) {
toast.info(
practiceUnlinkBlockedMessage(practice, courseUnlinkContext) ??
"This practice is not directly linked to this course.",
);
return;
}
setPracticeToUnlink(practice);
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
) : ( ) : (

View File

@ -16,7 +16,10 @@ import {
parentsFromPractice, parentsFromPractice,
} from "../../lib/practiceParents"; } from "../../lib/practiceParents";
import { import {
hasLessonDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listLessonContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink"; } from "../../lib/practiceParentUnlink";
import { Button } from "../../components/ui/button"; import { Button } from "../../components/ui/button";
@ -33,7 +36,6 @@ import type {
ExamPrepLessonPractice, ExamPrepLessonPractice,
GetExamPrepLessonPracticesResponse, GetExamPrepLessonPracticesResponse,
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../types/course.types"; } from "../../types/course.types";
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar"; import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
@ -243,20 +245,35 @@ export function LessonPracticesPage() {
} }
}; };
const lessonParent = useMemo( const lessonUnlinkContext = useMemo(
(): PracticeParent => ({ parent_kind: "LESSON", parent_id: lid }), () => ({ scope: "lesson" as const, lessonId: lid }),
[lid], [lid],
); );
const practiceUnlinkParents = useMemo(() => {
if (!practiceToUnlink) return [];
return listLessonContextUnlinkParents(practiceToUnlink, lid);
}, [lid, practiceToUnlink]);
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return; if (!practiceToUnlink || practiceUnlinkParents.length === 0) {
toast.error(
practiceToUnlink
? practiceUnlinkBlockedMessage(practiceToUnlink, lessonUnlinkContext) ??
"This practice is not linked to this lesson."
: "This practice is not linked to this lesson.",
);
return;
}
setUnlinking(true); setUnlinking(true);
try { try {
await unlinkPracticeFromParent({ for (const parent of practiceUnlinkParents) {
practiceId: practiceToUnlink.id, await unlinkPracticeFromParent({
parent: lessonParent, practiceId: practiceToUnlink.id,
isExamPrep, parent,
}); isExamPrep,
});
}
toast.success(`Practice removed from ${displayTitle}`); toast.success(`Practice removed from ${displayTitle}`);
setPracticeToUnlink(null); setPracticeToUnlink(null);
await load(); await load();
@ -417,7 +434,7 @@ export function LessonPracticesPage() {
practices={filteredPractices} practices={filteredPractices}
searchQuery={listSearch} searchQuery={listSearch}
locationLabel={displayTitle} locationLabel={displayTitle}
unlinkContext={{ scope: "lesson", lessonId: lid }} unlinkContext={lessonUnlinkContext}
isExamPrep={isExamPrep} isExamPrep={isExamPrep}
publishStatusUpdatingId={publishStatusUpdatingId} publishStatusUpdatingId={publishStatusUpdatingId}
onReload={load} onReload={load}
@ -430,7 +447,16 @@ export function LessonPracticesPage() {
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasLessonDirectPracticeLink(practice, lid)) {
toast.info(
practiceUnlinkBlockedMessage(practice, lessonUnlinkContext) ??
"This practice is not directly linked to this lesson.",
);
return;
}
setPracticeToUnlink(practice);
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
)} )}

View File

@ -28,8 +28,10 @@ import {
} from "../../lib/fetchAllOffsetPages"; } from "../../lib/fetchAllOffsetPages";
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents"; import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents";
import { import {
hasModuleDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listModuleContextUnlinkParents, listModuleContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink"; } from "../../lib/practiceParentUnlink";
import { Button } from "../../components/ui/button"; import { Button } from "../../components/ui/button";
@ -361,19 +363,29 @@ export function ModuleDetailPage() {
[lessons], [lessons],
); );
const moduleUnlinkContext = useMemo(
() => ({
scope: "module" as const,
moduleId: Number(moduleId),
lessonIds: moduleLessonIds,
}),
[moduleId, moduleLessonIds],
);
const practiceUnlinkParents = useMemo((): PracticeParent[] => { const practiceUnlinkParents = useMemo((): PracticeParent[] => {
const mid = Number(moduleId); const mid = Number(moduleId);
if (!practiceToUnlink || !Number.isFinite(mid) || mid < 1) return []; if (!practiceToUnlink || !Number.isFinite(mid) || mid < 1) return [];
return listModuleContextUnlinkParents( return listModuleContextUnlinkParents(practiceToUnlink, mid);
practiceToUnlink, }, [moduleId, practiceToUnlink]);
mid,
moduleLessonIds,
);
}, [moduleId, moduleLessonIds, practiceToUnlink]);
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink || practiceUnlinkParents.length === 0) { if (!practiceToUnlink || practiceUnlinkParents.length === 0) {
toast.error("This practice is not linked to this module."); toast.error(
practiceToUnlink
? practiceUnlinkBlockedMessage(practiceToUnlink, moduleUnlinkContext) ??
"This practice is not linked to this module."
: "This practice is not linked to this module.",
);
return; return;
} }
setUnlinkingPractice(true); setUnlinkingPractice(true);
@ -752,11 +764,7 @@ export function ModuleDetailPage() {
practices={filteredPractices} practices={filteredPractices}
searchQuery={practiceSearch} searchQuery={practiceSearch}
locationLabel={displayModuleName} locationLabel={displayModuleName}
unlinkContext={{ unlinkContext={moduleUnlinkContext}
scope: "module",
moduleId: Number(moduleId),
lessonIds: moduleLessonIds,
}}
publishStatusUpdatingId={publishStatusPracticeId} publishStatusUpdatingId={publishStatusPracticeId}
onReload={loadModulePractices} onReload={loadModulePractices}
unlinkActionLabel="Remove from module" unlinkActionLabel="Remove from module"
@ -772,7 +780,17 @@ export function ModuleDetailPage() {
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
const mid = Number(moduleId);
if (!hasModuleDirectPracticeLink(practice, mid)) {
toast.info(
practiceUnlinkBlockedMessage(practice, moduleUnlinkContext) ??
"This practice is not directly linked to this module.",
);
return;
}
setPracticeToUnlink(practice);
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
) : ( ) : (

View File

@ -12,8 +12,10 @@ import { unwrapPracticesList } from "../../../lib/parentContextPractice"
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages" import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
import { parentsFromPractice } from "../../../lib/practiceParents" import { parentsFromPractice } from "../../../lib/practiceParents"
import { import {
hasCatalogCourseDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError, listCatalogCourseContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../../lib/practiceParentUnlink" } from "../../../lib/practiceParentUnlink"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
@ -32,7 +34,6 @@ import {
} from "../../../lib/contentListFilters" } from "../../../lib/contentListFilters"
import type { import type {
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../../types/course.types" } from "../../../types/course.types"
@ -149,20 +150,33 @@ export function CatalogCoursePracticesPanel({
} }
} }
const catalogParent = useMemo( const catalogUnlinkContext = useMemo(
(): PracticeParent => ({ parent_kind: "CATALOG_COURSE", parent_id: catalogCourseId }), () => ({ scope: "catalog_course" as const, catalogCourseId }),
[catalogCourseId], [catalogCourseId],
) )
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return if (!practiceToUnlink) return
const parents = listCatalogCourseContextUnlinkParents(
practiceToUnlink,
catalogCourseId,
)
if (parents.length === 0) {
toast.error(
practiceUnlinkBlockedMessage(practiceToUnlink, catalogUnlinkContext) ??
"This practice is not linked to this catalog course.",
)
return
}
setUnlinking(true) setUnlinking(true)
try { try {
await unlinkPracticeFromParent({ for (const parent of parents) {
practiceId: practiceToUnlink.id, await unlinkPracticeFromParent({
parent: catalogParent, practiceId: practiceToUnlink.id,
isExamPrep: true, parent,
}) isExamPrep: true,
})
}
toast.success(`Practice removed from ${courseName}`) toast.success(`Practice removed from ${courseName}`)
setPracticeToUnlink(null) setPracticeToUnlink(null)
await load() await load()
@ -253,7 +267,7 @@ export function CatalogCoursePracticesPanel({
practices={filteredPractices} practices={filteredPractices}
searchQuery={listSearch} searchQuery={listSearch}
locationLabel={courseName} locationLabel={courseName}
unlinkContext={{ scope: "catalog_course", catalogCourseId }} unlinkContext={catalogUnlinkContext}
isExamPrep isExamPrep
publishStatusUpdatingId={publishStatusUpdatingId} publishStatusUpdatingId={publishStatusUpdatingId}
onReload={load} onReload={load}
@ -266,7 +280,16 @@ export function CatalogCoursePracticesPanel({
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasCatalogCourseDirectPracticeLink(practice, catalogCourseId)) {
toast.info(
practiceUnlinkBlockedMessage(practice, catalogUnlinkContext) ??
"This practice is not directly linked to this catalog course.",
)
return
}
setPracticeToUnlink(practice)
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
)} )}

View File

@ -12,8 +12,10 @@ import { unwrapPracticesList } from "../../../lib/parentContextPractice"
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages" import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
import { parentsFromPractice } from "../../../lib/practiceParents" import { parentsFromPractice } from "../../../lib/practiceParents"
import { import {
hasUnitDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError, listUnitContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../../lib/practiceParentUnlink" } from "../../../lib/practiceParentUnlink"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
@ -32,7 +34,6 @@ import {
} from "../../../lib/contentListFilters" } from "../../../lib/contentListFilters"
import type { import type {
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../../types/course.types" } from "../../../types/course.types"
@ -148,20 +149,30 @@ export function UnitPracticesPanel({
} }
} }
const unitParent = useMemo( const unitUnlinkContext = useMemo(
(): PracticeParent => ({ parent_kind: "UNIT", parent_id: unitId }), () => ({ scope: "unit" as const, unitId }),
[unitId], [unitId],
) )
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return if (!practiceToUnlink) return
const parents = listUnitContextUnlinkParents(practiceToUnlink, unitId)
if (parents.length === 0) {
toast.error(
practiceUnlinkBlockedMessage(practiceToUnlink, unitUnlinkContext) ??
"This practice is not linked to this unit.",
)
return
}
setUnlinking(true) setUnlinking(true)
try { try {
await unlinkPracticeFromParent({ for (const parent of parents) {
practiceId: practiceToUnlink.id, await unlinkPracticeFromParent({
parent: unitParent, practiceId: practiceToUnlink.id,
isExamPrep: true, parent,
}) isExamPrep: true,
})
}
toast.success(`Practice removed from ${unitName}`) toast.success(`Practice removed from ${unitName}`)
setPracticeToUnlink(null) setPracticeToUnlink(null)
await load() await load()
@ -252,7 +263,7 @@ export function UnitPracticesPanel({
practices={filteredPractices} practices={filteredPractices}
searchQuery={listSearch} searchQuery={listSearch}
locationLabel={unitName} locationLabel={unitName}
unlinkContext={{ scope: "unit", unitId }} unlinkContext={unitUnlinkContext}
isExamPrep isExamPrep
publishStatusUpdatingId={publishStatusUpdatingId} publishStatusUpdatingId={publishStatusUpdatingId}
onReload={load} onReload={load}
@ -265,7 +276,16 @@ export function UnitPracticesPanel({
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasUnitDirectPracticeLink(practice, unitId)) {
toast.info(
practiceUnlinkBlockedMessage(practice, unitUnlinkContext) ??
"This practice is not directly linked to this unit.",
)
return
}
setPracticeToUnlink(practice)
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
)} )}

View File

@ -62,7 +62,6 @@ import { cn } from "../../../lib/utils"
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../../lib/csv-export" import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../../lib/csv-export"
import { activityLogExportQuery } from "../../../lib/csvExportFilters" import { activityLogExportQuery } from "../../../lib/csvExportFilters"
import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination" import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination"
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types" import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types"
import { ActorCell, ActorLabel } from "./ActorLabel" import { ActorCell, ActorLabel } from "./ActorLabel"
import { ActorHoverCard } from "./ActorHoverCard" import { ActorHoverCard } from "./ActorHoverCard"
@ -96,6 +95,7 @@ export function ActivityLogListPanel({
scrollable = false, scrollable = false,
}: ActivityLogListPanelProps) { }: ActivityLogListPanelProps) {
const [logs, setLogs] = useState<ActivityLog[]>([]) const [logs, setLogs] = useState<ActivityLog[]>([])
const [totalCount, setTotalCount] = useState(0)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
@ -105,6 +105,7 @@ export function ActivityLogListPanel({
const [resourceTypeFilter, setResourceTypeFilter] = useState("") const [resourceTypeFilter, setResourceTypeFilter] = useState("")
const [resourceIdFilter, setResourceIdFilter] = useState("") const [resourceIdFilter, setResourceIdFilter] = useState("")
const [searchQuery, setSearchQuery] = useState("") const [searchQuery, setSearchQuery] = useState("")
const [debouncedSearch, setDebouncedSearch] = useState("")
const [dateAfter, setDateAfter] = useState("") const [dateAfter, setDateAfter] = useState("")
const [dateBefore, setDateBefore] = useState("") const [dateBefore, setDateBefore] = useState("")
@ -123,6 +124,7 @@ export function ActivityLogListPanel({
} }
if (dateAfter) filters.after = toRfc3339StartOfDay(dateAfter) if (dateAfter) filters.after = toRfc3339StartOfDay(dateAfter)
if (dateBefore) filters.before = toRfc3339EndOfDay(dateBefore) if (dateBefore) filters.before = toRfc3339EndOfDay(dateBefore)
if (debouncedSearch) filters.search = debouncedSearch
return filters return filters
}, [ }, [
fixedActorId, fixedActorId,
@ -131,6 +133,7 @@ export function ActivityLogListPanel({
resourceIdFilter, resourceIdFilter,
dateAfter, dateAfter,
dateBefore, dateBefore,
debouncedSearch,
]) ])
const exportParams = useMemo( const exportParams = useMemo(
@ -142,21 +145,32 @@ export function ActivityLogListPanel({
setLoading(true) setLoading(true)
setError(null) setError(null)
try { try {
const all = await fetchAllOffsetPages(async (offset, limit) => { const offset = (page - 1) * pageSize
const data = await getActivityLogs({ ...listFilters, limit, offset }) const data = await getActivityLogs({
return { items: data.logs, total_count: data.total_count } ...listFilters,
limit: pageSize,
offset,
}) })
setLogs(all) setLogs(data.logs)
setTotalCount(data.total_count)
} catch (e) { } catch (e) {
console.error("Failed to fetch activity logs:", e) console.error("Failed to fetch activity logs:", e)
setLogs([]) setLogs([])
setTotalCount(0)
const msg = getApiErrorMessage(e, "Failed to load activity logs") const msg = getApiErrorMessage(e, "Failed to load activity logs")
setError(msg) setError(msg)
notifyApiError(e, "Failed to load activity logs") notifyApiError(e, "Failed to load activity logs")
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, [listFilters]) }, [listFilters, page, pageSize])
useEffect(() => {
const timer = window.setTimeout(() => {
setDebouncedSearch(searchQuery.trim())
}, 300)
return () => window.clearTimeout(timer)
}, [searchQuery])
useEffect(() => { useEffect(() => {
void fetchLogs() void fetchLogs()
@ -164,7 +178,16 @@ export function ActivityLogListPanel({
useEffect(() => { useEffect(() => {
setPage(1) setPage(1)
}, [actionFilter, resourceTypeFilter, resourceIdFilter, dateAfter, dateBefore, fixedActorId, pageSize, searchQuery]) }, [
actionFilter,
resourceTypeFilter,
resourceIdFilter,
dateAfter,
dateBefore,
fixedActorId,
pageSize,
debouncedSearch,
])
const handleViewDetail = async (logId: number) => { const handleViewDetail = async (logId: number) => {
setDialogOpen(true) setDialogOpen(true)
@ -202,36 +225,11 @@ export function ActivityLogListPanel({
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim()) const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim())
const filteredLogs = useMemo(() => {
const q = searchQuery.trim().toLowerCase()
if (!q) return logs
return logs.filter((log) => {
const haystack = [
log.message,
log.action,
log.actor_name,
log.actor_email,
log.actor_role,
log.resource_type,
log.resource_id != null ? String(log.resource_id) : "",
JSON.stringify(log.metadata ?? {}),
]
.filter(Boolean)
.join(" ")
.toLowerCase()
return haystack.includes(q)
})
}, [logs, searchQuery])
const totalCount = filteredLogs.length
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)) const pageCount = Math.max(1, Math.ceil(totalCount / pageSize))
const safePage = Math.min(page, pageCount) const safePage = Math.min(page, pageCount)
const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
const endEntry = Math.min(safePage * pageSize, totalCount) const endEntry = Math.min(safePage * pageSize, totalCount)
const paginatedLogs = useMemo(() => { const paginatedLogs = logs
const start = (safePage - 1) * pageSize
return filteredLogs.slice(start, start + pageSize)
}, [filteredLogs, safePage, pageSize])
const showActorColumn = fixedActorId == null const showActorColumn = fixedActorId == null
const columnCount = showActorColumn ? 6 : 5 const columnCount = showActorColumn ? 6 : 5
@ -287,7 +285,7 @@ export function ActivityLogListPanel({
<p className="text-2xl font-bold text-grayScale-600"> <p className="text-2xl font-bold text-grayScale-600">
{logs[0]?.created_at ? getRelativeActivityTime(logs[0].created_at) : <UnassignedLabel />} {logs[0]?.created_at ? getRelativeActivityTime(logs[0].created_at) : <UnassignedLabel />}
</p> </p>
<p className="text-xs text-grayScale-400">Latest loaded</p> <p className="text-xs text-grayScale-400">Latest on this page</p>
</div> </div>
</div> </div>
<div className="flex items-center gap-4 rounded-xl border bg-white p-4"> <div className="flex items-center gap-4 rounded-xl border bg-white p-4">
@ -295,8 +293,8 @@ export function ActivityLogListPanel({
<FileText className="h-5 w-5" /> <FileText className="h-5 w-5" />
</div> </div>
<div> <div>
<p className="text-2xl font-bold text-grayScale-600">{filteredLogs.length}</p> <p className="text-2xl font-bold text-grayScale-600">{paginatedLogs.length}</p>
<p className="text-xs text-grayScale-400">Rows after search</p> <p className="text-xs text-grayScale-400">Rows on this page</p>
</div> </div>
</div> </div>
</div> </div>

View File

@ -47,6 +47,7 @@ export interface ActivityLogFilters {
resource_id?: number resource_id?: number
after?: string after?: string
before?: string before?: string
search?: string
limit?: number limit?: number
offset?: number offset?: number
} }