diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index 7675fef..0293b13 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -125,6 +125,7 @@ import type { UpdateParentLinkedPracticeResponse, UpdatePracticeParentsRequest, UpdatePracticeParentsResponse, + PracticeParent, PublishParentLinkedPracticeRequest, PublishStatusOnlyRequest, AccessTierOnlyRequest, @@ -732,6 +733,15 @@ export const updateExamPrepPracticeParents = ( data, ) +/** DELETE /exam-prep/practices/:id/parents/:parentKind/:parentId — unlink one parent. */ +export const unlinkExamPrepPracticeParent = ( + practiceId: number, + parent: PracticeParent, +) => + http.delete( + `/exam-prep/practices/${practiceId}/parents/${parent.parent_kind.toUpperCase()}/${parent.parent_id}`, + ) + /** DELETE /exam-prep/practices/:practiceId */ export const deleteExamPrepPractice = (practiceId: number) => http.delete<{ message: string; success: boolean; status_code: number; metadata: unknown }>( @@ -924,6 +934,15 @@ export const updatePracticeParents = ( data: UpdatePracticeParentsRequest, ) => http.put(`/practices/${practiceId}/parents`, data) +/** DELETE /practices/:id/parents/:parentKind/:parentId — unlink one parent. */ +export const unlinkPracticeParent = ( + practiceId: number, + parent: PracticeParent, +) => + http.delete( + `/practices/${practiceId}/parents/${parent.parent_kind.toUpperCase()}/${parent.parent_id}`, + ) + /** PUT /practices/:id */ export const updateParentLinkedPractice = ( practiceId: number, diff --git a/src/api/questionTypeDefinitions.api.ts b/src/api/questionTypeDefinitions.api.ts index 6a84090..060771b 100644 --- a/src/api/questionTypeDefinitions.api.ts +++ b/src/api/questionTypeDefinitions.api.ts @@ -12,7 +12,13 @@ import type { ValidateQuestionTypeDefinitionResult, } from "../types/questionTypeDefinition.types" import { normalizeGroupIds } from "../lib/questionTypeGroupIds" -import { normalizePracticeParents, parentsFromPractice } from "../lib/practiceParents" +import { + dedupeParents, + normalizePracticeParent, + normalizePracticeParents, + parentsFromPractice, +} from "../lib/practiceParents" +import type { PracticeParent } from "../types/course.types" interface ApiEnvelope { message?: string @@ -436,6 +442,15 @@ export async function deleteQuestionTypeDefinition(id: number) { return http.delete>(`/questions/type-definitions/${id}`) } +function normalizeParentsArray(raw: unknown): PracticeParent[] { + if (!Array.isArray(raw)) return [] + return dedupeParents( + raw + .map((entry) => normalizePracticeParent(entry)) + .filter((entry): entry is PracticeParent => entry != null), + ) +} + function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice | null { if (!row || typeof row !== "object") return null const o = row as Record @@ -473,14 +488,36 @@ function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice 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, - }) + const practiceKindRaw = asStr(o.practice_kind ?? o.PracticeKind ?? o.practiceKind ?? "LMS") + const isExamPrep = practiceKindRaw.toUpperCase() === "EXAM_PREP" + + const examPrepParentsRaw = o.exam_prep_parents ?? o.ExamPrepParents ?? o.examPrepParents + const examPrepParentsList = normalizeParentsArray(examPrepParentsRaw) + const exam_prep_parents = examPrepParentsList.length > 0 ? examPrepParentsList : null + + const exam_prep_lesson_id_raw = Number( + o.exam_prep_lesson_id ?? o.ExamPrepLessonId ?? o.examPrepLessonId, + ) + const exam_prep_lesson_id = + Number.isFinite(exam_prep_lesson_id_raw) && exam_prep_lesson_id_raw > 0 + ? exam_prep_lesson_id_raw + : undefined + + const lmsParentsList = isExamPrep + ? [] + : parentsFromPractice({ + parents: normalizePracticeParents(row), + parent_kind, + parent_id, + }) + const parents = isExamPrep ? null : lmsParentsList.length > 0 ? lmsParentsList : null + + const persona_id_raw = Number(o.persona_id ?? o.PersonaId ?? o.personaId) + const persona_id = + Number.isFinite(persona_id_raw) && persona_id_raw > 0 ? persona_id_raw : undefined return { - practice_kind: asStr(o.practice_kind ?? o.PracticeKind ?? o.practiceKind ?? "LMS"), + practice_kind: isExamPrep ? "EXAM_PREP" : "LMS", practice_id, question_set_id, title: asStr(o.title ?? o.Title) || `Practice #${practice_id}`, @@ -504,8 +541,11 @@ function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice : 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, + exam_prep_parents, + exam_prep_lesson_id, + parent_kind: (isExamPrep ? exam_prep_parents?.[0] : parents?.[0])?.parent_kind, + parent_id: (isExamPrep ? exam_prep_parents?.[0] : parents?.[0])?.parent_id, + persona_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, @@ -592,7 +632,7 @@ function parsePracticesPage( /** * GET /questions/type-definitions/:id/practices - * Lists LMS practices that contain questions using this definition. + * Lists LMS and exam-prep practices whose question set contains matching questions. */ export async function getQuestionTypeDefinitionPractices( definitionId: number, diff --git a/src/lib/examPrepPracticeEditPath.ts b/src/lib/examPrepPracticeEditPath.ts new file mode 100644 index 0000000..8bb4fec --- /dev/null +++ b/src/lib/examPrepPracticeEditPath.ts @@ -0,0 +1,283 @@ +import { + getExamPrepCatalogCoursePractices, + getExamPrepCatalogCourses, + getExamPrepCatalogUnits, + getExamPrepLessonPractices, + getExamPrepModuleLessons, + getExamPrepPracticeFull, + getExamPrepUnitModules, + getExamPrepUnitPractices, +} from "../api/courses.api" +import { examPrepParentsFromPractice } from "./questionTypeDefinitionPractices" +import { unwrapPracticeFullData } from "./practiceFullMapper" +import { dedupeParents, parentsFromPractice } from "./practiceParents" +import type { + ExamPrepCatalogCourseItem, + ExamPrepCatalogUnitItem, + ExamPrepModuleLessonItem, + ExamPrepUnitModuleItem, + PracticeParent, +} from "../types/course.types" +import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types" + +const PAGE_SIZE = 100 +const DEFAULT_PROGRAM_TYPE = "proficiency" + +type ExamPrepParentTab = "catalog_course" | "unit" | "lesson" + +function listFromEnvelope( + res: { data?: { data?: Record; Data?: Record } }, + key: string, +): T[] { + const body = res.data?.data ?? res.data?.Data + if (!body || typeof body !== "object") return [] + const record = body as Record + const pascalKey = key.charAt(0).toUpperCase() + key.slice(1) + const raw = record[key] ?? record[pascalKey] + return Array.isArray(raw) ? (raw as T[]) : [] +} + +function totalFromEnvelope( + res: { data?: { data?: Record; Data?: Record } }, +): number | undefined { + const body = res.data?.data ?? res.data?.Data + if (!body || typeof body !== "object") return undefined + const record = body as Record + const total = Number(record.total_count ?? record.TotalCount ?? record.totalCount) + return Number.isFinite(total) && total >= 0 ? total : undefined +} + +function parentTabFromKind(kind?: string): ExamPrepParentTab | null { + const k = (kind || "").toUpperCase() + if (k === "CATALOG_COURSE") return "catalog_course" + if (k === "UNIT") return "unit" + if (k === "LESSON") return "lesson" + return null +} + +function buildCatalogCourseEditPath(catalogCourseId: number, practiceId: number): string { + return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/edit-practice/${practiceId}?backTo=courses` +} + +function buildUnitEditPath( + catalogCourseId: number, + unitId: number, + practiceId: number, +): string { + return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/${unitId}/edit-practice/${practiceId}?backTo=unit` +} + +function buildLessonEditPath( + catalogCourseId: number, + unitId: number, + moduleId: number, + lessonId: number, + practiceId: number, + lessonTitle?: string, +): string { + const titleQuery = lessonTitle ? `lessonTitle=${encodeURIComponent(lessonTitle)}&` : "" + return `/new-content/courses/${DEFAULT_PROGRAM_TYPE}/${catalogCourseId}/${unitId}/${moduleId}/lessons/${lessonId}/edit-practice/${practiceId}?${titleQuery}backTo=lesson` +} + +async function fetchAllCatalogCourses(): Promise { + const all: ExamPrepCatalogCourseItem[] = [] + let offset = 0 + while (true) { + const res = await getExamPrepCatalogCourses({ limit: PAGE_SIZE, offset }) + const page = listFromEnvelope(res, "catalog_courses") + all.push(...page) + const total = totalFromEnvelope(res) + if (page.length === 0) break + if (total != null && all.length >= total) break + if (page.length < PAGE_SIZE) break + offset += page.length + } + return all +} + +async function fetchAllCatalogUnits(catalogCourseId: number): Promise { + const all: ExamPrepCatalogUnitItem[] = [] + let offset = 0 + while (true) { + const res = await getExamPrepCatalogUnits(catalogCourseId, { limit: PAGE_SIZE, offset }) + const page = listFromEnvelope(res, "units") + all.push(...page) + const total = totalFromEnvelope(res) + if (page.length === 0) break + if (total != null && all.length >= total) break + if (page.length < PAGE_SIZE) break + offset += page.length + } + return all +} + +async function fetchAllUnitModules(unitId: number): Promise { + const all: ExamPrepUnitModuleItem[] = [] + let offset = 0 + while (true) { + const res = await getExamPrepUnitModules(unitId, { limit: PAGE_SIZE, offset }) + const page = listFromEnvelope(res, "modules") + all.push(...page) + const total = totalFromEnvelope(res) + if (page.length === 0) break + if (total != null && all.length >= total) break + if (page.length < PAGE_SIZE) break + offset += page.length + } + return all +} + +async function fetchAllModuleLessons(moduleId: number): Promise { + const all: ExamPrepModuleLessonItem[] = [] + let offset = 0 + while (true) { + const res = await getExamPrepModuleLessons(moduleId, { limit: PAGE_SIZE, offset }) + const page = listFromEnvelope(res, "lessons") + all.push(...page) + const total = totalFromEnvelope(res) + if (page.length === 0) break + if (total != null && all.length >= total) break + if (page.length < PAGE_SIZE) break + offset += page.length + } + return all +} + +async function parentListContainsPractice( + tab: ExamPrepParentTab, + parentId: number, + practiceId: number, +): Promise { + let offset = 0 + while (true) { + const params = { limit: PAGE_SIZE, offset } + const res = + tab === "catalog_course" + ? await getExamPrepCatalogCoursePractices(parentId, params) + : tab === "unit" + ? await getExamPrepUnitPractices(parentId, params) + : await getExamPrepLessonPractices(parentId, params) + const page = listFromEnvelope<{ id?: number; ID?: number }>(res, "practices") + if (page.some((p) => Number(p.id ?? p.ID) === practiceId)) return true + const total = totalFromEnvelope(res) + if (page.length === 0) break + if (total != null && offset + page.length >= total) break + if (page.length < PAGE_SIZE) break + offset += page.length + } + return false +} + +async function detectParentTab( + practiceId: number, + parentId: number, + hintedTab: ExamPrepParentTab | null, +): Promise { + if (hintedTab && (await parentListContainsPractice(hintedTab, parentId, practiceId))) { + return hintedTab + } + const order: ExamPrepParentTab[] = + hintedTab == null + ? ["lesson", "unit", "catalog_course"] + : (["lesson", "unit", "catalog_course"] as ExamPrepParentTab[]).filter( + (tab) => tab !== hintedTab, + ) + for (const tab of order) { + if (await parentListContainsPractice(tab, parentId, practiceId)) return tab + } + return hintedTab +} + +async function findUnitPath(unitId: number, practiceId: number): Promise { + const courses = await fetchAllCatalogCourses() + for (const course of courses) { + const units = await fetchAllCatalogUnits(course.id) + const unit = units.find((u) => u.id === unitId) + if (unit) { + const catalogCourseId = unit.catalog_course_id || course.id + return buildUnitEditPath(catalogCourseId, unit.id, practiceId) + } + } + return null +} + +async function findLessonPath(lessonId: number, practiceId: number): Promise { + const courses = await fetchAllCatalogCourses() + for (const course of courses) { + const units = await fetchAllCatalogUnits(course.id) + for (const unit of units) { + const modules = await fetchAllUnitModules(unit.id) + for (const module of modules) { + const lessons = await fetchAllModuleLessons(module.id) + const lesson = lessons.find((l) => l.id === lessonId) + if (lesson) { + const catalogCourseId = unit.catalog_course_id || course.id + return buildLessonEditPath( + catalogCourseId, + unit.id, + module.id, + lesson.id, + practiceId, + lesson.title, + ) + } + } + } + } + return null +} + +async function resolveForParent( + practiceId: number, + parent: PracticeParent, +): Promise { + const parentId = parent.parent_id + if (parentId < 1) return null + const hintedTab = parentTabFromKind(parent.parent_kind) + const tab = await detectParentTab(practiceId, parentId, hintedTab) + const resolvedTab = tab ?? hintedTab + if (!resolvedTab) return null + if (resolvedTab === "catalog_course") { + return buildCatalogCourseEditPath(parentId, practiceId) + } + if (resolvedTab === "unit") return findUnitPath(parentId, practiceId) + return findLessonPath(parentId, practiceId) +} + +async function enrichExamPrepPracticeFromFull( + practice: QuestionTypeDefinitionPractice, +): Promise { + try { + const res = await getExamPrepPracticeFull(practice.practice_id) + const full = unwrapPracticeFullData(res) + const p = full?.practice + if (!p) return practice + const parents = dedupeParents(parentsFromPractice(p)) + return { + ...practice, + exam_prep_parents: parents.length > 0 ? parents : practice.exam_prep_parents, + } + } catch { + return practice + } +} + +/** + * Resolves an exam-prep edit-practice route for a practice linked to a question type definition. + */ +export async function resolveExamPrepPracticeEditPath( + practice: QuestionTypeDefinitionPractice, +): Promise { + let working = practice + if (examPrepParentsFromPractice(working).length === 0) { + working = await enrichExamPrepPracticeFromFull(working) + } + + const parentList = examPrepParentsFromPractice(working) + for (const parent of parentList) { + const path = await resolveForParent(working.practice_id, parent) + if (path) return path + } + + return null +} diff --git a/src/lib/learnEnglishDefinitionQuestion.ts b/src/lib/learnEnglishDefinitionQuestion.ts index 3c55968..7d2f9cf 100644 --- a/src/lib/learnEnglishDefinitionQuestion.ts +++ b/src/lib/learnEnglishDefinitionQuestion.ts @@ -193,6 +193,7 @@ export interface LearnEnglishDefinitionQuestionInput { associatedQuestionId?: number | null associatedAnchorRowId?: string | null prerequisiteQuestionIds?: number[] + stimulusBlockKey?: string | null displayOrder?: number mcqOptions?: { option_text: string; is_correct: boolean }[] trueFalseAnswerIsTrue?: boolean diff --git a/src/lib/practiceDynamicQuestionPayload.ts b/src/lib/practiceDynamicQuestionPayload.ts index 6964500..73f0e26 100644 --- a/src/lib/practiceDynamicQuestionPayload.ts +++ b/src/lib/practiceDynamicQuestionPayload.ts @@ -27,6 +27,7 @@ import { multipleChoiceSlotHasContent, normalizeMultipleChoiceValue, parseMultipleChoiceSlotValue, + serializeMultipleChoiceSlotValue, } from "./multipleChoiceSlotValue" import { isNoInputComponentKind } from "./questionComponentKinds" @@ -163,6 +164,38 @@ function slotValueForRow( return parseDynamicSlotValue(rawField) } +export function slotApiValueToFieldString(value: unknown, kind: string): string { + const upperKind = kind.trim().toUpperCase() + if (value == null) return "" + if (typeof value === "string") return value + if (upperKind === "PREP_TIME" || upperKind === "ANSWER_TIMER") { + if (typeof value === "object" && value !== null && "seconds" in value) { + const seconds = (value as { seconds?: unknown }).seconds + if (typeof seconds === "number" && Number.isFinite(seconds)) { + return String(seconds) + } + } + } + if (upperKind === "MULTIPLE_CHOICE" || upperKind === "OPTION") { + return serializeMultipleChoiceSlotValue(value as { options: unknown[] }) + } + if (typeof value === "object") return JSON.stringify(value) + return String(value) +} + +export function dynamicPayloadToFieldValues( + payload: DynamicQuestionPayload | null | undefined, +): Record { + const out: Record = {} + for (const slot of payload?.stimulus ?? []) { + out[`stimulus:${slot.id}`] = slotApiValueToFieldString(slot.value, slot.kind) + } + for (const slot of payload?.response ?? []) { + out[`response:${slot.id}`] = slotApiValueToFieldString(slot.value, slot.kind) + } + return out +} + export function buildDynamicQuestionPayload(input: { stimulusRows: { id: string; kind: string }[] responseRows: { id: string; kind: string }[] diff --git a/src/lib/practiceEditOrchestrator.ts b/src/lib/practiceEditOrchestrator.ts index 349c665..cd2e5c4 100644 --- a/src/lib/practiceEditOrchestrator.ts +++ b/src/lib/practiceEditOrchestrator.ts @@ -1,4 +1,6 @@ import { + getExamPrepPracticeFull, + getLearnEnglishPracticeFull, updateExamPrepPracticeFull, updateExamPrepPracticeParents, updateLearnEnglishPracticeFull, @@ -9,10 +11,12 @@ import type { QuestionTypeDefinition } from "../types/questionTypeDefinition.typ import { dedupeParents } from "./practiceParents" import { buildPracticeFullUpdateRequest, + unwrapPracticeFullData, type PracticeFormState, type PreservedQuestionSetFields, type PracticeEditQuestionInput, } from "./practiceFullMapper" +import { isIeltsSharedStimulusMode } from "./practiceStimulusBlocks" export interface PracticeEditInput { practiceId: number @@ -61,3 +65,57 @@ export async function executePracticeUpdate( }) } } + +export interface SyncStimulusBlocksAfterCreateInput { + practiceId: number + isExamPrep: boolean + status: PracticePublishStatus + formData: PracticeFormState + personaId: number + preservedQuestionSet: PreservedQuestionSetFields + questions: PracticeEditQuestionInput[] + definitions: QuestionTypeDefinition[] + isLearnEnglishLessonPractice: boolean + lessonDefaultTitle?: string +} + +/** After multi-step create, apply authoring profile + stimulus blocks via full PUT. */ +export async function syncStimulusBlocksAfterCreate( + opts: SyncStimulusBlocksAfterCreateInput, +): Promise { + if (!isIeltsSharedStimulusMode(opts.formData.authoringProfile)) return + + const res = opts.isExamPrep + ? await getExamPrepPracticeFull(opts.practiceId) + : await getLearnEnglishPracticeFull(opts.practiceId) + const full = unwrapPracticeFullData(res) + if (!full) throw new Error("Could not load created practice for stimulus block sync.") + + const sortedFull = [...full.questions].sort( + (a, b) => (a.display_order ?? 0) - (b.display_order ?? 0), + ) + const sortedInput = [...opts.questions].sort( + (a, b) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0), + ) + const questionsWithIds: PracticeEditQuestionInput[] = sortedInput.map((q, index) => ({ + ...q, + serverQuestionId: sortedFull[index]?.id ?? null, + })) + + const payload = buildPracticeFullUpdateRequest({ + formData: opts.formData, + personaId: opts.personaId, + status: opts.status, + preservedQuestionSet: opts.preservedQuestionSet, + questions: questionsWithIds, + definitions: opts.definitions, + isLearnEnglishLessonPractice: opts.isLearnEnglishLessonPractice, + lessonDefaultTitle: opts.lessonDefaultTitle, + }) + + if (opts.isExamPrep) { + await updateExamPrepPracticeFull(opts.practiceId, payload) + return + } + await updateLearnEnglishPracticeFull(opts.practiceId, payload) +} diff --git a/src/lib/practiceFullMapper.ts b/src/lib/practiceFullMapper.ts index ab22018..d237d12 100644 --- a/src/lib/practiceFullMapper.ts +++ b/src/lib/practiceFullMapper.ts @@ -6,6 +6,7 @@ import type { PracticeFullQuestionSet, PracticeParent, PracticePublishStatus, + AuthoringProfile, QuestionOption, QuestionShortAnswer, UpdatePracticeFullRequest, @@ -24,9 +25,23 @@ import { questionRowHasContent, type LearnEnglishDefinitionQuestionInput, } from "./learnEnglishDefinitionQuestion" -import { serializeMultipleChoiceSlotValue } from "./multipleChoiceSlotValue" import { normalizePracticeParents, parentsFromPractice } from "./practiceParents" import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator" +import { + dynamicPayloadToFieldValues, + slotApiValueToFieldString, +} from "./practiceDynamicQuestionPayload" +import { + filterQuestionStimulusForBlock, + getBlockStimulusByKey, + isIeltsSharedStimulusMode, + mapApiStimulusBlocksToForm, + mapFormStimulusBlocksToApi, + normalizeAuthoringProfile, + validatePracticeStimulusBlocks, + validateStimulusBlocks, + type PracticeFormStimulusBlock, +} from "./practiceStimulusBlocks" import { resolveAssociatedQuestionId, validateQuestionAssociations, @@ -39,6 +54,7 @@ export interface PracticeFormQuestionRow { associatedQuestionId: number | null associatedAnchorRowId: string | null prerequisiteQuestionIds?: number[] + stimulusBlockKey: string | null questionTypeDefinitionId: number | null text: string difficultyLevel: "EASY" | "MEDIUM" | "HARD" @@ -55,6 +71,8 @@ export interface PracticeFormState { storyImageUrl: string shuffleQuestions: boolean tips: string + authoringProfile: AuthoringProfile + stimulusBlocks: PracticeFormStimulusBlock[] parents: PracticeParent[] questions: PracticeFormQuestionRow[] } @@ -232,6 +250,15 @@ export function normalizePracticeFullQuestion( dynamic_payload: normalizeDynamicPayload( record.dynamic_payload ?? record.DynamicPayload, ), + effective_dynamic_payload: normalizeDynamicPayload( + record.effective_dynamic_payload ?? record.EffectiveDynamicPayload, + ), + stimulus_block_key: + record.stimulus_block_key != null + ? String(record.stimulus_block_key).trim() || null + : record.StimulusBlockKey != null + ? String(record.StimulusBlockKey).trim() || null + : null, difficulty_level: pickStr(record, "difficulty_level", "DifficultyLevel", "difficultyLevel") || undefined, @@ -322,6 +349,9 @@ function normalizePracticeFullPractice(raw: unknown): PracticeFullPractice | nul pickStr(record, "story_image", "StoryImage", "storyImage") || undefined, persona_id: pickNum(record, "persona_id", "PersonaId", "personaId"), question_set_id: questionSetId, + authoring_profile: normalizeAuthoringProfile( + record.authoring_profile ?? record.AuthoringProfile, + ), publish_status: pickStr(record, "publish_status", "PublishStatus", "publishStatus") || null, quick_tips: pickStr(record, "quick_tips", "QuickTips", "quickTips") || undefined, @@ -348,7 +378,29 @@ export function normalizePracticeFullData(raw: unknown): PracticeFullData | null const questions = questionsRaw .map((entry) => normalizePracticeFullQuestion(entry)) .filter((entry): entry is PracticeFullQuestionItem => entry != null) - return { practice, question_set: questionSet, questions } + const stimulusBlocksRaw = record.stimulus_blocks ?? record.StimulusBlocks + const stimulus_blocks = Array.isArray(stimulusBlocksRaw) + ? stimulusBlocksRaw + .map((entry) => { + const blockRecord = asRecord(entry) + if (!blockRecord) return null + const blockKey = pickStr(blockRecord, "block_key", "BlockKey", "blockKey") + if (!blockKey) return null + return { + ...(pickNum(blockRecord, "id", "Id", "ID") != null + ? { id: pickNum(blockRecord, "id", "Id", "ID")! } + : {}), + block_key: blockKey, + display_order: + pickNum(blockRecord, "display_order", "DisplayOrder", "displayOrder") ?? 0, + stimulus: normalizeDynamicElementArray( + blockRecord.stimulus ?? blockRecord.Stimulus, + ), + } + }) + .filter((entry): entry is NonNullable => entry != null) + : undefined + return { practice, question_set: questionSet, questions, stimulus_blocks } } function payloadValuesByKind( @@ -410,38 +462,6 @@ function hydrateDynamicFieldValues( return merged } -function slotApiValueToFieldString(value: unknown, kind: string): string { - const upperKind = kind.trim().toUpperCase() - if (value == null) return "" - if (typeof value === "string") return value - if (upperKind === "PREP_TIME" || upperKind === "ANSWER_TIMER") { - if (typeof value === "object" && value !== null && "seconds" in value) { - const seconds = (value as { seconds?: unknown }).seconds - if (typeof seconds === "number" && Number.isFinite(seconds)) { - return String(seconds) - } - } - } - if (upperKind === "MULTIPLE_CHOICE" || upperKind === "OPTION") { - return serializeMultipleChoiceSlotValue(value as { options: unknown[] }) - } - if (typeof value === "object") return JSON.stringify(value) - return String(value) -} - -export function dynamicPayloadToFieldValues( - payload: DynamicQuestionPayload | null | undefined, -): Record { - const out: Record = {} - for (const slot of payload?.stimulus ?? []) { - out[`stimulus:${slot.id}`] = slotApiValueToFieldString(slot.value, slot.kind) - } - for (const slot of payload?.response ?? []) { - out[`response:${slot.id}`] = slotApiValueToFieldString(slot.value, slot.kind) - } - return out -} - function normalizeShortAnswers( shortAnswers: PracticeFullQuestionItem["short_answers"], ): string[] { @@ -531,6 +551,7 @@ function mapFullQuestionToFormRow( associatedQuestionId: q.associated_question_id ?? null, associatedAnchorRowId: null, prerequisiteQuestionIds: q.prerequisite_question_ids, + stimulusBlockKey: q.stimulus_block_key ?? null, questionTypeDefinitionId: defId, text, difficultyLevel, @@ -553,7 +574,7 @@ export function mapPracticeFullToFormState( preservedQuestionSet: PreservedQuestionSetFields parents: PracticeParent[] } { - const { practice, question_set, questions } = data + const { practice, question_set, questions, stimulus_blocks } = data const sorted = [...questions].sort( (a, b) => (a.display_order ?? 0) - (b.display_order ?? 0), ) @@ -568,6 +589,7 @@ export function mapPracticeFullToFormState( serverQuestionId: null, associatedQuestionId: null, associatedAnchorRowId: null, + stimulusBlockKey: null, questionTypeDefinitionId: typeDefinitions[0]?.id ?? null, text: "", difficultyLevel: "EASY" as const, @@ -591,6 +613,8 @@ export function mapPracticeFullToFormState( storyImageUrl: practice.story_image?.trim() || "", shuffleQuestions: Boolean(question_set.shuffle_questions), tips: practice.quick_tips?.trim() || "", + authoringProfile: normalizeAuthoringProfile(practice.authoring_profile), + stimulusBlocks: mapApiStimulusBlocksToForm(stimulus_blocks), parents: parentsFromPractice(practice), questions: formQuestions, }, @@ -638,7 +662,17 @@ function buildFullUpdateQuestion( if (created.question_type_definition_id != null) { item.question_type_definition_id = created.question_type_definition_id } - if (created.dynamic_payload) item.dynamic_payload = created.dynamic_payload + if (created.dynamic_payload) { + item.dynamic_payload = q.stimulusBlockKey?.trim() + ? filterQuestionStimulusForBlock( + created.dynamic_payload, + q.dynamicFieldValues ?? {}, + ) + : created.dynamic_payload + } + if (q.stimulusBlockKey?.trim()) { + item.stimulus_block_key = q.stimulusBlockKey.trim() + } if (created.options?.length) item.options = created.options if (created.short_answers?.length) { item.short_answers = created.short_answers.map((entry) => @@ -674,11 +708,22 @@ export interface BuildPracticeFullUpdateInput { export function buildPracticeFullUpdateRequest( opts: BuildPracticeFullUpdateInput, ): UpdatePracticeFullRequest { - const err = validatePracticeQuestionsWithDefinitions( - opts.questions, - opts.definitions, - ) - if (err) throw new Error(err) + const useBlocks = isIeltsSharedStimulusMode(opts.formData.authoringProfile) + if (useBlocks) { + const blockValidationErr = validatePracticeStimulusBlocks( + opts.formData.authoringProfile, + opts.formData.stimulusBlocks, + opts.questions, + opts.definitions, + ) + if (blockValidationErr) throw new Error(blockValidationErr) + } else { + const err = validatePracticeQuestionsWithDefinitions( + opts.questions, + opts.definitions, + ) + if (err) throw new Error(err) + } const lessonTitle = opts.lessonDefaultTitle?.trim() || "Lesson practice" const practiceTitle = opts.isLearnEnglishLessonPractice @@ -748,6 +793,7 @@ export function buildPracticeFullUpdateRequest( persona_id: opts.personaId, quick_tips: opts.formData.tips.trim(), publish_status: opts.status, + authoring_profile: opts.formData.authoringProfile, }, question_set: { title: opts.isLearnEnglishLessonPractice @@ -762,6 +808,9 @@ export function buildPracticeFullUpdateRequest( status: opts.status, intro_video_url: opts.preservedQuestionSet.introVideoUrl.trim() || null, }, + stimulus_blocks: useBlocks + ? mapFormStimulusBlocksToApi(opts.formData.stimulusBlocks) + : [], questions, } } diff --git a/src/lib/practiceParentUnlink.ts b/src/lib/practiceParentUnlink.ts new file mode 100644 index 0000000..241331b --- /dev/null +++ b/src/lib/practiceParentUnlink.ts @@ -0,0 +1,73 @@ +import type { AxiosError } from "axios" +import { + unlinkExamPrepPracticeParent, + unlinkPracticeParent, +} from "../api/courses.api" +import type { ParentContextPractice, PracticeParent } from "../types/course.types" +import { normalizeParentContextPractice } from "./parentContextPractice" +import { formatPracticeParentLabel, parentsFromPractice } from "./practiceParents" + +export function unlinkParentConfirmMessage( + locationLabel: string, + options?: { isLastParent?: boolean }, +): string { + if (options?.isLastParent) { + return `Remove this practice from ${locationLabel}? It will not appear in any course, module, or lesson until re-attached. Questions are kept.` + } + return `Remove this practice from ${locationLabel}? The practice will remain available at other locations.` +} + +export function mapPracticeParentUnlinkError(err: unknown): string { + const ax = err as AxiosError<{ message?: string; error?: string }> + const status = ax.response?.status + const body = ax.response?.data + if (status === 403) { + return "You don't have permission to change practice locations." + } + if (status === 404) { + const msg = String(body?.message ?? body?.error ?? "").toLowerCase() + if (msg.includes("not linked")) { + return "This location was already removed." + } + return "Practice not found." + } + if (status === 400) { + return body?.message || body?.error || "Invalid location." + } + if (err instanceof Error && err.message.trim()) return err.message.trim() + return "Could not remove location." +} + +export function isPracticeParentUnlinkNotLinkedError(err: unknown): boolean { + const ax = err as AxiosError<{ message?: string; error?: string }> + if (ax.response?.status !== 404) return false + const msg = String(ax.response?.data?.message ?? ax.response?.data?.error ?? "").toLowerCase() + return msg.includes("not linked") +} + +export async function unlinkPracticeFromParent(opts: { + practiceId: number + parent: PracticeParent + isExamPrep?: boolean +}): Promise { + const res = opts.isExamPrep + ? await unlinkExamPrepPracticeParent(opts.practiceId, opts.parent) + : await unlinkPracticeParent(opts.practiceId, opts.parent) + const normalized = normalizeParentContextPractice(res.data?.data) + if (!normalized) { + throw new Error("Practice details were missing after unlink.") + } + return normalized +} + +export function parentsAfterUnlink(practice: ParentContextPractice): PracticeParent[] { + return parentsFromPractice(practice) +} + +export function contextualUnlinkLabel( + parent: PracticeParent, + contextLabel?: string, +): string { + if (contextLabel?.trim()) return contextLabel.trim() + return formatPracticeParentLabel(parent) +} diff --git a/src/lib/practiceStimulusBlocks.ts b/src/lib/practiceStimulusBlocks.ts new file mode 100644 index 0000000..a0660b9 --- /dev/null +++ b/src/lib/practiceStimulusBlocks.ts @@ -0,0 +1,325 @@ +import type { AuthoringProfile, PracticeStimulusBlock } from "../types/course.types" +import type { + DynamicElementInstance, + DynamicQuestionPayload, + QuestionTypeDefinition, +} from "../types/questionTypeDefinition.types" +import { buildDynamicQuestionPayload } from "./practiceDynamicQuestionPayload" +import { dynamicPayloadToFieldValues } from "./practiceDynamicQuestionPayload" +import { + validateDefinitionQuestion, + questionRowHasContent, + type LearnEnglishDefinitionQuestionInput, +} from "./learnEnglishDefinitionQuestion" +import { isNoInputComponentKind } from "./questionComponentKinds" +import { defaultLabelForKind } from "./schemaSlotLabel" + +export const BLOCK_KEY_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/ + +/** Stimulus kinds valid in practice-level blocks (no response kinds). */ +export const STIMULUS_BLOCK_KINDS = [ + "QUESTION_TEXT", + "PREP_TIME", + "INSTRUCTION", + "AUDIO_PROMPT", + "TEXT_PASSAGE", + "IMAGE", + "MATCHING_INPUTS", + "SELECT_MISSING_WORDS", + "TABLE", + "PDF_ATTACHMENT", +] as const + +export type StimulusBlockKind = (typeof STIMULUS_BLOCK_KINDS)[number] + +export interface PracticeFormStimulusBlockElement { + id: string + kind: string + fieldValue: string +} + +export interface PracticeFormStimulusBlock { + blockKey: string + displayOrder: number + elements: PracticeFormStimulusBlockElement[] +} + +export function isIeltsSharedStimulusMode(profile: AuthoringProfile | string | undefined): boolean { + return profile === "IELTS_SHARED_STIMULUS" +} + +export function normalizeAuthoringProfile(raw: unknown): AuthoringProfile { + const text = String(raw ?? "").trim().toUpperCase() + return text === "IELTS_SHARED_STIMULUS" ? "IELTS_SHARED_STIMULUS" : "STANDALONE" +} + +export function suggestBlockKey(existing: PracticeFormStimulusBlock[]): string { + let n = existing.length + 1 + let key = `section-${n}` + const keys = new Set(existing.map((b) => b.blockKey)) + while (keys.has(key)) { + n += 1 + key = `section-${n}` + } + return key +} + +export function suggestBlockElementId(kind: string, existing: PracticeFormStimulusBlockElement[]): string { + const base = kind.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_") + let n = 1 + let id = `${base}_${n}` + const ids = new Set(existing.map((e) => e.id)) + while (ids.has(id)) { + n += 1 + id = `${base}_${n}` + } + return id +} + +export function blockElementsFromStimulus( + stimulus: DynamicElementInstance[], +): PracticeFormStimulusBlockElement[] { + const fieldValues = dynamicPayloadToFieldValues({ stimulus, response: [] }) + return stimulus.map((el) => ({ + id: el.id, + kind: el.kind, + fieldValue: fieldValues[`stimulus:${el.id}`] ?? "", + })) +} + +export function buildBlockStimulusPayload( + elements: PracticeFormStimulusBlockElement[], +): DynamicElementInstance[] { + const stimulusRows = elements + .filter((e) => !isNoInputComponentKind(e.kind)) + .map((e) => ({ id: e.id, kind: e.kind })) + const fieldValues: Record = {} + for (const el of elements) { + fieldValues[`stimulus:${el.id}`] = el.fieldValue + } + return buildDynamicQuestionPayload({ + stimulusRows, + responseRows: [], + fieldValues, + }).stimulus +} + +export function mapApiStimulusBlocksToForm( + blocks: PracticeStimulusBlock[] | undefined, +): PracticeFormStimulusBlock[] { + return (blocks ?? []) + .slice() + .sort((a, b) => (a.display_order ?? 0) - (b.display_order ?? 0)) + .map((b, index) => ({ + blockKey: b.block_key, + displayOrder: b.display_order ?? index + 1, + elements: blockElementsFromStimulus(b.stimulus ?? []), + })) +} + +export function mapFormStimulusBlocksToApi( + blocks: PracticeFormStimulusBlock[], +): PracticeStimulusBlock[] { + return blocks.map((b, index) => ({ + block_key: b.blockKey.trim(), + display_order: b.displayOrder ?? index + 1, + stimulus: buildBlockStimulusPayload(b.elements), + })) +} + +export function validateStimulusBlocks(blocks: PracticeFormStimulusBlock[]): string | null { + const seen = new Set() + for (const block of blocks) { + const key = block.blockKey.trim() + if (!key) return "Block key is required." + if (!BLOCK_KEY_RE.test(key)) { + return `Invalid block key: ${block.blockKey}. Use letters, digits, underscores, and hyphens only.` + } + if (seen.has(key)) return `Duplicate block key: ${key}` + seen.add(key) + for (const el of block.elements) { + if (isNoInputComponentKind(el.kind)) continue + const kind = el.kind.trim().toUpperCase() + if (!STIMULUS_BLOCK_KINDS.includes(kind as StimulusBlockKind)) { + return `Invalid stimulus component kind in block "${key}": ${el.kind}` + } + } + } + return null +} + +export function validateStimulusBlockKeys( + blocks: PracticeFormStimulusBlock[], + questions: { stimulusBlockKey?: string | null }[], +): string | null { + const keys = new Set(blocks.map((b) => b.blockKey.trim())) + for (let i = 0; i < questions.length; i++) { + const key = questions[i].stimulusBlockKey?.trim() + if (!key) continue + if (!keys.has(key)) { + return `Question ${i + 1} references unknown stimulus block: ${key}` + } + } + return null +} + +export function getBlockStimulusByKey( + blocks: PracticeFormStimulusBlock[], + blockKey: string | null | undefined, +): DynamicElementInstance[] { + const key = blockKey?.trim() + if (!key) return [] + const block = blocks.find((b) => b.blockKey.trim() === key) + if (!block) return [] + return buildBlockStimulusPayload(block.elements) +} + +export function mergeEffectivePayload( + blockStimulus: DynamicElementInstance[], + questionPayload?: DynamicQuestionPayload | null, +): DynamicQuestionPayload { + const stimulus = [...blockStimulus] + const byId = new Map(stimulus.map((el, i) => [el.id?.trim(), i])) + for (const el of questionPayload?.stimulus ?? []) { + const id = el.id?.trim() + if (id && byId.has(id)) { + stimulus[byId.get(id)!] = el + } else { + stimulus.push(el) + } + } + return { + stimulus, + response: questionPayload?.response ?? [], + } +} + +export function mergeBlockStimulusIntoFieldValues( + def: QuestionTypeDefinition, + blockStimulus: DynamicElementInstance[], + questionFieldValues: Record, +): Record { + const merged = { ...(questionFieldValues ?? {}) } + const blockByKind = new Map() + const blockFieldValues = dynamicPayloadToFieldValues({ stimulus: blockStimulus, response: [] }) + + for (const el of blockStimulus) { + const kind = el.kind.trim().toUpperCase() + if (!blockByKind.has(kind)) blockByKind.set(kind, el) + } + + for (const row of def.stimulus_schema) { + const key = `stimulus:${row.id}` + if (merged[key]?.trim()) continue + const kind = row.kind.trim().toUpperCase() + const blockEl = blockByKind.get(kind) + if (blockEl) { + merged[key] = blockFieldValues[`stimulus:${blockEl.id}`] ?? "" + } + } + + for (const el of blockStimulus) { + const key = `stimulus:${el.id}` + const qVal = merged[key]?.trim() + if (!qVal) { + merged[key] = blockFieldValues[key] ?? "" + } + } + + return merged +} + +export function validateDefinitionQuestionWithBlock( + def: QuestionTypeDefinition, + q: LearnEnglishDefinitionQuestionInput, + index1Based: number, + blockStimulus: DynamicElementInstance[] | null, +): string | null { + if (!blockStimulus?.length) { + return validateDefinitionQuestion(def, q, index1Based) + } + const mergedFieldValues = mergeBlockStimulusIntoFieldValues( + def, + blockStimulus, + q.dynamicFieldValues ?? {}, + ) + return validateDefinitionQuestion( + def, + { ...q, dynamicFieldValues: mergedFieldValues }, + index1Based, + ) +} + +export function validatePracticeStimulusBlocks( + authoringProfile: AuthoringProfile, + blocks: PracticeFormStimulusBlock[], + questions: LearnEnglishDefinitionQuestionInput[], + definitions: QuestionTypeDefinition[], +): string | null { + if (!isIeltsSharedStimulusMode(authoringProfile)) return null + const blockErr = validateStimulusBlocks(blocks) + if (blockErr) return blockErr + const keyErr = validateStimulusBlockKeys(blocks, questions) + if (keyErr) return keyErr + const byId = new Map(definitions.map((d) => [d.id, d])) + const filled = questions.filter((q) => { + const def = byId.get(q.questionTypeDefinitionId) + return def ? questionRowHasContent(q, def) : false + }) + if (filled.length === 0) return "Add at least one question with content." + for (let i = 0; i < filled.length; i++) { + const q = filled[i] + const def = byId.get(q.questionTypeDefinitionId) + if (!def) { + return `Question ${i + 1}: type definition #${q.questionTypeDefinitionId} was not found. Refresh and try again.` + } + const blockStimulus = getBlockStimulusByKey(blocks, q.stimulusBlockKey) + const err = validateDefinitionQuestionWithBlock(def, q, i + 1, blockStimulus) + if (err) return err + } + return null +} + +export function filterQuestionStimulusForBlock( + payload: DynamicQuestionPayload, + questionFieldValues: Record, +): DynamicQuestionPayload { + const stimulus = payload.stimulus.filter((slot) => { + const raw = questionFieldValues[`stimulus:${slot.id}`] + return Boolean(raw?.trim()) + }) + return { ...payload, stimulus } +} + +export function countQuestionsReferencingBlock( + blockKey: string, + questions: { stimulusBlockKey?: string | null }[], +): number { + const key = blockKey.trim() + return questions.filter((q) => q.stimulusBlockKey?.trim() === key).length +} + +export function stimulusBlockKindLabel(kind: string): string { + return defaultLabelForKind(kind) +} + +export function createEmptyStimulusBlock( + existing: PracticeFormStimulusBlock[], +): PracticeFormStimulusBlock { + return { + blockKey: suggestBlockKey(existing), + displayOrder: existing.length + 1, + elements: [], + } +} + +export function createEmptyBlockElement( + kind: string, + existing: PracticeFormStimulusBlockElement[], +): PracticeFormStimulusBlockElement { + return { + id: suggestBlockElementId(kind, existing), + kind, + fieldValue: "", + } +} diff --git a/src/lib/questionTypeDefinitionPracticeEditPath.ts b/src/lib/questionTypeDefinitionPracticeEditPath.ts new file mode 100644 index 0000000..d811f3f --- /dev/null +++ b/src/lib/questionTypeDefinitionPracticeEditPath.ts @@ -0,0 +1,13 @@ +import { resolveExamPrepPracticeEditPath } from "./examPrepPracticeEditPath" +import { resolveLearnEnglishPracticeEditPath } from "./learnEnglishPracticeEditPath" +import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types" + +/** Routes to the LMS or exam-prep practice editor based on `practice_kind`. */ +export async function resolveQuestionTypeDefinitionPracticeEditPath( + practice: QuestionTypeDefinitionPractice, +): Promise { + if ((practice.practice_kind || "LMS").toUpperCase() === "EXAM_PREP") { + return resolveExamPrepPracticeEditPath(practice) + } + return resolveLearnEnglishPracticeEditPath(practice) +} diff --git a/src/lib/questionTypeDefinitionPractices.ts b/src/lib/questionTypeDefinitionPractices.ts new file mode 100644 index 0000000..ea4aeba --- /dev/null +++ b/src/lib/questionTypeDefinitionPractices.ts @@ -0,0 +1,41 @@ +import { dedupeParents, formatPracticeParentLabel } from "./practiceParents" +import type { PracticeParent } from "../types/course.types" +import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types" + +export function examPrepParentsFromPractice( + practice: Pick< + QuestionTypeDefinitionPractice, + "exam_prep_parents" | "exam_prep_lesson_id" + >, +): PracticeParent[] { + const parents = practice.exam_prep_parents ?? [] + if (parents.length > 0) return dedupeParents(parents) + const lessonId = practice.exam_prep_lesson_id + if (lessonId != null && lessonId > 0) { + return [{ parent_kind: "LESSON", parent_id: lessonId }] + } + return [] +} + +/** Single-line location for the practice meta row (e.g. "Course #2 · Lesson #42"). */ +export function formatPracticeLocation(row: QuestionTypeDefinitionPractice): string { + if ((row.practice_kind || "LMS").toUpperCase() === "EXAM_PREP") { + const parents = examPrepParentsFromPractice(row) + if (parents.length > 0) { + return parents.map(formatPracticeParentLabel).join(" · ") + } + return "Unlinked" + } + + const parents = row.parents ?? [] + if (parents.length > 0) { + return parents.map(formatPracticeParentLabel).join(" · ") + } + return "Unlinked" +} + +export function isQuestionTypeDefinitionPracticeUnlinked( + row: QuestionTypeDefinitionPractice, +): boolean { + return formatPracticeLocation(row) === "Unlinked" +} diff --git a/src/pages/content-management/AddPracticeFlow.tsx b/src/pages/content-management/AddPracticeFlow.tsx index b4a20a3..d415b72 100644 --- a/src/pages/content-management/AddPracticeFlow.tsx +++ b/src/pages/content-management/AddPracticeFlow.tsx @@ -19,6 +19,11 @@ import { validateLearnEnglishQuestionsWithDefinitions, } from "../../lib/learnEnglishPracticePublish"; import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator"; +import { syncStimulusBlocksAfterCreate } from "../../lib/practiceEditOrchestrator"; +import { + isIeltsSharedStimulusMode, + validatePracticeStimulusBlocks, +} from "../../lib/practiceStimulusBlocks"; import { buildCreatePracticeParentsPayload, dedupeParents, @@ -226,6 +231,8 @@ export function AddPracticeFlow() { storyImageUrl: "", shuffleQuestions: false, tips: "", + authoringProfile: "STANDALONE" as const, + stimulusBlocks: [] as import("../../lib/practiceStimulusBlocks").PracticeFormStimulusBlock[], parents: [] as { parent_kind: PracticeParentKind; parent_id: number }[], questions: [ { @@ -235,6 +242,7 @@ export function AddPracticeFlow() { associatedQuestionId: null as number | null, associatedAnchorRowId: null as string | null, prerequisiteQuestionIds: [] as number[], + stimulusBlockKey: null as string | null, questionTypeDefinitionId: null as number | null, text: "", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", @@ -389,6 +397,7 @@ export function AddPracticeFlow() { : index + 1, associatedQuestionId: q.associatedQuestionId ?? null, associatedAnchorRowId: q.associatedAnchorRowId ?? null, + stimulusBlockKey: q.stimulusBlockKey ?? null, dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) }, mcqOptions: (q.mcqOptions ?? []).map( (o: { text?: string; isCorrect?: boolean }) => ({ @@ -400,10 +409,14 @@ export function AddPracticeFlow() { shortAnswers: (q.shortAnswers ?? []).map((s: string) => String(s)), })); - const validationMsg = validateLearnEnglishQuestionsWithDefinitions( - mappedQuestions, - typeDefinitions, - ); + const validationMsg = isIeltsSharedStimulusMode(formData.authoringProfile) + ? validatePracticeStimulusBlocks( + formData.authoringProfile, + formData.stimulusBlocks, + mappedQuestions, + typeDefinitions, + ) + : validateLearnEnglishQuestionsWithDefinitions(mappedQuestions, typeDefinitions); if (validationMsg) { toast.error("Check your questions", { description: validationMsg }); return; @@ -438,7 +451,7 @@ export function AddPracticeFlow() { setSubmitting(true); try { - await executePracticeCreation({ + const { practiceId } = await executePracticeCreation({ parents: createParents, parentKind: parentContext?.kind, parentId: parentContext?.id, @@ -471,6 +484,25 @@ export function AddPracticeFlow() { questions: mappedQuestions, definitions: typeDefinitions, }); + if (isIeltsSharedStimulusMode(formData.authoringProfile)) { + await syncStimulusBlocksAfterCreate({ + practiceId, + isExamPrep, + status, + formData, + personaId, + preservedQuestionSet: { + timeLimitMinutes: null, + passingScore: null, + introVideoUrl: "", + status, + }, + questions: mappedQuestions, + definitions: typeDefinitions, + isLearnEnglishLessonPractice, + lessonDefaultTitle, + }); + } toast.success("Practice created successfully"); setIsPublished(true); } catch (e) { @@ -531,6 +563,9 @@ export function AddPracticeFlow() { storyImageUrl: "", shuffleQuestions: false, tips: "", + authoringProfile: "STANDALONE", + stimulusBlocks: [], + parents: [], questions: [ { id: "q1", @@ -539,6 +574,7 @@ export function AddPracticeFlow() { associatedQuestionId: null as number | null, associatedAnchorRowId: null as string | null, prerequisiteQuestionIds: [] as number[], + stimulusBlockKey: null as string | null, questionTypeDefinitionId: typeDefinitions[0]?.id ?? (null as number | null), text: "", diff --git a/src/pages/content-management/EditPracticeFlow.tsx b/src/pages/content-management/EditPracticeFlow.tsx index 3ac272d..ac78aeb 100644 --- a/src/pages/content-management/EditPracticeFlow.tsx +++ b/src/pages/content-management/EditPracticeFlow.tsx @@ -21,6 +21,10 @@ import { validateLearnEnglishQuestionsWithDefinitions, } from "../../lib/learnEnglishPracticePublish"; import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator"; +import { + isIeltsSharedStimulusMode, + validatePracticeStimulusBlocks, +} from "../../lib/practiceStimulusBlocks"; import { dedupeParents, formatPracticeParentsSummary, @@ -245,12 +249,17 @@ export function EditPracticeFlow() { storyImageUrl: "", shuffleQuestions: false, tips: "", + authoringProfile: "STANDALONE" as const, + stimulusBlocks: [] as import("../../lib/practiceStimulusBlocks").PracticeFormStimulusBlock[], parents: [] as PracticeParent[], questions: [ { id: "q1", displayOrder: 1, serverQuestionId: null as number | null, + associatedQuestionId: null as number | null, + associatedAnchorRowId: null as string | null, + stimulusBlockKey: null as string | null, questionTypeDefinitionId: null as number | null, text: "", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", @@ -374,6 +383,7 @@ export function EditPracticeFlow() { serverQuestionId: q.serverQuestionId ?? null, associatedQuestionId: q.associatedQuestionId ?? null, associatedAnchorRowId: q.associatedAnchorRowId ?? null, + stimulusBlockKey: q.stimulusBlockKey ?? null, dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) }, mcqOptions: (q.mcqOptions ?? []).map( (o: { text?: string; isCorrect?: boolean }) => ({ @@ -385,10 +395,14 @@ export function EditPracticeFlow() { shortAnswers: (q.shortAnswers ?? []).map((s: string) => String(s)), })); - const validationMsg = validateLearnEnglishQuestionsWithDefinitions( - mappedQuestions, - typeDefinitions, - ); + const validationMsg = isIeltsSharedStimulusMode(formData.authoringProfile) + ? validatePracticeStimulusBlocks( + formData.authoringProfile, + formData.stimulusBlocks, + mappedQuestions, + typeDefinitions, + ) + : validateLearnEnglishQuestionsWithDefinitions(mappedQuestions, typeDefinitions); if (validationMsg) { toast.error("Check your questions", { description: validationMsg }); return; @@ -542,6 +556,11 @@ export function EditPracticeFlow() { isExamPrepParents={isExamPrep} parentsOptional={isExamPrep} parentsCollapsedDefault={isExamPrep} + practiceId={practiceId} + onParentsUnlinked={(parents) => { + setFormData((fd) => ({ ...fd, parents })) + initialParentsRef.current = parents + }} /> ); case 2: diff --git a/src/pages/content-management/LessonPracticesPage.tsx b/src/pages/content-management/LessonPracticesPage.tsx index 4dce5b7..b19d648 100644 --- a/src/pages/content-management/LessonPracticesPage.tsx +++ b/src/pages/content-management/LessonPracticesPage.tsx @@ -21,6 +21,12 @@ import { setExamPrepPracticePublishStatus, setLearnEnglishPracticePublishStatus, } from "../../api/courses.api"; +import { parentsFromPractice } from "../../lib/practiceParents"; +import { + isPracticeParentUnlinkNotLinkedError, + mapPracticeParentUnlinkError, + unlinkPracticeFromParent, +} from "../../lib/practiceParentUnlink"; import { Badge } from "../../components/ui/badge"; import { Button } from "../../components/ui/button"; import { PracticeActionButton } from "./components/PracticeActionButton"; @@ -38,6 +44,7 @@ import type { GetExamPrepLessonPracticesResponse, GetPracticesByParentContextResponse, ParentContextPractice, + PracticeParent, PracticePublishStatus, } from "../../types/course.types"; import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip"; @@ -96,6 +103,7 @@ function PracticeCard({ index, total, onEdit, + onUnlink, onDelete, onTogglePublishStatus, publishStatusUpdating, @@ -104,6 +112,7 @@ function PracticeCard({ index: number; total: number; onEdit?: () => void; + onUnlink?: () => void; onDelete?: () => void; onTogglePublishStatus?: (nextStatus: PracticePublishStatus) => void; publishStatusUpdating?: boolean; @@ -167,6 +176,17 @@ function PracticeCard({ onToggle={onTogglePublishStatus} /> + {onUnlink ? ( + + ) : null} {onDelete ? ( + + + + + { @@ -646,13 +747,13 @@ export function LessonPracticesPage() { > - Delete this practice? + Delete this practice permanently?

{practiceToDelete?.title} {" "} - will be removed from this lesson. This action cannot be undone. + and all of its questions will be deleted. This cannot be undone.

+ + +
+
+ ) : null} + {lessonPracticeChoice && lessonPracticeChoicePaths ? ( (null) const [practiceToDelete, setPracticeToDelete] = useState(null) + const [practiceToUnlink, setPracticeToUnlink] = useState(null) const [deleting, setDeleting] = useState(false) + const [unlinking, setUnlinking] = useState(false) const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState(null) const [listSearch, setListSearch] = useState("") const [publishStatusFilter, setPublishStatusFilter] = useState("all") @@ -135,6 +144,38 @@ export function CatalogCoursePracticesPanel({ } } + const catalogParent = useMemo( + (): PracticeParent => ({ parent_kind: "CATALOG_COURSE", parent_id: catalogCourseId }), + [catalogCourseId], + ) + + const confirmUnlinkPractice = async () => { + if (!practiceToUnlink) return + setUnlinking(true) + try { + await unlinkPracticeFromParent({ + practiceId: practiceToUnlink.id, + parent: catalogParent, + isExamPrep: true, + }) + toast.success(`Practice removed from ${courseName}`) + setPracticeToUnlink(null) + await load() + } catch (e) { + if (isPracticeParentUnlinkNotLinkedError(e)) { + toast.info("This location was already removed.") + setPracticeToUnlink(null) + await load() + return + } + toast.error("Could not remove location", { + description: mapPracticeParentUnlinkError(e), + }) + } finally { + setUnlinking(false) + } + } + const confirmDeletePractice = async () => { if (!practiceToDelete) return setDeleting(true) @@ -214,23 +255,60 @@ export function CatalogCoursePracticesPanel({ onEdit={() => navigate(editPracticeHref(practice.id))} onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} + onUnlink={() => setPracticeToUnlink(practice)} onDelete={() => setPracticeToDelete(practice)} /> ))} )} + !open && !unlinking && setPracticeToUnlink(null)} + > + + + Remove from this catalog course? + +

