From ad75a0628486d8f5a4b71d6e698393d26546afa2 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 19 Jun 2026 02:40:37 -0700 Subject: [PATCH] Add attach-practice flow, nullable parents, and practice UX improvements. Support linking existing practices from course/module/lesson pages with client-side search, a full-page attach wizard, and titled parent summaries on review. Extend practice creation for question-type shells, multi-parent APIs, and layout fixes across admin flows. Co-authored-by: Cursor --- src/api/courses.api.ts | 14 + src/api/questionTypeDefinitions.api.ts | 173 ++++++++ src/app/AppRoutes.tsx | 21 + src/components/SearchHighlight.tsx | 67 +++ src/components/topbar/Topbar.tsx | 2 +- src/hooks/usePracticeParentTitles.ts | 51 +++ src/index.css | 1 + src/layouts/AppLayout.tsx | 2 +- src/lib/attachPracticeToParent.ts | 32 ++ src/lib/fetchAllPractices.ts | 34 ++ src/lib/learnEnglishDefinitionQuestion.ts | 4 + src/lib/learnEnglishPracticeEditPath.ts | 350 ++++++++++++++++ src/lib/parentContextPractice.ts | 39 +- src/lib/practiceContentPaths.ts | 114 ++++++ src/lib/practiceCreationOrchestrator.ts | 61 ++- src/lib/practiceEditOrchestrator.ts | 13 +- src/lib/practiceFullMapper.ts | 76 +++- src/lib/practiceParentTitles.ts | 251 ++++++++++++ src/lib/practiceParents.ts | 131 ++++++ src/lib/questionAssociations.ts | 170 ++++++++ src/pages/auth/AcceptInvitePage.tsx | 2 +- src/pages/auth/ForgotPasswordPage.tsx | 2 +- src/pages/auth/LoginPage.tsx | 2 +- src/pages/auth/VerificationPage.tsx | 2 +- .../content-management/AddPracticeFlow.tsx | 144 ++++++- .../content-management/CourseDetailPage.tsx | 33 +- .../CourseModuleDetailPage.tsx | 68 ++- .../content-management/EditPracticeFlow.tsx | 40 +- .../LessonPracticesPage.tsx | 44 +- .../LinkExistingPracticeFlow.tsx | 309 ++++++++++++++ .../content-management/ModuleDetailPage.tsx | 73 +++- .../PracticeDetailsPage.tsx | 6 +- .../content-management/ProgramDetailPage.tsx | 9 +- .../QuestionTypeLibraryPage.tsx | 14 + .../components/CreatePracticeWizard.tsx | 3 +- .../components/PracticeActionButton.tsx | 40 ++ .../components/PracticeActionChoiceDialog.tsx | 117 ++++++ .../components/QuestionTypeCard.tsx | 32 +- .../QuestionTypeDefinitionPracticesDialog.tsx | 304 ++++++++++++++ .../components/practice-steps/ContextStep.tsx | 86 +++- .../LinkExistingPracticeReviewStep.tsx | 196 +++++++++ .../practice-steps/PracticeParentsField.tsx | 132 ++++++ .../PracticeSequentialReview.tsx | 23 +- .../QuestionAssociationField.tsx | 111 +++++ .../practice-steps/QuestionsStep.tsx | 87 +++- .../components/practice-steps/ReviewStep.tsx | 5 +- .../SelectPracticeToAttachStep.tsx | 386 ++++++++++++++++++ .../mapQuestionsForPracticeReview.ts | 73 +++- src/pages/legal/InfoLayout.tsx | 2 +- src/types/course.types.ts | 54 ++- src/types/questionTypeDefinition.types.ts | 40 ++ 51 files changed, 3909 insertions(+), 136 deletions(-) create mode 100644 src/components/SearchHighlight.tsx create mode 100644 src/hooks/usePracticeParentTitles.ts create mode 100644 src/lib/attachPracticeToParent.ts create mode 100644 src/lib/fetchAllPractices.ts create mode 100644 src/lib/learnEnglishPracticeEditPath.ts create mode 100644 src/lib/practiceContentPaths.ts create mode 100644 src/lib/practiceParentTitles.ts create mode 100644 src/lib/practiceParents.ts create mode 100644 src/lib/questionAssociations.ts create mode 100644 src/pages/content-management/LinkExistingPracticeFlow.tsx create mode 100644 src/pages/content-management/components/PracticeActionButton.tsx create mode 100644 src/pages/content-management/components/PracticeActionChoiceDialog.tsx create mode 100644 src/pages/content-management/components/QuestionTypeDefinitionPracticesDialog.tsx create mode 100644 src/pages/content-management/components/practice-steps/LinkExistingPracticeReviewStep.tsx create mode 100644 src/pages/content-management/components/practice-steps/PracticeParentsField.tsx create mode 100644 src/pages/content-management/components/practice-steps/QuestionAssociationField.tsx create mode 100644 src/pages/content-management/components/practice-steps/SelectPracticeToAttachStep.tsx diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index 9fa1620..adcf783 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -105,6 +105,8 @@ import type { GetExamPrepModuleLessonsResponse, GetTopLevelModuleLessonsResponse, GetPracticesByParentContextResponse, + GetPracticesListParams, + GetPracticesListResponse, CreateParentLinkedPracticeRequest, CreateParentLinkedPracticeResponse, UpdateParentLinkedPracticeRequest, @@ -112,6 +114,8 @@ import type { UpdatePracticeFullRequest, UpdatePracticeFullResponse, UpdateParentLinkedPracticeResponse, + UpdatePracticeParentsRequest, + UpdatePracticeParentsResponse, PublishParentLinkedPracticeRequest, PublishStatusOnlyRequest, AccessTierOnlyRequest, @@ -839,10 +843,20 @@ export const getPracticesByParentLesson = ( ) => http.get(`/lessons/${lessonId}/practices`, { params }) +/** GET /practices — list all practices (for attach-existing flow). */ +export const getPractices = (params?: GetPracticesListParams) => + http.get("/practices", { params }) + /** POST /practices — create a practice (story + question set) for course / module / lesson. */ export const createParentLinkedPractice = (data: CreateParentLinkedPracticeRequest) => http.post("/practices", data) +/** PUT /practices/:id/parents — replace all parent links on a practice. */ +export const updatePracticeParents = ( + practiceId: number, + data: UpdatePracticeParentsRequest, +) => http.put(`/practices/${practiceId}/parents`, data) + /** PUT /practices/:id */ export const updateParentLinkedPractice = ( practiceId: number, diff --git a/src/api/questionTypeDefinitions.api.ts b/src/api/questionTypeDefinitions.api.ts index b596952..5b29c23 100644 --- a/src/api/questionTypeDefinitions.api.ts +++ b/src/api/questionTypeDefinitions.api.ts @@ -4,10 +4,14 @@ import type { QuestionComponentCatalog, QuestionTypeDefinition, QuestionTypeDefinitionCreatePayload, + QuestionTypeDefinitionPractice, + QuestionTypeDefinitionPracticesParams, + QuestionTypeDefinitionPracticesResult, QuestionTypeDefinitionUpdatePayload, QuestionTypeDefinitionValidatePayload, ValidateQuestionTypeDefinitionResult, } from "../types/questionTypeDefinition.types" +import { normalizePracticeParents, parentsFromPractice } from "../lib/practiceParents" interface ApiEnvelope { message?: string @@ -408,3 +412,172 @@ export async function updateQuestionTypeDefinition( export async function deleteQuestionTypeDefinition(id: number) { return http.delete>(`/questions/type-definitions/${id}`) } + +function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice | null { + if (!row || typeof row !== "object") return null + const o = row as Record + const practice_id = Number(o.practice_id ?? o.PracticeId ?? o.practiceId ?? o.id ?? o.ID) + const question_set_id = Number(o.question_set_id ?? o.QuestionSetId ?? o.questionSetId) + if (!Number.isFinite(practice_id) || practice_id <= 0) return null + if (!Number.isFinite(question_set_id) || question_set_id <= 0) return null + + const matching_question_count = Number( + o.matching_question_count ?? o.MatchingQuestionCount ?? o.matchingQuestionCount ?? 0, + ) + const parentObj = + o.parent != null && typeof o.parent === "object" && !Array.isArray(o.parent) + ? (o.parent as Record) + : o.Parent != null && typeof o.Parent === "object" && !Array.isArray(o.Parent) + ? (o.Parent as Record) + : null + + const parent_idRaw = + o.parent_id ?? + o.ParentId ?? + o.parentId ?? + parentObj?.id ?? + parentObj?.Id ?? + parentObj?.ID + const parent_id = + parent_idRaw != null && Number.isFinite(Number(parent_idRaw)) ? Number(parent_idRaw) : undefined + + const parent_kind = + asStr(o.parent_kind ?? o.ParentKind ?? o.parentKind) || + (parentObj ? asStr(parentObj.kind ?? parentObj.Kind) : "") || + undefined + + const program_id = Number(o.program_id ?? o.ProgramId ?? o.programId) + const course_id = Number(o.course_id ?? o.CourseId ?? o.courseId) + const module_id = Number(o.module_id ?? o.ModuleId ?? o.moduleId) + const lesson_id = Number(o.lesson_id ?? o.LessonId ?? o.lessonId) + const parents = parentsFromPractice({ + parents: normalizePracticeParents(row), + parent_kind, + parent_id, + }) + + return { + practice_kind: asStr(o.practice_kind ?? o.PracticeKind ?? o.practiceKind ?? "LMS"), + practice_id, + question_set_id, + title: asStr(o.title ?? o.Title) || `Practice #${practice_id}`, + story_description: + o.story_description != null + ? asStr(o.story_description) + : o.StoryDescription != null + ? asStr(o.StoryDescription) + : undefined, + story_image: + o.story_image != null + ? asStr(o.story_image) + : o.StoryImage != null + ? asStr(o.StoryImage) + : undefined, + quick_tips: + o.quick_tips != null + ? asStr(o.quick_tips) + : o.QuickTips != null + ? asStr(o.QuickTips) + : undefined, + publish_status: asStr(o.publish_status ?? o.PublishStatus ?? o.publishStatus) || undefined, + parents, + parent_kind: parents[0]?.parent_kind, + parent_id: parents[0]?.parent_id, + program_id: Number.isFinite(program_id) && program_id > 0 ? program_id : undefined, + course_id: Number.isFinite(course_id) && course_id > 0 ? course_id : undefined, + module_id: Number.isFinite(module_id) && module_id > 0 ? module_id : undefined, + lesson_id: Number.isFinite(lesson_id) && lesson_id > 0 ? lesson_id : undefined, + matching_question_count: Number.isFinite(matching_question_count) ? matching_question_count : 0, + created_at: + o.created_at != null + ? asStr(o.created_at) + : o.CreatedAt != null + ? asStr(o.CreatedAt) + : undefined, + updated_at: + o.updated_at != null + ? asStr(o.updated_at) + : o.UpdatedAt != null + ? asStr(o.UpdatedAt) + : undefined, + } +} + +function parsePracticesList(payload: unknown): QuestionTypeDefinitionPractice[] { + if (!payload) return [] + if (Array.isArray(payload)) { + return payload + .map((item) => normalizePracticeFromApi(item)) + .filter((x): x is QuestionTypeDefinitionPractice => x != null) + } + if (typeof payload === "object" && payload !== null) { + const o = payload as Record + const inner = o.practices ?? o.Practices + if (Array.isArray(inner)) return parsePracticesList(inner) + const data = o.data ?? o.Data + if (data && typeof data === "object") return parsePracticesList(data) + } + return [] +} + +function parsePracticesPage( + payload: unknown, + definitionId: number, + params?: QuestionTypeDefinitionPracticesParams, +): QuestionTypeDefinitionPracticesResult { + const practices = parsePracticesList(payload) + const limit = params?.limit ?? 20 + const offset = params?.offset ?? 0 + + if (!payload || typeof payload !== "object" || Array.isArray(payload)) { + return { + question_type_definition_id: definitionId, + practices, + total_count: practices.length, + limit, + offset, + } + } + + const o = payload as Record + const data = + o.data != null && typeof o.data === "object" && !Array.isArray(o.data) + ? (o.data as Record) + : o + + const question_type_definition_id = Number( + data.question_type_definition_id ?? + data.QuestionTypeDefinitionId ?? + data.questionTypeDefinitionId ?? + definitionId, + ) + const total_count = parseListTotalCount(data) ?? parseListTotalCount(payload) ?? practices.length + const parsedLimit = Number(data.limit ?? data.Limit ?? limit) + const parsedOffset = Number(data.offset ?? data.Offset ?? offset) + + return { + question_type_definition_id: + Number.isFinite(question_type_definition_id) && question_type_definition_id > 0 + ? question_type_definition_id + : definitionId, + practices, + total_count, + limit: Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : limit, + offset: Number.isFinite(parsedOffset) && parsedOffset >= 0 ? parsedOffset : offset, + } +} + +/** + * GET /questions/type-definitions/:id/practices + * Lists LMS practices that contain questions using this definition. + */ +export async function getQuestionTypeDefinitionPractices( + definitionId: number, + params?: QuestionTypeDefinitionPracticesParams, +): Promise { + const res = await http.get>(`/questions/type-definitions/${definitionId}/practices`, { + params, + }) + const raw = unwrapApiPayload(res) ?? res.data + return parsePracticesPage(raw, definitionId, params) +} diff --git a/src/app/AppRoutes.tsx b/src/app/AppRoutes.tsx index ba80b5b..a5a122a 100644 --- a/src/app/AppRoutes.tsx +++ b/src/app/AppRoutes.tsx @@ -23,6 +23,7 @@ import { LessonPracticesPage } from "../pages/content-management/LessonPractices import { ModuleDetailPage } from "../pages/content-management/ModuleDetailPage"; import { AddVideoFlow } from "../pages/content-management/AddVideoFlow"; import { AddPracticeFlow } from "../pages/content-management/AddPracticeFlow"; +import { LinkExistingPracticeFlow } from "../pages/content-management/LinkExistingPracticeFlow"; import { EditPracticeFlow } from "../pages/content-management/EditPracticeFlow"; import { CourseModuleDetailPage } from "../pages/content-management/CourseModuleDetailPage"; import { ProgramTypeSelectionPage } from "../pages/content-management/ProgramTypeSelectionPage"; @@ -182,6 +183,10 @@ export function AppRoutes() { path="/new-content/question-types" element={} /> + } + /> } @@ -198,14 +203,26 @@ export function AppRoutes() { path="/new-content/courses/:programType/add-practice" element={} /> + } + /> } /> + } + /> } /> + } + /> } @@ -266,6 +283,10 @@ export function AppRoutes() { path="/new-content/learn-english/:level/courses/add-practice" element={} /> + } + /> } /> b.length - a.length) + .map(escapeRegExp) + .join("|") + const regex = new RegExp(`(${pattern})`, "gi") + const parts = text.split(regex).filter((part) => part.length > 0) + if (parts.length <= 1) return [{ text, match: false }] + + const lowerTokens = new Set(tokens.map((token) => token.toLowerCase())) + return parts.map((part) => ({ + text: part, + match: lowerTokens.has(part.toLowerCase()), + })) +} + +interface SearchHighlightProps { + text: string + query: string + className?: string + highlightClassName?: string +} + +export function SearchHighlight({ + text, + query, + className, + highlightClassName = "rounded-sm bg-amber-200/90 px-0.5 font-inherit text-inherit", +}: SearchHighlightProps) { + const segments = useMemo( + () => segmentByTokens(text, getSearchTokens(query)), + [text, query], + ) + + if (!query.trim()) { + return {text} + } + + return ( + + {segments.map((segment, index) => + segment.match ? ( + + {segment.text} + + ) : ( + {segment.text} + ), + )} + + ) +} diff --git a/src/components/topbar/Topbar.tsx b/src/components/topbar/Topbar.tsx index 8a3fb58..460138b 100644 --- a/src/components/topbar/Topbar.tsx +++ b/src/components/topbar/Topbar.tsx @@ -45,7 +45,7 @@ export function Topbar({ onSidebarToggle }: TopbarProps) { } return ( -
+
{/* Sidebar toggle */} + + ) : null} )} diff --git a/src/pages/content-management/CourseModuleDetailPage.tsx b/src/pages/content-management/CourseModuleDetailPage.tsx index 2dd1422..8a8d4d5 100644 --- a/src/pages/content-management/CourseModuleDetailPage.tsx +++ b/src/pages/content-management/CourseModuleDetailPage.tsx @@ -2,6 +2,12 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ArrowLeft, Plus, FileText, Video } from "lucide-react"; import { Link, useNavigate, useParams } from "react-router-dom"; import { Button } from "../../components/ui/button"; +import { PracticeActionButton } from "./components/PracticeActionButton"; +import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog"; +import { + buildPracticeContentPaths, + type PracticeContentPathOptions, +} from "../../lib/practiceContentPaths"; import { cn } from "../../lib/utils"; import { Card } from "../../components/ui/card"; import { @@ -78,6 +84,25 @@ export function CourseModuleDetailPage() { const parsedUnitId = Number(unitId); const [activeTab, setActiveTab] = useState<"video" | "practice">("video"); + const [lessonPracticeChoice, setLessonPracticeChoice] = + useState(null); + const lessonPracticeChoicePaths = useMemo( + () => + lessonPracticeChoice + ? buildPracticeContentPaths(lessonPracticeChoice) + : null, + [lessonPracticeChoice], + ); + const modulePracticePathOptions = useMemo( + (): PracticeContentPathOptions => ({ + isExamPrep: true, + programType, + courseId, + unitId, + moduleId, + }), + [programType, courseId, unitId, moduleId], + ); const [moduleTitle, setModuleTitle] = useState("Module"); const [moduleDescription, setModuleDescription] = useState("—"); const [modulePublishStatus, setModulePublishStatus] = useState< @@ -631,9 +656,6 @@ export function CourseModuleDetailPage() { } }; - const lessonAttachPracticePath = (lesson: (typeof lessons)[number]) => - `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/add-practice?lessonId=${lesson.id}&lessonTitle=${encodeURIComponent(lesson.title)}`; - const lessonPracticesPath = (lesson: (typeof lessons)[number]) => `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/lessons/${lesson.id}/practices?lessonTitle=${encodeURIComponent(lesson.title)}`; @@ -668,18 +690,15 @@ export function CourseModuleDetailPage() {
- + { @@ -947,7 +966,17 @@ export function CourseModuleDetailPage() { onEdit={() => openEditLesson(lesson)} onDelete={() => setDeletingLessonId(lesson.id)} description={lesson.description} - onAddPractice={() => navigate(lessonAttachPracticePath(lesson))} + onAddPractice={() => + setLessonPracticeChoice({ + isExamPrep: true, + programType, + courseId, + unitId, + moduleId, + lessonId: String(lesson.id), + lessonTitle: lesson.title, + }) + } onViewPractices={() => navigate(lessonPracticesPath(lesson))} onTogglePublishStatus={(nextStatus) => void handleToggleLessonPublishStatus(lesson.id, nextStatus) @@ -1197,6 +1226,23 @@ export function CourseModuleDetailPage() {
+ + {lessonPracticeChoice && lessonPracticeChoicePaths ? ( + { + if (!open) setLessonPracticeChoice(null) + }} + createHref={lessonPracticeChoicePaths.create} + attachHref={lessonPracticeChoicePaths.attach} + pathOptions={lessonPracticeChoice} + parentLabel={ + lessonPracticeChoice.lessonTitle + ? `Lesson — ${lessonPracticeChoice.lessonTitle}` + : null + } + /> + ) : null} ); } diff --git a/src/pages/content-management/EditPracticeFlow.tsx b/src/pages/content-management/EditPracticeFlow.tsx index 3e0f87d..9d36782 100644 --- a/src/pages/content-management/EditPracticeFlow.tsx +++ b/src/pages/content-management/EditPracticeFlow.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { Link, useNavigate, @@ -21,6 +21,13 @@ import { validateLearnEnglishQuestionsWithDefinitions, } from "../../lib/learnEnglishPracticePublish"; import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator"; +import { + dedupeParents, + formatPracticeParentsSummary, + practiceParentsEqual, + validatePracticeParents, +} from "../../lib/practiceParents"; +import type { PracticeParent } from "../../types/course.types"; import { mapPracticeFullToFormState, unwrapPracticeFullData, @@ -223,6 +230,7 @@ export function EditPracticeFlow() { storyImageUrl: "", shuffleQuestions: false, tips: "", + parents: [] as PracticeParent[], questions: [ { id: "q1", @@ -250,6 +258,7 @@ export function EditPracticeFlow() { ); const [definitionsLoading, setDefinitionsLoading] = useState(true); const [definitionsError, setDefinitionsError] = useState(null); + const initialParentsRef = useRef([]); useEffect(() => { let cancelled = false; @@ -292,6 +301,7 @@ export function EditPracticeFlow() { if (cancelled) return; setFormData(mapped.formData); setPreservedQuestionSet(mapped.preservedQuestionSet); + initialParentsRef.current = mapped.parents; if (mapped.personaId != null) { setSelectedPersona(String(mapped.personaId)); } @@ -337,6 +347,7 @@ export function EditPracticeFlow() { } const mappedQuestions = formData.questions.map((q, index) => ({ + clientRowId: q.id, questionText: String(q.text ?? "").trim(), questionTypeDefinitionId: Number(q.questionTypeDefinitionId), difficultyLevel: (q.difficultyLevel ?? "EASY") as "EASY" | "MEDIUM" | "HARD", @@ -346,6 +357,8 @@ export function EditPracticeFlow() { ? Number(q.displayOrder) : index + 1, serverQuestionId: q.serverQuestionId ?? null, + associatedQuestionId: q.associatedQuestionId ?? null, + associatedAnchorRowId: q.associatedAnchorRowId ?? null, dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) }, mcqOptions: (q.mcqOptions ?? []).map( (o: { text?: string; isCorrect?: boolean }) => ({ @@ -370,6 +383,14 @@ export function EditPracticeFlow() { lessonTitleDisplay?.trim() || (lessonId ? `Lesson ${lessonId} practice` : "Lesson practice"); + if (!isExamPrep) { + const parentsErr = validatePracticeParents(formData.parents); + if (parentsErr) { + toast.error("Check practice locations", { description: parentsErr }); + return; + } + } + setSubmitting(true); try { await executePracticeUpdate({ @@ -386,10 +407,17 @@ export function EditPracticeFlow() { definitions: typeDefinitions, isLearnEnglishLessonPractice, lessonDefaultTitle, + parents: dedupeParents(formData.parents), + parentsChanged: + !isExamPrep && + !practiceParentsEqual(formData.parents, initialParentsRef.current), }); toast.success( status === "PUBLISHED" ? "Practice updated and published" : "Practice saved as draft", ); + if (!isExamPrep) { + initialParentsRef.current = dedupeParents(formData.parents); + } setIsSaved(true); } catch (e) { toast.error("Could not update practice", { @@ -466,6 +494,11 @@ export function EditPracticeFlow() { ); } + const reviewParentSummary = + formData.parents.length > 0 + ? formatPracticeParentsSummary(formData.parents) + : parentSummary; + const renderStep = () => { const useContextStep = isModuleContext || isCourseContext || isLessonContext; @@ -481,7 +514,8 @@ export function EditPracticeFlow() { onCancel={() => navigate(backPath)} isLessonPractice={isLearnEnglishLessonPractice} lessonTitle={lessonTitleDisplay} - parentSummary={parentSummary} + parentSummary={reviewParentSummary} + showParentsEditor={!isExamPrep} /> ); case 2: @@ -523,7 +557,7 @@ export function EditPracticeFlow() { prevStep={prevStep} onEditContext={() => setCurrentStep(1)} onEditQuestions={() => setCurrentStep(3)} - parentSummary={parentSummary} + parentSummary={reviewParentSummary} typeDefinitions={typeDefinitions} canPublish submitting={submitting} diff --git a/src/pages/content-management/LessonPracticesPage.tsx b/src/pages/content-management/LessonPracticesPage.tsx index b173ea6..494ff57 100644 --- a/src/pages/content-management/LessonPracticesPage.tsx +++ b/src/pages/content-management/LessonPracticesPage.tsx @@ -23,6 +23,7 @@ import { } from "../../api/courses.api"; import { Badge } from "../../components/ui/badge"; import { Button } from "../../components/ui/button"; +import { PracticeActionButton } from "./components/PracticeActionButton"; import { Card, CardContent } from "../../components/ui/card"; import { Dialog, @@ -68,6 +69,7 @@ function mapExamPrepPracticeToCard( ): ParentContextPractice { return { id: practice.id, + parents: [{ parent_kind: "LESSON", parent_id: practice.lesson_id }], parent_kind: "LESSON", parent_id: practice.lesson_id, title: practice.title, @@ -332,9 +334,31 @@ export function LessonPracticesPage() { const displayTitle = lessonTitle || (validLesson ? `Lesson #${lid}` : "Lesson practices"); - const addPracticeHref = isExamPrep - ? `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/add-practice?lessonId=${lid}&lessonTitle=${encodeURIComponent(lessonTitle || displayTitle)}` - : `/new-content/learn-english/${level}/courses/add-practice?backTo=module&courseId=${courseId}&moduleId=${moduleId}&lessonId=${lid}&lessonTitle=${encodeURIComponent(lessonTitle || displayTitle)}`; + const practicePathOptions = useMemo( + () => ({ + isExamPrep, + level, + programType, + courseId, + unitId, + moduleId, + lessonId: validLesson ? String(lid) : null, + lessonTitle: lessonTitle || displayTitle, + backTo: isExamPrep ? "lesson" : "module", + }), + [ + isExamPrep, + level, + programType, + courseId, + unitId, + moduleId, + validLesson, + lid, + lessonTitle, + displayTitle, + ], + ); const editPracticeHref = (practiceId: number) => { const titleQuery = lessonTitle @@ -449,14 +473,15 @@ export function LessonPracticesPage() {
- + + +
+ + ) + } + + const submitAttach = async () => { + if (!selectedPractice) return + setSubmitting(true) + try { + await attachPracticeToParent(selectedPractice, targetParent) + toast.success("Practice linked successfully") + setIsComplete(true) + } catch (e) { + toast.error("Could not link practice", { + description: learnEnglishPracticeApiErrorMessage(e), + }) + } finally { + setSubmitting(false) + } + } + + if (isComplete) { + return ( +
+
+
+ +
+

+ Practice linked successfully +

+

+ + {selectedPractice?.title?.trim() || `Practice #${selectedPractice?.id}`} + {" "} + is now attached to {targetSummary}. +

+ +
+ ) + } + + return ( +
+
+
+ + + {backLabel} + +
+ +
+
+

Attach Existing Practice

+ +
+

+ Browse your practice library and link an existing practice to this content location. +

+
+
+
+ +
+
+

Attach to

+

+ {targetSummary} +

+
+
+
+
+ +
+ +
+ +
+ {currentStep === 1 ? ( + setCurrentStep(2)} + onCancel={() => navigate(backPath)} + /> + ) : selectedPractice ? ( + setCurrentStep(1)} + onConfirm={() => void submitAttach()} + /> + ) : null} +
+
+
+ ) +} diff --git a/src/pages/content-management/ModuleDetailPage.tsx b/src/pages/content-management/ModuleDetailPage.tsx index a6c5671..b3d3377 100644 --- a/src/pages/content-management/ModuleDetailPage.tsx +++ b/src/pages/content-management/ModuleDetailPage.tsx @@ -20,6 +20,9 @@ import type { } from "../../types/course.types"; import { unwrapPracticesList } from "../../lib/parentContextPractice"; import { Button } from "../../components/ui/button"; +import { PracticeActionButton } from "./components/PracticeActionButton"; +import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog"; +import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../lib/practiceContentPaths"; import { Dialog, DialogContent, @@ -70,6 +73,25 @@ export function ModuleDetailPage() { const [practiceSearch, setPracticeSearch] = useState(""); const [practicePublishStatusFilter, setPracticePublishStatusFilter] = useState("all"); + const [lessonPracticeChoice, setLessonPracticeChoice] = + useState(null); + const lessonPracticeChoicePaths = useMemo( + () => + lessonPracticeChoice + ? buildPracticeContentPaths(lessonPracticeChoice) + : null, + [lessonPracticeChoice], + ); + const modulePracticePathOptions = useMemo( + (): PracticeContentPathOptions => ({ + isExamPrep: false, + level, + courseId, + moduleId, + backTo: "module", + }), + [level, courseId, moduleId], + ); const [lessons, setLessons] = useState([]); const [lessonsLoading, setLessonsLoading] = useState(true); const [lessonsLoadError, setLessonsLoadError] = useState(null); @@ -472,18 +494,15 @@ export function ModuleDetailPage() {
- + + ) : null}
)} @@ -865,6 +887,23 @@ export function ModuleDetailPage() { )} + + {lessonPracticeChoice && lessonPracticeChoicePaths ? ( + { + if (!open) setLessonPracticeChoice(null) + }} + createHref={lessonPracticeChoicePaths.create} + attachHref={lessonPracticeChoicePaths.attach} + pathOptions={lessonPracticeChoice} + parentLabel={ + lessonPracticeChoice.lessonTitle + ? `Lesson — ${lessonPracticeChoice.lessonTitle}` + : null + } + /> + ) : null} ); } diff --git a/src/pages/content-management/PracticeDetailsPage.tsx b/src/pages/content-management/PracticeDetailsPage.tsx index 78ea6fa..dbcc8e3 100644 --- a/src/pages/content-management/PracticeDetailsPage.tsx +++ b/src/pages/content-management/PracticeDetailsPage.tsx @@ -26,6 +26,7 @@ import { } from "../../components/ui/dialog" import { Input } from "../../components/ui/input" import { Textarea } from "../../components/ui/textarea" +import { formatPracticeParentsSummary, parentsFromPractice } from "../../lib/practiceParents" import type { LearningProgramListItem, ParentContextPractice, @@ -598,6 +599,7 @@ export function PracticeDetailsPage() { ...practice, ...payload, id: practice.id, + parents: parentsFromPractice({ ...practice, ...payload }), parent_kind: practice.parent_kind, parent_id: practice.parent_id, created_at: practice.created_at, @@ -952,10 +954,10 @@ export function PracticeDetailsPage() {
- {practice.parent_kind} + {formatPracticeParentsSummary(parentsFromPractice(practice))} - parent #{practice.parent_id} · practice #{practice.id} + practice #{practice.id}
{flowMode === "view" && ( diff --git a/src/pages/content-management/ProgramDetailPage.tsx b/src/pages/content-management/ProgramDetailPage.tsx index 9b33ddd..1787bb7 100644 --- a/src/pages/content-management/ProgramDetailPage.tsx +++ b/src/pages/content-management/ProgramDetailPage.tsx @@ -12,6 +12,7 @@ import { X, } from "lucide-react"; import { Button } from "../../components/ui/button"; +import { PracticeActionButton } from "./components/PracticeActionButton"; import { Card } from "../../components/ui/card"; import { Dialog, @@ -648,16 +649,14 @@ export function ProgramDetailPage() { - +
diff --git a/src/pages/content-management/QuestionTypeLibraryPage.tsx b/src/pages/content-management/QuestionTypeLibraryPage.tsx index d4d9829..c328914 100644 --- a/src/pages/content-management/QuestionTypeLibraryPage.tsx +++ b/src/pages/content-management/QuestionTypeLibraryPage.tsx @@ -30,6 +30,7 @@ import { countActiveFilters } from "../../lib/adminFilterUtils" import { cn } from "../../lib/utils" import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" import { QuestionTypeCard } from "./components/QuestionTypeCard" +import { QuestionTypeDefinitionPracticesDialog } from "./components/QuestionTypeDefinitionPracticesDialog" import { deleteQuestionTypeDefinition, getQuestionTypeDefinitions, @@ -69,6 +70,7 @@ export function QuestionTypeLibraryPage() { const [offset, setOffset] = useState(0) const [definitionPendingDelete, setDefinitionPendingDelete] = useState(null) const [deleteSubmitting, setDeleteSubmitting] = useState(false) + const [definitionForPractices, setDefinitionForPractices] = useState(null) const hasActiveFilters = query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all" @@ -363,6 +365,10 @@ export function QuestionTypeLibraryPage() { responseKindsCount={d.response_component_kinds?.length ?? 0} deleteDisabled={!!d.is_system} onEdit={() => navigate(`/new-content/question-types/${d.id}/edit`)} + onCreatePractice={() => + navigate(`/new-content/question-types/${d.id}/create-practice`) + } + onViewPractices={() => setDefinitionForPractices(d)} onDelete={() => openDeleteConfirm(d)} /> ))} @@ -441,6 +447,14 @@ export function QuestionTypeLibraryPage() { + { + if (!open) setDefinitionForPractices(null) + }} + /> + diff --git a/src/pages/content-management/components/CreatePracticeWizard.tsx b/src/pages/content-management/components/CreatePracticeWizard.tsx index 15a2415..30cdec1 100644 --- a/src/pages/content-management/components/CreatePracticeWizard.tsx +++ b/src/pages/content-management/components/CreatePracticeWizard.tsx @@ -190,8 +190,7 @@ export function CreatePracticeWizard({ parent, onCreated }: Props) { setSaving(true) try { await createParentLinkedPractice({ - parent_kind: parent.kind, - parent_id: parent.id, + parents: [{ parent_kind: parent.kind, parent_id: parent.id }], title: practiceTitle.trim(), story_description: storyDescription.trim(), story_image: storyImage.trim(), diff --git a/src/pages/content-management/components/PracticeActionButton.tsx b/src/pages/content-management/components/PracticeActionButton.tsx new file mode 100644 index 0000000..514e53c --- /dev/null +++ b/src/pages/content-management/components/PracticeActionButton.tsx @@ -0,0 +1,40 @@ +import { useMemo, useState } from "react" +import type { ComponentProps } from "react" +import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../../lib/practiceContentPaths" +import { Button } from "../../../components/ui/button" +import { PracticeActionChoiceDialog } from "./PracticeActionChoiceDialog" + +interface PracticeActionButtonProps + extends Omit, "onClick"> { + pathOptions: PracticeContentPathOptions + parentLabel?: string | null +} + +export function PracticeActionButton({ + pathOptions, + parentLabel, + children, + ...buttonProps +}: PracticeActionButtonProps) { + const [open, setOpen] = useState(false) + const paths = useMemo( + () => buildPracticeContentPaths(pathOptions), + [pathOptions], + ) + + return ( + <> + + + + ) +} diff --git a/src/pages/content-management/components/PracticeActionChoiceDialog.tsx b/src/pages/content-management/components/PracticeActionChoiceDialog.tsx new file mode 100644 index 0000000..9c046be --- /dev/null +++ b/src/pages/content-management/components/PracticeActionChoiceDialog.tsx @@ -0,0 +1,117 @@ +import { Link2, Plus } from "lucide-react" +import { useNavigate } from "react-router-dom" +import { toast } from "sonner" +import { Button } from "../../../components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "../../../components/ui/dialog" +import { + resolvePracticeParentFromPathOptions, + type PracticeContentPathOptions, +} from "../../../lib/practiceContentPaths" + +interface PracticeActionChoiceDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + createHref: string + attachHref: string + pathOptions: PracticeContentPathOptions + parentLabel?: string | null +} + +export function PracticeActionChoiceDialog({ + open, + onOpenChange, + createHref, + attachHref, + pathOptions, + parentLabel, +}: PracticeActionChoiceDialogProps) { + const navigate = useNavigate() + + const openAttachPage = () => { + if (!resolvePracticeParentFromPathOptions(pathOptions)) { + toast.error("Missing content context", { + description: + "Open attach practice from a course, module, or lesson so the API knows where to link the practice.", + }) + return + } + onOpenChange(false) + navigate(attachHref) + } + + return ( + + + + + Add practice + + + {parentLabel ? ( + <> + Choose how to add a practice for{" "} + {parentLabel}. + + ) : ( + "Create a new practice or link an existing one from your library." + )} + + + +
+ + + +
+ +
+ +
+
+
+ ) +} diff --git a/src/pages/content-management/components/QuestionTypeCard.tsx b/src/pages/content-management/components/QuestionTypeCard.tsx index aa718da..2a45ae9 100644 --- a/src/pages/content-management/components/QuestionTypeCard.tsx +++ b/src/pages/content-management/components/QuestionTypeCard.tsx @@ -1,4 +1,4 @@ -import { Edit2, Sparkles, Trash2, Layers, Shield } from "lucide-react" +import { Edit2, GraduationCap, Plus, Sparkles, Trash2, Layers, Shield } from "lucide-react" import { Badge } from "../../../components/ui/badge" import { Card } from "../../../components/ui/card" import { Button } from "../../../components/ui/button" @@ -14,6 +14,8 @@ export interface QuestionTypeDefinitionCardModel { responseKindsCount: number onEdit?: () => void onDelete?: () => void + onViewPractices?: () => void + onCreatePractice?: () => void deleteDisabled?: boolean } @@ -27,6 +29,8 @@ export function QuestionTypeCard({ responseKindsCount, onEdit, onDelete, + onViewPractices, + onCreatePractice, deleteDisabled, }: QuestionTypeDefinitionCardModel) { const statusLabel = (status || "—").toString() @@ -69,6 +73,32 @@ export function QuestionTypeCard({ {statusLabel}
+ {onCreatePractice ? ( + + ) : null} + {onViewPractices ? ( + + ) : null} {onEdit ? ( +
+ ) : null} +
+ +
+ {loading ? ( +
+ +

Loading practices…

+
+ ) : practices.length === 0 ? ( +
+
+ +
+

No practices found

+

+ No published or draft practices currently contain questions built from this definition. +

+ {definition ? ( + + ) : null} +
+ ) : ( +
    + {practices.map((practice) => ( +
  • +
    +
    +

    {practice.title}

    +
    + practice #{practice.practice_id} + · + set #{practice.question_set_id} + {practice.parents && practice.parents.length > 0 ? ( + <> + · + {formatPracticeParentsSummary(practice.parents)} + + ) : ( + <> + · + Unlinked + + )} +
    + {practice.story_description?.trim() ? ( +

    {practice.story_description}

    + ) : null} +

    Created {formatDate(practice.created_at)}

    +
    +
    + + + {practice.publish_status || "—"} + + + {practice.matching_question_count} matching question + {practice.matching_question_count === 1 ? "" : "s"} + +
    +
    +
  • + ))} +
+ )} + + {!loading && totalCount > 0 ? ( +
+
+ + Showing {pageStart}–{pageEnd} of {totalCount} + + + + Per page +
+ + +
+
+
+
+ + +
+
+ ) : null} +
+
+
+ ) +} diff --git a/src/pages/content-management/components/practice-steps/ContextStep.tsx b/src/pages/content-management/components/practice-steps/ContextStep.tsx index 5254aed..14e1fe8 100644 --- a/src/pages/content-management/components/practice-steps/ContextStep.tsx +++ b/src/pages/content-management/components/practice-steps/ContextStep.tsx @@ -1,21 +1,37 @@ import { useRef, useState, type ChangeEvent } from "react"; -import { ArrowRight, Loader2, Upload } from "lucide-react"; +import { ArrowRight, ChevronDown, ChevronUp, Loader2, Upload } from "lucide-react"; import { Button } from "../../../../components/ui/button"; import { Card } from "../../../../components/ui/card"; import { Input } from "../../../../components/ui/input"; import { Textarea } from "../../../../components/ui/textarea"; import { toast } from "sonner"; import { uploadImageFile } from "../../../../api/files.api"; +import type { PracticeParent } from "../../../../types/course.types"; +import { PracticeParentsField } from "./PracticeParentsField"; +import { formatPracticeParentsSummary } from "../../../../lib/practiceParents"; interface ContextStepProps { - formData: any; - setFormData: (data: any) => void; + formData: { + title?: string; + description?: string; + storyImageUrl?: string; + shuffleQuestions?: boolean; + tips?: string; + parents?: PracticeParent[]; + }; + setFormData: (data: ContextStepProps["formData"]) => void; nextStep: () => void; onCancel: () => void; /** Lesson-linked practice: no title, story description, or story image on step 1. */ isLessonPractice?: boolean; lessonTitle?: string | null; parentSummary?: string | null; + /** Learn English LMS — show multi-parent picker. */ + showParentsEditor?: boolean; + lockedParentKey?: string | null; + /** When true, locations are optional and the picker can stay collapsed. */ + parentsOptional?: boolean; + parentsCollapsedDefault?: boolean; } /** @@ -29,9 +45,14 @@ export function ContextStep({ isLessonPractice = false, lessonTitle = null, parentSummary = null, + showParentsEditor = false, + lockedParentKey = null, + parentsOptional = false, + parentsCollapsedDefault = false, }: ContextStepProps) { const storyFileRef = useRef(null); const [uploadingStory, setUploadingStory] = useState(false); + const [parentsExpanded, setParentsExpanded] = useState(!parentsCollapsedDefault); const handleStoryImageFile = async (event: ChangeEvent) => { const file = event.target.files?.[0]; @@ -55,6 +76,11 @@ export function ContextStep({ ? true : Boolean(formData.title?.trim()) && Boolean(formData.description?.trim()); + const parentsSummary = + formData.parents && formData.parents.length > 0 + ? formatPracticeParentsSummary(formData.parents) + : parentSummary; + return (
@@ -91,16 +117,64 @@ export function ContextStep({
- {parentSummary ? ( + {parentsSummary && !showParentsEditor ? (

LMS parent

-

{parentSummary}

+

{parentsSummary}

- The question set and practice will be linked to this course, module, or lesson. + The question set and practice will be linked to these locations.

) : null} + {showParentsEditor ? ( + parentsOptional ? ( +
+
+

Locations optional

+

+ You can create this practice now and attach it to courses, modules, or lessons + later from the practice editor. +

+
+ + {parentsExpanded ? ( + setFormData({ ...formData, parents })} + /> + ) : null} +
+ ) : ( + setFormData({ ...formData, parents })} + /> + ) + ) : null} + {!isLessonPractice ? ( <>
diff --git a/src/pages/content-management/components/practice-steps/LinkExistingPracticeReviewStep.tsx b/src/pages/content-management/components/practice-steps/LinkExistingPracticeReviewStep.tsx new file mode 100644 index 0000000..d528650 --- /dev/null +++ b/src/pages/content-management/components/practice-steps/LinkExistingPracticeReviewStep.tsx @@ -0,0 +1,196 @@ +import { useMemo } from "react" +import { Loader2, Rocket } from "lucide-react" +import { Button } from "../../../../components/ui/button" +import { Card } from "../../../../components/ui/card" +import { + mergedParentsForAttach, + practiceAlreadyLinkedToParent, +} from "../../../../lib/attachPracticeToParent" +import { dedupeParents } from "../../../../lib/practiceParents" +import { + formatPracticeParentDisplayLabel, + formatPracticeParentsDisplaySummary, + type PracticeParentTitleHints, +} from "../../../../lib/practiceParentTitles" +import type { ParentContextPractice, PracticeParent } from "../../../../types/course.types" +import { cn } from "../../../../lib/utils" +import { usePracticeParentTitles } from "../../../../hooks/usePracticeParentTitles" + +interface LinkExistingPracticeReviewStepProps { + practice: ParentContextPractice + targetParent: PracticeParent + targetSummary: string + titleHints?: PracticeParentTitleHints + saving?: boolean + onBack: () => void + onConfirm: () => void + variant?: "page" | "dialog" +} + +function ParentsSummaryValue({ + loading, + text, +}: { + loading: boolean + text: string +}) { + if (loading) { + return ( + + + Loading locations… + + ) + } + return <>{text} +} + +export function LinkExistingPracticeReviewStep({ + practice, + targetParent, + targetSummary, + titleHints, + saving = false, + onBack, + onConfirm, + variant = "page", +}: LinkExistingPracticeReviewStepProps) { + const currentParentList = useMemo( + () => dedupeParents(practice.parents ?? []), + [practice.parents], + ) + const afterParentList = useMemo( + () => mergedParentsForAttach(practice, targetParent), + [practice, targetParent], + ) + const parentsToResolve = useMemo( + () => dedupeParents([...currentParentList, ...afterParentList, targetParent]), + [currentParentList, afterParentList, targetParent], + ) + + const { titles, loading: titlesLoading } = usePracticeParentTitles( + parentsToResolve, + titleHints, + ) + + const currentParents = formatPracticeParentsDisplaySummary(currentParentList, titles) + const afterParents = formatPracticeParentsDisplaySummary(afterParentList, titles) + const attachToLabel = titlesLoading + ? targetSummary + : formatPracticeParentDisplayLabel(targetParent, titles) + const alreadyLinked = practiceAlreadyLinkedToParent(practice, targetParent) + const isDialog = variant === "dialog" + + const reviewCard = ( + +

+ Review attachment +

+

+ Confirm linking this practice to the selected content location. +

+ +
+
+
+ Practice +
+
+ {practice.title?.trim() || `Practice #${practice.id}`} +
+
+ #{practice.id} · question set #{practice.question_set_id} +
+
+
+
+ Attach to +
+
+ +
+
+
+
+ Current locations +
+
+ +
+
+
+
+ After attachment +
+
+ +
+
+
+ + {alreadyLinked ? ( +
+ This practice is already linked to this location. +
+ ) : null} +
+ ) + + const actions = ( +
+ + +
+ ) + + if (isDialog) { + return ( +
+ {reviewCard} + {actions} +
+ ) + } + + return ( +
+ {reviewCard} + {actions} +
+ ) +} diff --git a/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx b/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx new file mode 100644 index 0000000..e06a2b0 --- /dev/null +++ b/src/pages/content-management/components/practice-steps/PracticeParentsField.tsx @@ -0,0 +1,132 @@ +import { Plus, Trash2 } from "lucide-react" +import { Button } from "../../../../components/ui/button" +import { Input } from "../../../../components/ui/input" +import type { PracticeParent, PracticeParentKind } from "../../../../types/course.types" +import { dedupeParents, newParentRow } from "../../../../lib/practiceParents" + +const KIND_OPTIONS: { value: PracticeParentKind; label: string }[] = [ + { value: "COURSE", label: "Course" }, + { value: "MODULE", label: "Module" }, + { value: "LESSON", label: "Lesson" }, +] + +interface PracticeParentsFieldProps { + parents: PracticeParent[] + onChange: (parents: PracticeParent[]) => void + disabled?: boolean + /** When set, this row cannot be removed (contextual entry point). */ + lockedParentKey?: string | null + /** When true, all rows can be cleared (unlinked practice). */ + optional?: boolean +} + +function parentKey(parent: PracticeParent): string { + return `${parent.parent_kind}:${parent.parent_id}` +} + +export function PracticeParentsField({ + parents, + onChange, + disabled = false, + lockedParentKey = null, + optional = false, +}: PracticeParentsFieldProps) { + const rows = parents.length > 0 ? parents : [newParentRow()] + + const updateRow = (index: number, patch: Partial) => { + const next = rows.map((row, i) => (i === index ? { ...row, ...patch } : row)) + onChange(dedupeParents(next)) + } + + const removeRow = (index: number) => { + const row = rows[index] + if (lockedParentKey && parentKey(row) === lockedParentKey) return + if (rows.length <= 1) { + if (optional) onChange([]) + return + } + onChange(rows.filter((_, i) => i !== index)) + } + + const addRow = () => { + onChange([...rows, newParentRow()]) + } + + return ( +
+
+

Attached locations

+

+ {optional + ? "Attach now or leave empty and link this practice later." + : "Link this practice to one or more courses, modules, or lessons. Each location can only have one practice."} +

+
+ +
    + {rows.map((row, index) => { + const key = parentKey(row) + const isLocked = Boolean(lockedParentKey && key === lockedParentKey && row.parent_id > 0) + return ( +
  • + + 0 ? row.parent_id : ""} + onChange={(e) => + updateRow(index, { parent_id: Number(e.target.value) || 0 }) + } + placeholder="Parent id" + className="h-9 w-28 rounded-[8px] border-grayScale-200 font-mono text-sm" + /> + + {row.parent_kind} parent id from the content hierarchy + + +
  • + ) + })} +
+ + +
+ ) +} diff --git a/src/pages/content-management/components/practice-steps/PracticeSequentialReview.tsx b/src/pages/content-management/components/practice-steps/PracticeSequentialReview.tsx index 637258c..fbadb27 100644 --- a/src/pages/content-management/components/practice-steps/PracticeSequentialReview.tsx +++ b/src/pages/content-management/components/practice-steps/PracticeSequentialReview.tsx @@ -30,6 +30,7 @@ export type PracticeSequentialReviewProps = { saveError?: string | null; canPublish?: boolean; showMissingParentWarning?: boolean; + showUnlinkedBanner?: boolean; onEditContext?: () => void; onEditQuestions?: () => void; onBack: () => void; @@ -133,6 +134,7 @@ export function PracticeSequentialReview({ saveError = null, canPublish = true, showMissingParentWarning = false, + showUnlinkedBanner = false, onEditContext, onEditQuestions, onBack, @@ -143,7 +145,12 @@ export function PracticeSequentialReview({ sectionTitle = "Create Practice Questions", sectionSubtitle = "Define the dialogue flow and interactions for this scenario.", }: PracticeSequentialReviewProps) { - const filledQuestions = questions.filter((q) => q.questionText.trim()); + const filledQuestions = questions.filter( + (q) => + q.questionText.trim() || + q.voicePrompt.trim() || + q.sampleAnswerVoicePrompt.trim(), + ); return (
@@ -160,6 +167,16 @@ export function PracticeSequentialReview({
) : null} + {showUnlinkedBanner && parentLink === "Not attached to any course, module, or lesson" ? ( +
+

Not attached yet

+

+ This practice will be saved without course, module, or lesson links. Attach locations + later from the practice editor. +

+
+ ) : null} + {showMissingParentWarning && !canPublish ? (

Missing parent for the API

@@ -284,7 +301,7 @@ export function PracticeSequentialReview({ {filledQuestions.length}
-
+
{filledQuestions.map((question, index) => (
@@ -333,7 +350,7 @@ export function PracticeSequentialReview({ ) : null}
-
+
{filledQuestions.map((question, index) => (
diff --git a/src/pages/content-management/components/practice-steps/QuestionAssociationField.tsx b/src/pages/content-management/components/practice-steps/QuestionAssociationField.tsx new file mode 100644 index 0000000..611ca02 --- /dev/null +++ b/src/pages/content-management/components/practice-steps/QuestionAssociationField.tsx @@ -0,0 +1,111 @@ +import { Select } from "../../../../components/ui/select" +import { + getSectionAnchorOptions, + isQuestionSectionAnchor, + setQuestionSectionAnchorRef, + type QuestionAssociationRow, +} from "../../../../lib/questionAssociations" + +type QuestionAssociationFieldProps = { + question: QuestionAssociationRow + allQuestions: QuestionAssociationRow[] + onChange: (patch: { + associatedQuestionId: number | null + associatedAnchorRowId: string | null + }) => void +} + +export function QuestionAssociationField({ + question, + allQuestions, + onChange, +}: QuestionAssociationFieldProps) { + const isAnchor = isQuestionSectionAnchor(question) + const anchorOptions = getSectionAnchorOptions(allQuestions, question.id) + const selectedValue = + question.associatedQuestionId != null + ? String(question.associatedQuestionId) + : question.associatedAnchorRowId ?? "" + + return ( +
+

+ Section grouping +

+ + + {!isAnchor ? ( +
+ + +

+ Learners complete earlier sections before this question unlocks. +

+
+ ) : ( +

+ This question opens a new section. Link follow-up questions to it using the + section anchor dropdown. +

+ )} + + {question.prerequisiteQuestionIds && question.prerequisiteQuestionIds.length > 0 ? ( +

+ Prerequisites (from API): {question.prerequisiteQuestionIds.join(", ")} +

+ ) : null} +
+ ) +} diff --git a/src/pages/content-management/components/practice-steps/QuestionsStep.tsx b/src/pages/content-management/components/practice-steps/QuestionsStep.tsx index eea75d0..f2aad23 100644 --- a/src/pages/content-management/components/practice-steps/QuestionsStep.tsx +++ b/src/pages/content-management/components/practice-steps/QuestionsStep.tsx @@ -38,13 +38,23 @@ import { legacyQuestionTypeFromDefinition, } from "../../../../lib/learnEnglishDefinitionQuestion"; import { validateLearnEnglishQuestionsWithDefinitions } from "../../../../lib/learnEnglishPracticePublish"; +import { + fixAssociationsAfterReorder, + findLastSectionAnchor, + sectionBadgeLabel, + setQuestionSectionAnchorRef, + validateQuestionAssociations, +} from "../../../../lib/questionAssociations"; import { cn } from "../../../../lib/utils"; import { toast } from "sonner"; +import { QuestionAssociationField } from "./QuestionAssociationField"; function syncQuestionDisplayOrders( questions: T[], ): T[] { - return questions.map((q, index) => ({ ...q, displayOrder: index + 1 })); + return fixAssociationsAfterReorder( + questions.map((q, index) => ({ ...q, displayOrder: index + 1 })), + ); } function truncateText(value: string, max = 100): string { @@ -152,11 +162,17 @@ function defaultMcqOptions() { ]; } -function createEmptyQuestionRow(id: string, displayOrder = 1) { +function createEmptyQuestionRow(id: string, displayOrder = 1, inheritAnchor?: { + associatedQuestionId: number | null + associatedAnchorRowId: string | null +}) { return { id, displayOrder, serverQuestionId: null as number | null, + associatedQuestionId: inheritAnchor?.associatedQuestionId ?? null, + associatedAnchorRowId: inheritAnchor?.associatedAnchorRowId ?? null, + prerequisiteQuestionIds: [] as number[], questionTypeDefinitionId: null as number | null, text: "", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", @@ -273,9 +289,22 @@ export function QuestionsStep({ setFormData({ ...formData, questions: newQuestions }); }; - const addQuestion = () => { + const addQuestion = (startNewSection = false) => { const id = `q${Date.now()}`; - const row = createEmptyQuestionRow(id); + const lastAnchor = startNewSection ? undefined : findLastSectionAnchor(formData.questions); + const inheritAnchor = lastAnchor + ? (() => { + const linked = setQuestionSectionAnchorRef( + { id, associatedQuestionId: null, associatedAnchorRowId: null }, + lastAnchor, + ); + return { + associatedQuestionId: linked.associatedQuestionId ?? null, + associatedAnchorRowId: linked.associatedAnchorRowId ?? null, + }; + })() + : undefined; + const row = createEmptyQuestionRow(id, formData.questions.length + 1, inheritAnchor); if (typeDefinitions[0]) { row.questionTypeDefinitionId = typeDefinitions[0].id; row.dynamicFieldValues = emptyDynamicFieldValuesForDefinition( @@ -511,8 +540,9 @@ export function QuestionsStep({

Questions

- Choose a question type for each item, then fill in the fields that type requires. Collapse cards to - compare and drag them into order. Questions are saved when you publish or save the practice. + Choose a question type for each item, then fill in the fields that type requires. + Group questions into sections so learners complete earlier blocks before later ones unlock. + Collapse cards to compare and drag them into order.

@@ -618,6 +648,9 @@ export function QuestionsStep({ {q.difficultyLevel ?? "EASY"} + + {sectionBadgeLabel(q, formData.questions)} + {q.points ?? 1} pt{(q.points ?? 1) === 1 ? "" : "s"} @@ -679,6 +712,16 @@ export function QuestionsStep({
+ { + const newQuestions = [...formData.questions]; + newQuestions[i] = { ...newQuestions[i], ...patch }; + setFormData({ ...formData, questions: newQuestions }); + }} + /> +