+ + {practiceToUnlink?.title || "This practice"} + {" "} + will be detached from{" "} + {courseName}. + {practiceToUnlink && + parentsFromPractice(practiceToUnlink).filter( + (p) => + !( + p.parent_kind === catalogParent.parent_kind && + p.parent_id === catalogParent.parent_id + ), + ).length === 0 + ? " The practice will be unlinked until re-attached." + : " Other locations are unaffected."} +

+ + + + +
+
+ !open && setPracticeToDelete(null)}> - Delete practice? + Delete practice permanently?

This permanently removes{" "} {practiceToDelete?.title || "this practice"} - - . + {" "} + and all of its questions.

+ + +
+
+ !open && setPracticeToDelete(null)}> - Delete practice? + Delete practice permanently?

This permanently removes{" "} {practiceToDelete?.title || "this practice"} - - . + {" "} + and all of its questions.

) @@ -134,7 +225,7 @@ export function PracticeParentsField({ type="button" variant="outline" size="sm" - disabled={disabled} + disabled={disabled || Boolean(unlinkingKey)} onClick={addRow} className="rounded-[8px] border-grayScale-200 text-xs font-semibold" > diff --git a/src/pages/content-management/components/practice-steps/QuestionsStep.tsx b/src/pages/content-management/components/practice-steps/QuestionsStep.tsx index f2aad23..91b065c 100644 --- a/src/pages/content-management/components/practice-steps/QuestionsStep.tsx +++ b/src/pages/content-management/components/practice-steps/QuestionsStep.tsx @@ -48,6 +48,11 @@ import { import { cn } from "../../../../lib/utils"; import { toast } from "sonner"; import { QuestionAssociationField } from "./QuestionAssociationField"; +import { StimulusBlocksPanel } from "./StimulusBlocksPanel"; +import { + isIeltsSharedStimulusMode, + validatePracticeStimulusBlocks, +} from "../../../../lib/practiceStimulusBlocks"; function syncQuestionDisplayOrders( questions: T[], @@ -173,6 +178,7 @@ function createEmptyQuestionRow(id: string, displayOrder = 1, inheritAnchor?: { associatedQuestionId: inheritAnchor?.associatedQuestionId ?? null, associatedAnchorRowId: inheritAnchor?.associatedAnchorRowId ?? null, prerequisiteQuestionIds: [] as number[], + stimulusBlockKey: null as string | null, questionTypeDefinitionId: null as number | null, text: "", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", @@ -318,37 +324,83 @@ export function QuestionsStep({ setExpandedQuestionIds(new Set([id])); }; - const renderTypeSpecificFields = (q: any, i: number, def: QuestionTypeDefinition) => { + const renderTypeSpecificFields = ( + q: any, + i: number, + def: QuestionTypeDefinition, + options?: { responseOnly?: boolean }, + ) => { + const responseOnly = Boolean(options?.responseOnly); if (definitionUsesDynamicPayload(def)) { return (

- Image, audio, and PDF use upload or URL.{" "} - Table uses the visual table builder. Timer and - prep-time slots use seconds. Other slots use text or structured JSON where noted. + {responseOnly ? ( + <> + Shared stimulus comes from the linked block. Edit{" "} + response fields below. + Use overrides only when this question needs different stimulus than the block. + + ) : ( + <> + Image, audio, and PDF use upload or URL.{" "} + Table uses the visual table builder. Timer and + prep-time slots use seconds. Other slots use text or structured JSON where noted. + + )}

- {def.stimulus_schema.length > 0 ? ( -
-

Stimulus

- {def.stimulus_schema.map((row) => ( -
- - setDynamicValue(i, `stimulus:${row.id}`, next) - } - allFieldValues={q.dynamicFieldValues} - stimulusSchema={def.stimulus_schema} - responseSchema={def.response_schema} - /> -
- ))} -
+ {!responseOnly ? ( + def.stimulus_schema.length > 0 ? ( +
+

+ Stimulus +

+ {def.stimulus_schema.map((row) => ( +
+ + setDynamicValue(i, `stimulus:${row.id}`, next) + } + allFieldValues={q.dynamicFieldValues} + stimulusSchema={def.stimulus_schema} + responseSchema={def.response_schema} + /> +
+ ))} +
+ ) : null + ) : def.stimulus_schema.length > 0 ? ( +
+ + Override block stimulus for this question (optional) + +
+ {def.stimulus_schema.map((row) => ( +
+ + setDynamicValue(i, `stimulus:${row.id}`, next) + } + allFieldValues={q.dynamicFieldValues} + stimulusSchema={def.stimulus_schema} + responseSchema={def.response_schema} + /> +
+ ))} +
+
) : null} {def.response_schema.length > 0 ? (
@@ -535,17 +587,41 @@ export function QuestionsStep({ ); }; + const ieltsMode = isIeltsSharedStimulusMode(formData.authoringProfile); + return (

Questions

- Choose a question type for each item, then fill in the fields that type requires. + {ieltsMode + ? "Create shared stimulus blocks, link questions to a block, then fill in each question's response fields." + : "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.

+ {ieltsMode ? ( +
+ setFormData({ ...formData, stimulusBlocks })} + onClearQuestionBlockKeys={(blockKey) => { + setFormData({ + ...formData, + questions: formData.questions.map((row: { stimulusBlockKey?: string | null }) => + row.stimulusBlockKey?.trim() === blockKey.trim() + ? { ...row, stimulusBlockKey: null } + : row, + ), + }); + }} + /> +
+ ) : null} + {formData.questions.length > 1 ? (
+ +
+ + {expanded ? ( +
+
+ + + updateBlock(blockIndex, { blockKey: e.target.value }) + } + className="font-mono text-sm" + placeholder="section-1" + /> +
+ +
+

+ Shared stimulus +

+ {block.elements.map((element, elementIndex) => { + const presentation = getStimulusKindPresentation(element.kind) + const fieldValues: Record = { + [`stimulus:${element.id}`]: element.fieldValue, + } + return ( +
+
+
+ + {presentation.label} + + {element.id} + +
+ +
+ { + const elements = [...block.elements] + elements[elementIndex] = { + ...elements[elementIndex], + fieldValue: next, + } + updateBlock(blockIndex, { elements }) + }} + allFieldValues={fieldValues} + stimulusSchema={block.elements.map((el) => ({ + id: el.id, + kind: el.kind, + }))} + responseSchema={[]} + /> +
+ ) + })} + +
+ +
+
+
+ ) : null} + + ) + })} +
+ + +
+ ) +} diff --git a/src/types/course.types.ts b/src/types/course.types.ts index 9953f33..b87967f 100644 --- a/src/types/course.types.ts +++ b/src/types/course.types.ts @@ -762,16 +762,27 @@ export interface UpdatePracticeParentsResponse { metadata: unknown | null } +export type AuthoringProfile = "STANDALONE" | "IELTS_SHARED_STIMULUS" + +export interface PracticeStimulusBlock { + id?: number + block_key: string + display_order: number + stimulus: import("./questionTypeDefinition.types").DynamicElementInstance[] +} + /** Question row in GET/PUT /practices/:id/full and /exam-prep/practices/:id/full. */ export interface PracticeFullQuestionItem { id?: number | null display_order: number associated_question_id?: number | null prerequisite_question_ids?: number[] + stimulus_block_key?: string | null question_text?: string question_type: string question_type_definition_id?: number | null dynamic_payload?: DynamicQuestionPayload | null + effective_dynamic_payload?: DynamicQuestionPayload | null difficulty_level?: string points?: number status?: PracticePublishStatus | string @@ -810,6 +821,7 @@ export interface PracticeFullPractice { story_image?: string persona_id?: number | null question_set_id: number + authoring_profile?: AuthoringProfile | string | null publish_status?: PracticePublishStatus | string | null quick_tips?: string parents?: PracticeParent[] @@ -825,6 +837,7 @@ export interface PracticeFullPractice { export interface PracticeFullData { practice: PracticeFullPractice question_set: PracticeFullQuestionSet + stimulus_blocks?: PracticeStimulusBlock[] questions: PracticeFullQuestionItem[] } @@ -836,6 +849,12 @@ export interface GetPracticeFullResponse { metadata: unknown | null } +export interface UpdatePracticeFullStimulusBlockItem { + block_key: string + display_order?: number + stimulus: import("./questionTypeDefinition.types").DynamicElementInstance[] +} + export interface UpdatePracticeFullRequest { practice: { title: string @@ -844,6 +863,7 @@ export interface UpdatePracticeFullRequest { persona_id: number quick_tips: string publish_status: PracticePublishStatus + authoring_profile?: AuthoringProfile } question_set: { title: string @@ -854,6 +874,7 @@ export interface UpdatePracticeFullRequest { status: PracticePublishStatus intro_video_url?: string | null } + stimulus_blocks?: UpdatePracticeFullStimulusBlockItem[] questions: PracticeFullQuestionItem[] } diff --git a/src/types/questionTypeDefinition.types.ts b/src/types/questionTypeDefinition.types.ts index b5ec248..a9d33f1 100644 --- a/src/types/questionTypeDefinition.types.ts +++ b/src/types/questionTypeDefinition.types.ts @@ -61,17 +61,25 @@ export interface DynamicQuestionPayload { response: DynamicElementInstance[] } +export type QuestionTypeDefinitionPracticeKind = "LMS" | "EXAM_PREP" + /** Row from GET /questions/type-definitions/:id/practices */ export interface QuestionTypeDefinitionPractice { - practice_kind: string + practice_kind: QuestionTypeDefinitionPracticeKind practice_id: number question_set_id: number title: string story_description?: string story_image?: string + persona_id?: number quick_tips?: string - publish_status?: string + publish_status?: "DRAFT" | "PUBLISHED" | string + /** LMS hierarchy links — read when `practice_kind === "LMS"`. */ parents: PracticeParent[] | null + /** Exam-prep hierarchy links — read when `practice_kind === "EXAM_PREP"`. */ + exam_prep_parents?: PracticeParent[] | null + /** Legacy convenience when a LESSON parent exists; prefer `exam_prep_parents`. */ + exam_prep_lesson_id?: number | null /** @deprecated use parents[] */ parent_kind?: string /** @deprecated use parents[] */