Integrate practice stimulus blocks, parent unlink, and question-type practice listing.

Add IELTS shared stimulus authoring, per-parent unlink APIs and UI, and fix question-type practice modal to show LMS/exam-prep locations and edit routes correctly.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-02 04:59:28 -07:00
parent 8294b3fcf4
commit 5df5a7f742
26 changed files with 2120 additions and 148 deletions

View File

@ -125,6 +125,7 @@ import type {
UpdateParentLinkedPracticeResponse, UpdateParentLinkedPracticeResponse,
UpdatePracticeParentsRequest, UpdatePracticeParentsRequest,
UpdatePracticeParentsResponse, UpdatePracticeParentsResponse,
PracticeParent,
PublishParentLinkedPracticeRequest, PublishParentLinkedPracticeRequest,
PublishStatusOnlyRequest, PublishStatusOnlyRequest,
AccessTierOnlyRequest, AccessTierOnlyRequest,
@ -732,6 +733,15 @@ export const updateExamPrepPracticeParents = (
data, data,
) )
/** DELETE /exam-prep/practices/:id/parents/:parentKind/:parentId — unlink one parent. */
export const unlinkExamPrepPracticeParent = (
practiceId: number,
parent: PracticeParent,
) =>
http.delete<UpdatePracticeParentsResponse>(
`/exam-prep/practices/${practiceId}/parents/${parent.parent_kind.toUpperCase()}/${parent.parent_id}`,
)
/** DELETE /exam-prep/practices/:practiceId */ /** DELETE /exam-prep/practices/:practiceId */
export const deleteExamPrepPractice = (practiceId: number) => export const deleteExamPrepPractice = (practiceId: number) =>
http.delete<{ message: string; success: boolean; status_code: number; metadata: unknown }>( http.delete<{ message: string; success: boolean; status_code: number; metadata: unknown }>(
@ -924,6 +934,15 @@ export const updatePracticeParents = (
data: UpdatePracticeParentsRequest, data: UpdatePracticeParentsRequest,
) => http.put<UpdatePracticeParentsResponse>(`/practices/${practiceId}/parents`, data) ) => http.put<UpdatePracticeParentsResponse>(`/practices/${practiceId}/parents`, data)
/** DELETE /practices/:id/parents/:parentKind/:parentId — unlink one parent. */
export const unlinkPracticeParent = (
practiceId: number,
parent: PracticeParent,
) =>
http.delete<UpdatePracticeParentsResponse>(
`/practices/${practiceId}/parents/${parent.parent_kind.toUpperCase()}/${parent.parent_id}`,
)
/** PUT /practices/:id */ /** PUT /practices/:id */
export const updateParentLinkedPractice = ( export const updateParentLinkedPractice = (
practiceId: number, practiceId: number,

View File

@ -12,7 +12,13 @@ import type {
ValidateQuestionTypeDefinitionResult, ValidateQuestionTypeDefinitionResult,
} from "../types/questionTypeDefinition.types" } from "../types/questionTypeDefinition.types"
import { normalizeGroupIds } from "../lib/questionTypeGroupIds" 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<T> { interface ApiEnvelope<T> {
message?: string message?: string
@ -436,6 +442,15 @@ export async function deleteQuestionTypeDefinition(id: number) {
return http.delete<ApiEnvelope<unknown>>(`/questions/type-definitions/${id}`) return http.delete<ApiEnvelope<unknown>>(`/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 { function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice | null {
if (!row || typeof row !== "object") return null if (!row || typeof row !== "object") return null
const o = row as Record<string, unknown> const o = row as Record<string, unknown>
@ -473,14 +488,36 @@ function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice
const course_id = Number(o.course_id ?? o.CourseId ?? o.courseId) const course_id = Number(o.course_id ?? o.CourseId ?? o.courseId)
const module_id = Number(o.module_id ?? o.ModuleId ?? o.moduleId) const module_id = Number(o.module_id ?? o.ModuleId ?? o.moduleId)
const lesson_id = Number(o.lesson_id ?? o.LessonId ?? o.lessonId) const lesson_id = Number(o.lesson_id ?? o.LessonId ?? o.lessonId)
const parents = parentsFromPractice({ 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), parents: normalizePracticeParents(row),
parent_kind, parent_kind,
parent_id, 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 { return {
practice_kind: asStr(o.practice_kind ?? o.PracticeKind ?? o.practiceKind ?? "LMS"), practice_kind: isExamPrep ? "EXAM_PREP" : "LMS",
practice_id, practice_id,
question_set_id, question_set_id,
title: asStr(o.title ?? o.Title) || `Practice #${practice_id}`, title: asStr(o.title ?? o.Title) || `Practice #${practice_id}`,
@ -504,8 +541,11 @@ function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice
: undefined, : undefined,
publish_status: asStr(o.publish_status ?? o.PublishStatus ?? o.publishStatus) || undefined, publish_status: asStr(o.publish_status ?? o.PublishStatus ?? o.publishStatus) || undefined,
parents, parents,
parent_kind: parents[0]?.parent_kind, exam_prep_parents,
parent_id: parents[0]?.parent_id, 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, program_id: Number.isFinite(program_id) && program_id > 0 ? program_id : undefined,
course_id: Number.isFinite(course_id) && course_id > 0 ? course_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, module_id: Number.isFinite(module_id) && module_id > 0 ? module_id : undefined,
@ -592,7 +632,7 @@ function parsePracticesPage(
/** /**
* GET /questions/type-definitions/:id/practices * 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( export async function getQuestionTypeDefinitionPractices(
definitionId: number, definitionId: number,

View File

@ -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<T>(
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
key: string,
): T[] {
const body = res.data?.data ?? res.data?.Data
if (!body || typeof body !== "object") return []
const record = body as Record<string, unknown>
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<string, unknown>; Data?: Record<string, unknown> } },
): number | undefined {
const body = res.data?.data ?? res.data?.Data
if (!body || typeof body !== "object") return undefined
const record = body as Record<string, unknown>
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<ExamPrepCatalogCourseItem[]> {
const all: ExamPrepCatalogCourseItem[] = []
let offset = 0
while (true) {
const res = await getExamPrepCatalogCourses({ limit: PAGE_SIZE, offset })
const page = listFromEnvelope<ExamPrepCatalogCourseItem>(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<ExamPrepCatalogUnitItem[]> {
const all: ExamPrepCatalogUnitItem[] = []
let offset = 0
while (true) {
const res = await getExamPrepCatalogUnits(catalogCourseId, { limit: PAGE_SIZE, offset })
const page = listFromEnvelope<ExamPrepCatalogUnitItem>(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<ExamPrepUnitModuleItem[]> {
const all: ExamPrepUnitModuleItem[] = []
let offset = 0
while (true) {
const res = await getExamPrepUnitModules(unitId, { limit: PAGE_SIZE, offset })
const page = listFromEnvelope<ExamPrepUnitModuleItem>(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<ExamPrepModuleLessonItem[]> {
const all: ExamPrepModuleLessonItem[] = []
let offset = 0
while (true) {
const res = await getExamPrepModuleLessons(moduleId, { limit: PAGE_SIZE, offset })
const page = listFromEnvelope<ExamPrepModuleLessonItem>(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<boolean> {
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<ExamPrepParentTab | null> {
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<string | null> {
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<string | null> {
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<string | null> {
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<QuestionTypeDefinitionPractice> {
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<string | null> {
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
}

View File

@ -193,6 +193,7 @@ export interface LearnEnglishDefinitionQuestionInput {
associatedQuestionId?: number | null associatedQuestionId?: number | null
associatedAnchorRowId?: string | null associatedAnchorRowId?: string | null
prerequisiteQuestionIds?: number[] prerequisiteQuestionIds?: number[]
stimulusBlockKey?: string | null
displayOrder?: number displayOrder?: number
mcqOptions?: { option_text: string; is_correct: boolean }[] mcqOptions?: { option_text: string; is_correct: boolean }[]
trueFalseAnswerIsTrue?: boolean trueFalseAnswerIsTrue?: boolean

View File

@ -27,6 +27,7 @@ import {
multipleChoiceSlotHasContent, multipleChoiceSlotHasContent,
normalizeMultipleChoiceValue, normalizeMultipleChoiceValue,
parseMultipleChoiceSlotValue, parseMultipleChoiceSlotValue,
serializeMultipleChoiceSlotValue,
} from "./multipleChoiceSlotValue" } from "./multipleChoiceSlotValue"
import { isNoInputComponentKind } from "./questionComponentKinds" import { isNoInputComponentKind } from "./questionComponentKinds"
@ -163,6 +164,38 @@ function slotValueForRow(
return parseDynamicSlotValue(rawField) 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<string, string> {
const out: Record<string, string> = {}
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: { export function buildDynamicQuestionPayload(input: {
stimulusRows: { id: string; kind: string }[] stimulusRows: { id: string; kind: string }[]
responseRows: { id: string; kind: string }[] responseRows: { id: string; kind: string }[]

View File

@ -1,4 +1,6 @@
import { import {
getExamPrepPracticeFull,
getLearnEnglishPracticeFull,
updateExamPrepPracticeFull, updateExamPrepPracticeFull,
updateExamPrepPracticeParents, updateExamPrepPracticeParents,
updateLearnEnglishPracticeFull, updateLearnEnglishPracticeFull,
@ -9,10 +11,12 @@ import type { QuestionTypeDefinition } from "../types/questionTypeDefinition.typ
import { dedupeParents } from "./practiceParents" import { dedupeParents } from "./practiceParents"
import { import {
buildPracticeFullUpdateRequest, buildPracticeFullUpdateRequest,
unwrapPracticeFullData,
type PracticeFormState, type PracticeFormState,
type PreservedQuestionSetFields, type PreservedQuestionSetFields,
type PracticeEditQuestionInput, type PracticeEditQuestionInput,
} from "./practiceFullMapper" } from "./practiceFullMapper"
import { isIeltsSharedStimulusMode } from "./practiceStimulusBlocks"
export interface PracticeEditInput { export interface PracticeEditInput {
practiceId: number 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<void> {
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)
}

View File

@ -6,6 +6,7 @@ import type {
PracticeFullQuestionSet, PracticeFullQuestionSet,
PracticeParent, PracticeParent,
PracticePublishStatus, PracticePublishStatus,
AuthoringProfile,
QuestionOption, QuestionOption,
QuestionShortAnswer, QuestionShortAnswer,
UpdatePracticeFullRequest, UpdatePracticeFullRequest,
@ -24,9 +25,23 @@ import {
questionRowHasContent, questionRowHasContent,
type LearnEnglishDefinitionQuestionInput, type LearnEnglishDefinitionQuestionInput,
} from "./learnEnglishDefinitionQuestion" } from "./learnEnglishDefinitionQuestion"
import { serializeMultipleChoiceSlotValue } from "./multipleChoiceSlotValue"
import { normalizePracticeParents, parentsFromPractice } from "./practiceParents" import { normalizePracticeParents, parentsFromPractice } from "./practiceParents"
import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator" import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator"
import {
dynamicPayloadToFieldValues,
slotApiValueToFieldString,
} from "./practiceDynamicQuestionPayload"
import {
filterQuestionStimulusForBlock,
getBlockStimulusByKey,
isIeltsSharedStimulusMode,
mapApiStimulusBlocksToForm,
mapFormStimulusBlocksToApi,
normalizeAuthoringProfile,
validatePracticeStimulusBlocks,
validateStimulusBlocks,
type PracticeFormStimulusBlock,
} from "./practiceStimulusBlocks"
import { import {
resolveAssociatedQuestionId, resolveAssociatedQuestionId,
validateQuestionAssociations, validateQuestionAssociations,
@ -39,6 +54,7 @@ export interface PracticeFormQuestionRow {
associatedQuestionId: number | null associatedQuestionId: number | null
associatedAnchorRowId: string | null associatedAnchorRowId: string | null
prerequisiteQuestionIds?: number[] prerequisiteQuestionIds?: number[]
stimulusBlockKey: string | null
questionTypeDefinitionId: number | null questionTypeDefinitionId: number | null
text: string text: string
difficultyLevel: "EASY" | "MEDIUM" | "HARD" difficultyLevel: "EASY" | "MEDIUM" | "HARD"
@ -55,6 +71,8 @@ export interface PracticeFormState {
storyImageUrl: string storyImageUrl: string
shuffleQuestions: boolean shuffleQuestions: boolean
tips: string tips: string
authoringProfile: AuthoringProfile
stimulusBlocks: PracticeFormStimulusBlock[]
parents: PracticeParent[] parents: PracticeParent[]
questions: PracticeFormQuestionRow[] questions: PracticeFormQuestionRow[]
} }
@ -232,6 +250,15 @@ export function normalizePracticeFullQuestion(
dynamic_payload: normalizeDynamicPayload( dynamic_payload: normalizeDynamicPayload(
record.dynamic_payload ?? record.DynamicPayload, 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: difficulty_level:
pickStr(record, "difficulty_level", "DifficultyLevel", "difficultyLevel") || pickStr(record, "difficulty_level", "DifficultyLevel", "difficultyLevel") ||
undefined, undefined,
@ -322,6 +349,9 @@ function normalizePracticeFullPractice(raw: unknown): PracticeFullPractice | nul
pickStr(record, "story_image", "StoryImage", "storyImage") || undefined, pickStr(record, "story_image", "StoryImage", "storyImage") || undefined,
persona_id: pickNum(record, "persona_id", "PersonaId", "personaId"), persona_id: pickNum(record, "persona_id", "PersonaId", "personaId"),
question_set_id: questionSetId, question_set_id: questionSetId,
authoring_profile: normalizeAuthoringProfile(
record.authoring_profile ?? record.AuthoringProfile,
),
publish_status: publish_status:
pickStr(record, "publish_status", "PublishStatus", "publishStatus") || null, pickStr(record, "publish_status", "PublishStatus", "publishStatus") || null,
quick_tips: pickStr(record, "quick_tips", "QuickTips", "quickTips") || undefined, quick_tips: pickStr(record, "quick_tips", "QuickTips", "quickTips") || undefined,
@ -348,7 +378,29 @@ export function normalizePracticeFullData(raw: unknown): PracticeFullData | null
const questions = questionsRaw const questions = questionsRaw
.map((entry) => normalizePracticeFullQuestion(entry)) .map((entry) => normalizePracticeFullQuestion(entry))
.filter((entry): entry is PracticeFullQuestionItem => entry != null) .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<typeof entry> => entry != null)
: undefined
return { practice, question_set: questionSet, questions, stimulus_blocks }
} }
function payloadValuesByKind( function payloadValuesByKind(
@ -410,38 +462,6 @@ function hydrateDynamicFieldValues(
return merged 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<string, string> {
const out: Record<string, string> = {}
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( function normalizeShortAnswers(
shortAnswers: PracticeFullQuestionItem["short_answers"], shortAnswers: PracticeFullQuestionItem["short_answers"],
): string[] { ): string[] {
@ -531,6 +551,7 @@ function mapFullQuestionToFormRow(
associatedQuestionId: q.associated_question_id ?? null, associatedQuestionId: q.associated_question_id ?? null,
associatedAnchorRowId: null, associatedAnchorRowId: null,
prerequisiteQuestionIds: q.prerequisite_question_ids, prerequisiteQuestionIds: q.prerequisite_question_ids,
stimulusBlockKey: q.stimulus_block_key ?? null,
questionTypeDefinitionId: defId, questionTypeDefinitionId: defId,
text, text,
difficultyLevel, difficultyLevel,
@ -553,7 +574,7 @@ export function mapPracticeFullToFormState(
preservedQuestionSet: PreservedQuestionSetFields preservedQuestionSet: PreservedQuestionSetFields
parents: PracticeParent[] parents: PracticeParent[]
} { } {
const { practice, question_set, questions } = data const { practice, question_set, questions, stimulus_blocks } = data
const sorted = [...questions].sort( const sorted = [...questions].sort(
(a, b) => (a.display_order ?? 0) - (b.display_order ?? 0), (a, b) => (a.display_order ?? 0) - (b.display_order ?? 0),
) )
@ -568,6 +589,7 @@ export function mapPracticeFullToFormState(
serverQuestionId: null, serverQuestionId: null,
associatedQuestionId: null, associatedQuestionId: null,
associatedAnchorRowId: null, associatedAnchorRowId: null,
stimulusBlockKey: null,
questionTypeDefinitionId: typeDefinitions[0]?.id ?? null, questionTypeDefinitionId: typeDefinitions[0]?.id ?? null,
text: "", text: "",
difficultyLevel: "EASY" as const, difficultyLevel: "EASY" as const,
@ -591,6 +613,8 @@ export function mapPracticeFullToFormState(
storyImageUrl: practice.story_image?.trim() || "", storyImageUrl: practice.story_image?.trim() || "",
shuffleQuestions: Boolean(question_set.shuffle_questions), shuffleQuestions: Boolean(question_set.shuffle_questions),
tips: practice.quick_tips?.trim() || "", tips: practice.quick_tips?.trim() || "",
authoringProfile: normalizeAuthoringProfile(practice.authoring_profile),
stimulusBlocks: mapApiStimulusBlocksToForm(stimulus_blocks),
parents: parentsFromPractice(practice), parents: parentsFromPractice(practice),
questions: formQuestions, questions: formQuestions,
}, },
@ -638,7 +662,17 @@ function buildFullUpdateQuestion(
if (created.question_type_definition_id != null) { if (created.question_type_definition_id != null) {
item.question_type_definition_id = created.question_type_definition_id 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.options?.length) item.options = created.options
if (created.short_answers?.length) { if (created.short_answers?.length) {
item.short_answers = created.short_answers.map((entry) => item.short_answers = created.short_answers.map((entry) =>
@ -674,11 +708,22 @@ export interface BuildPracticeFullUpdateInput {
export function buildPracticeFullUpdateRequest( export function buildPracticeFullUpdateRequest(
opts: BuildPracticeFullUpdateInput, opts: BuildPracticeFullUpdateInput,
): UpdatePracticeFullRequest { ): UpdatePracticeFullRequest {
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( const err = validatePracticeQuestionsWithDefinitions(
opts.questions, opts.questions,
opts.definitions, opts.definitions,
) )
if (err) throw new Error(err) if (err) throw new Error(err)
}
const lessonTitle = opts.lessonDefaultTitle?.trim() || "Lesson practice" const lessonTitle = opts.lessonDefaultTitle?.trim() || "Lesson practice"
const practiceTitle = opts.isLearnEnglishLessonPractice const practiceTitle = opts.isLearnEnglishLessonPractice
@ -748,6 +793,7 @@ export function buildPracticeFullUpdateRequest(
persona_id: opts.personaId, persona_id: opts.personaId,
quick_tips: opts.formData.tips.trim(), quick_tips: opts.formData.tips.trim(),
publish_status: opts.status, publish_status: opts.status,
authoring_profile: opts.formData.authoringProfile,
}, },
question_set: { question_set: {
title: opts.isLearnEnglishLessonPractice title: opts.isLearnEnglishLessonPractice
@ -762,6 +808,9 @@ export function buildPracticeFullUpdateRequest(
status: opts.status, status: opts.status,
intro_video_url: opts.preservedQuestionSet.introVideoUrl.trim() || null, intro_video_url: opts.preservedQuestionSet.introVideoUrl.trim() || null,
}, },
stimulus_blocks: useBlocks
? mapFormStimulusBlocksToApi(opts.formData.stimulusBlocks)
: [],
questions, questions,
} }
} }

View File

@ -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<ParentContextPractice> {
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)
}

View File

@ -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<string, string> = {}
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<string>()
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<string, string>,
): Record<string, string> {
const merged = { ...(questionFieldValues ?? {}) }
const blockByKind = new Map<string, DynamicElementInstance>()
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<string, string>,
): 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: "",
}
}

View File

@ -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<string | null> {
if ((practice.practice_kind || "LMS").toUpperCase() === "EXAM_PREP") {
return resolveExamPrepPracticeEditPath(practice)
}
return resolveLearnEnglishPracticeEditPath(practice)
}

View File

@ -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"
}

View File

@ -19,6 +19,11 @@ import {
validateLearnEnglishQuestionsWithDefinitions, validateLearnEnglishQuestionsWithDefinitions,
} from "../../lib/learnEnglishPracticePublish"; } from "../../lib/learnEnglishPracticePublish";
import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator"; import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator";
import { syncStimulusBlocksAfterCreate } from "../../lib/practiceEditOrchestrator";
import {
isIeltsSharedStimulusMode,
validatePracticeStimulusBlocks,
} from "../../lib/practiceStimulusBlocks";
import { import {
buildCreatePracticeParentsPayload, buildCreatePracticeParentsPayload,
dedupeParents, dedupeParents,
@ -226,6 +231,8 @@ export function AddPracticeFlow() {
storyImageUrl: "", storyImageUrl: "",
shuffleQuestions: false, shuffleQuestions: false,
tips: "", tips: "",
authoringProfile: "STANDALONE" as const,
stimulusBlocks: [] as import("../../lib/practiceStimulusBlocks").PracticeFormStimulusBlock[],
parents: [] as { parent_kind: PracticeParentKind; parent_id: number }[], parents: [] as { parent_kind: PracticeParentKind; parent_id: number }[],
questions: [ questions: [
{ {
@ -235,6 +242,7 @@ export function AddPracticeFlow() {
associatedQuestionId: null as number | null, associatedQuestionId: null as number | null,
associatedAnchorRowId: null as string | null, associatedAnchorRowId: null as string | null,
prerequisiteQuestionIds: [] as number[], prerequisiteQuestionIds: [] as number[],
stimulusBlockKey: null as string | null,
questionTypeDefinitionId: null as number | null, questionTypeDefinitionId: null as number | null,
text: "", text: "",
difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD",
@ -389,6 +397,7 @@ export function AddPracticeFlow() {
: index + 1, : index + 1,
associatedQuestionId: q.associatedQuestionId ?? null, associatedQuestionId: q.associatedQuestionId ?? null,
associatedAnchorRowId: q.associatedAnchorRowId ?? null, associatedAnchorRowId: q.associatedAnchorRowId ?? null,
stimulusBlockKey: q.stimulusBlockKey ?? null,
dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) }, dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) },
mcqOptions: (q.mcqOptions ?? []).map( mcqOptions: (q.mcqOptions ?? []).map(
(o: { text?: string; isCorrect?: boolean }) => ({ (o: { text?: string; isCorrect?: boolean }) => ({
@ -400,10 +409,14 @@ export function AddPracticeFlow() {
shortAnswers: (q.shortAnswers ?? []).map((s: string) => String(s)), shortAnswers: (q.shortAnswers ?? []).map((s: string) => String(s)),
})); }));
const validationMsg = validateLearnEnglishQuestionsWithDefinitions( const validationMsg = isIeltsSharedStimulusMode(formData.authoringProfile)
? validatePracticeStimulusBlocks(
formData.authoringProfile,
formData.stimulusBlocks,
mappedQuestions, mappedQuestions,
typeDefinitions, typeDefinitions,
); )
: validateLearnEnglishQuestionsWithDefinitions(mappedQuestions, typeDefinitions);
if (validationMsg) { if (validationMsg) {
toast.error("Check your questions", { description: validationMsg }); toast.error("Check your questions", { description: validationMsg });
return; return;
@ -438,7 +451,7 @@ export function AddPracticeFlow() {
setSubmitting(true); setSubmitting(true);
try { try {
await executePracticeCreation({ const { practiceId } = await executePracticeCreation({
parents: createParents, parents: createParents,
parentKind: parentContext?.kind, parentKind: parentContext?.kind,
parentId: parentContext?.id, parentId: parentContext?.id,
@ -471,6 +484,25 @@ export function AddPracticeFlow() {
questions: mappedQuestions, questions: mappedQuestions,
definitions: typeDefinitions, 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"); toast.success("Practice created successfully");
setIsPublished(true); setIsPublished(true);
} catch (e) { } catch (e) {
@ -531,6 +563,9 @@ export function AddPracticeFlow() {
storyImageUrl: "", storyImageUrl: "",
shuffleQuestions: false, shuffleQuestions: false,
tips: "", tips: "",
authoringProfile: "STANDALONE",
stimulusBlocks: [],
parents: [],
questions: [ questions: [
{ {
id: "q1", id: "q1",
@ -539,6 +574,7 @@ export function AddPracticeFlow() {
associatedQuestionId: null as number | null, associatedQuestionId: null as number | null,
associatedAnchorRowId: null as string | null, associatedAnchorRowId: null as string | null,
prerequisiteQuestionIds: [] as number[], prerequisiteQuestionIds: [] as number[],
stimulusBlockKey: null as string | null,
questionTypeDefinitionId: questionTypeDefinitionId:
typeDefinitions[0]?.id ?? (null as number | null), typeDefinitions[0]?.id ?? (null as number | null),
text: "", text: "",

View File

@ -21,6 +21,10 @@ import {
validateLearnEnglishQuestionsWithDefinitions, validateLearnEnglishQuestionsWithDefinitions,
} from "../../lib/learnEnglishPracticePublish"; } from "../../lib/learnEnglishPracticePublish";
import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator"; import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator";
import {
isIeltsSharedStimulusMode,
validatePracticeStimulusBlocks,
} from "../../lib/practiceStimulusBlocks";
import { import {
dedupeParents, dedupeParents,
formatPracticeParentsSummary, formatPracticeParentsSummary,
@ -245,12 +249,17 @@ export function EditPracticeFlow() {
storyImageUrl: "", storyImageUrl: "",
shuffleQuestions: false, shuffleQuestions: false,
tips: "", tips: "",
authoringProfile: "STANDALONE" as const,
stimulusBlocks: [] as import("../../lib/practiceStimulusBlocks").PracticeFormStimulusBlock[],
parents: [] as PracticeParent[], parents: [] as PracticeParent[],
questions: [ questions: [
{ {
id: "q1", id: "q1",
displayOrder: 1, displayOrder: 1,
serverQuestionId: null as number | null, 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, questionTypeDefinitionId: null as number | null,
text: "", text: "",
difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD",
@ -374,6 +383,7 @@ export function EditPracticeFlow() {
serverQuestionId: q.serverQuestionId ?? null, serverQuestionId: q.serverQuestionId ?? null,
associatedQuestionId: q.associatedQuestionId ?? null, associatedQuestionId: q.associatedQuestionId ?? null,
associatedAnchorRowId: q.associatedAnchorRowId ?? null, associatedAnchorRowId: q.associatedAnchorRowId ?? null,
stimulusBlockKey: q.stimulusBlockKey ?? null,
dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) }, dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) },
mcqOptions: (q.mcqOptions ?? []).map( mcqOptions: (q.mcqOptions ?? []).map(
(o: { text?: string; isCorrect?: boolean }) => ({ (o: { text?: string; isCorrect?: boolean }) => ({
@ -385,10 +395,14 @@ export function EditPracticeFlow() {
shortAnswers: (q.shortAnswers ?? []).map((s: string) => String(s)), shortAnswers: (q.shortAnswers ?? []).map((s: string) => String(s)),
})); }));
const validationMsg = validateLearnEnglishQuestionsWithDefinitions( const validationMsg = isIeltsSharedStimulusMode(formData.authoringProfile)
? validatePracticeStimulusBlocks(
formData.authoringProfile,
formData.stimulusBlocks,
mappedQuestions, mappedQuestions,
typeDefinitions, typeDefinitions,
); )
: validateLearnEnglishQuestionsWithDefinitions(mappedQuestions, typeDefinitions);
if (validationMsg) { if (validationMsg) {
toast.error("Check your questions", { description: validationMsg }); toast.error("Check your questions", { description: validationMsg });
return; return;
@ -542,6 +556,11 @@ export function EditPracticeFlow() {
isExamPrepParents={isExamPrep} isExamPrepParents={isExamPrep}
parentsOptional={isExamPrep} parentsOptional={isExamPrep}
parentsCollapsedDefault={isExamPrep} parentsCollapsedDefault={isExamPrep}
practiceId={practiceId}
onParentsUnlinked={(parents) => {
setFormData((fd) => ({ ...fd, parents }))
initialParentsRef.current = parents
}}
/> />
); );
case 2: case 2:

View File

@ -21,6 +21,12 @@ import {
setExamPrepPracticePublishStatus, setExamPrepPracticePublishStatus,
setLearnEnglishPracticePublishStatus, setLearnEnglishPracticePublishStatus,
} from "../../api/courses.api"; } from "../../api/courses.api";
import { parentsFromPractice } from "../../lib/practiceParents";
import {
isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError,
unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink";
import { Badge } from "../../components/ui/badge"; import { Badge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button"; import { Button } from "../../components/ui/button";
import { PracticeActionButton } from "./components/PracticeActionButton"; import { PracticeActionButton } from "./components/PracticeActionButton";
@ -38,6 +44,7 @@ import type {
GetExamPrepLessonPracticesResponse, GetExamPrepLessonPracticesResponse,
GetPracticesByParentContextResponse, GetPracticesByParentContextResponse,
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../types/course.types"; } from "../../types/course.types";
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip"; import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
@ -96,6 +103,7 @@ function PracticeCard({
index, index,
total, total,
onEdit, onEdit,
onUnlink,
onDelete, onDelete,
onTogglePublishStatus, onTogglePublishStatus,
publishStatusUpdating, publishStatusUpdating,
@ -104,6 +112,7 @@ function PracticeCard({
index: number; index: number;
total: number; total: number;
onEdit?: () => void; onEdit?: () => void;
onUnlink?: () => void;
onDelete?: () => void; onDelete?: () => void;
onTogglePublishStatus?: (nextStatus: PracticePublishStatus) => void; onTogglePublishStatus?: (nextStatus: PracticePublishStatus) => void;
publishStatusUpdating?: boolean; publishStatusUpdating?: boolean;
@ -167,6 +176,17 @@ function PracticeCard({
onToggle={onTogglePublishStatus} onToggle={onTogglePublishStatus}
/> />
</div> </div>
{onUnlink ? (
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 gap-1.5 text-grayScale-700 hover:bg-grayScale-100"
onClick={onUnlink}
>
Unlink
</Button>
) : null}
{onDelete ? ( {onDelete ? (
<Button <Button
type="button" type="button"
@ -259,7 +279,9 @@ export function LessonPracticesPage() {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState<string | null>(null); const [loadError, setLoadError] = useState<string | null>(null);
const [practiceToDelete, setPracticeToDelete] = useState<ParentContextPractice | null>(null); const [practiceToDelete, setPracticeToDelete] = useState<ParentContextPractice | null>(null);
const [practiceToUnlink, setPracticeToUnlink] = useState<ParentContextPractice | null>(null);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
const [unlinking, setUnlinking] = useState(false);
const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState< const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState<
number | null number | null
>(null); >(null);
@ -404,6 +426,38 @@ export function LessonPracticesPage() {
} }
}; };
const lessonParent = useMemo(
(): PracticeParent => ({ parent_kind: "LESSON", parent_id: lid }),
[lid],
);
const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return;
setUnlinking(true);
try {
await unlinkPracticeFromParent({
practiceId: practiceToUnlink.id,
parent: lessonParent,
isExamPrep,
});
toast.success(`Practice removed from ${displayTitle}`);
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 from lesson", {
description: mapPracticeParentUnlinkError(e),
});
} finally {
setUnlinking(false);
}
};
const confirmDeletePractice = async () => { const confirmDeletePractice = async () => {
if (!practiceToDelete) return; if (!practiceToDelete) return;
setDeleting(true); setDeleting(true);
@ -611,6 +665,7 @@ export function LessonPracticesPage() {
onSaveAsDraft={() => onSaveAsDraft={() =>
void handlePracticePublishStatus(p.id, "DRAFT") void handlePracticePublishStatus(p.id, "DRAFT")
} }
onUnlink={() => setPracticeToUnlink(p)}
onDelete={() => setPracticeToDelete(p)} onDelete={() => setPracticeToDelete(p)}
/> />
))} ))}
@ -623,9 +678,8 @@ export function LessonPracticesPage() {
index={i} index={i}
total={filteredPractices.length} total={filteredPractices.length}
onEdit={() => void navigate(editPracticeHref(p.id))} onEdit={() => void navigate(editPracticeHref(p.id))}
onDelete={ onUnlink={() => setPracticeToUnlink(p)}
isExamPrep ? () => setPracticeToDelete(p) : undefined onDelete={isExamPrep ? () => setPracticeToDelete(p) : undefined}
}
publishStatusUpdating={publishStatusUpdatingId === p.id} publishStatusUpdating={publishStatusUpdatingId === p.id}
onTogglePublishStatus={(nextStatus) => onTogglePublishStatus={(nextStatus) =>
void handlePracticePublishStatus(p.id, nextStatus) void handlePracticePublishStatus(p.id, nextStatus)
@ -638,6 +692,53 @@ export function LessonPracticesPage() {
</div> </div>
</div> </div>
<Dialog
open={practiceToUnlink !== null}
onOpenChange={(open) => {
if (!open && !unlinking) setPracticeToUnlink(null);
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Remove from this lesson?</DialogTitle>
</DialogHeader>
<p className="text-sm text-grayScale-600">
<span className="font-semibold text-grayScale-900">
{practiceToUnlink?.title}
</span>{" "}
will be detached from{" "}
<span className="font-semibold text-grayScale-900">{displayTitle}</span>.
{practiceToUnlink &&
parentsFromPractice(practiceToUnlink).filter(
(p) =>
!(
p.parent_kind === lessonParent.parent_kind &&
p.parent_id === lessonParent.parent_id
),
).length === 0
? " The practice will be unlinked until you attach it again. Questions are kept."
: " Other locations are unaffected."}
</p>
<DialogFooter>
<Button
type="button"
variant="outline"
disabled={unlinking}
onClick={() => setPracticeToUnlink(null)}
>
Cancel
</Button>
<Button
type="button"
disabled={unlinking}
onClick={() => void confirmUnlinkPractice()}
>
{unlinking ? "Removing…" : "Remove from lesson"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog <Dialog
open={practiceToDelete !== null} open={practiceToDelete !== null}
onOpenChange={(open) => { onOpenChange={(open) => {
@ -646,13 +747,13 @@ export function LessonPracticesPage() {
> >
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>Delete this practice?</DialogTitle> <DialogTitle>Delete this practice permanently?</DialogTitle>
</DialogHeader> </DialogHeader>
<p className="text-sm text-grayScale-600"> <p className="text-sm text-grayScale-600">
<span className="font-semibold text-grayScale-900"> <span className="font-semibold text-grayScale-900">
{practiceToDelete?.title} {practiceToDelete?.title}
</span>{" "} </span>{" "}
will be removed from this lesson. This action cannot be undone. and all of its questions will be deleted. This cannot be undone.
</p> </p>
<DialogFooter> <DialogFooter>
<Button <Button

View File

@ -15,10 +15,17 @@ import {
import type { import type {
ContentAccessTier, ContentAccessTier,
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
TopLevelModuleLessonItem, TopLevelModuleLessonItem,
} from "../../types/course.types"; } from "../../types/course.types";
import { unwrapPracticesList } from "../../lib/parentContextPractice"; import { unwrapPracticesList } from "../../lib/parentContextPractice";
import { parentsFromPractice } from "../../lib/practiceParents";
import {
isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError,
unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink";
import { Button } from "../../components/ui/button"; import { Button } from "../../components/ui/button";
import { PracticeActionButton } from "./components/PracticeActionButton"; import { PracticeActionButton } from "./components/PracticeActionButton";
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog"; import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
@ -123,6 +130,9 @@ export function ModuleDetailPage() {
const [publishStatusPracticeId, setPublishStatusPracticeId] = useState< const [publishStatusPracticeId, setPublishStatusPracticeId] = useState<
number | null number | null
>(null); >(null);
const [practiceToUnlink, setPracticeToUnlink] =
useState<ParentContextPractice | null>(null);
const [unlinkingPractice, setUnlinkingPractice] = useState(false);
const [loadedModuleName, setLoadedModuleName] = useState<string | null>(null); const [loadedModuleName, setLoadedModuleName] = useState<string | null>(null);
const [loadedModuleDescription, setLoadedModuleDescription] = useState< const [loadedModuleDescription, setLoadedModuleDescription] = useState<
string | null string | null
@ -326,16 +336,46 @@ export function ModuleDetailPage() {
: "Practice saved as draft", : "Practice saved as draft",
); );
} catch (e: unknown) { } catch (e: unknown) {
console.error(e); const err = e as { response?: { data?: { message?: string } } };
const msg = toast.error(err.response?.data?.message || "Failed to update practice status");
(e as { response?: { data?: { message?: string } } })?.response?.data
?.message ?? "Failed to update practice status";
toast.error(msg);
} finally { } finally {
setPublishStatusPracticeId(null); setPublishStatusPracticeId(null);
} }
}; };
const moduleParent = useMemo((): PracticeParent | null => {
const mid = Number(moduleId);
if (!Number.isFinite(mid) || mid < 1) return null;
return { parent_kind: "MODULE", parent_id: mid };
}, [moduleId]);
const confirmUnlinkPractice = async () => {
if (!practiceToUnlink || !moduleParent) return;
setUnlinkingPractice(true);
try {
await unlinkPracticeFromParent({
practiceId: practiceToUnlink.id,
parent: moduleParent,
isExamPrep: false,
});
toast.success(`Practice removed from ${displayModuleName}`);
setPracticeToUnlink(null);
await loadModulePractices();
} catch (e) {
if (isPracticeParentUnlinkNotLinkedError(e)) {
toast.info("This location was already removed.");
setPracticeToUnlink(null);
await loadModulePractices();
return;
}
toast.error("Could not remove from module", {
description: mapPracticeParentUnlinkError(e),
});
} finally {
setUnlinkingPractice(false);
}
};
const openEditLesson = (lesson: TopLevelModuleLessonItem) => { const openEditLesson = (lesson: TopLevelModuleLessonItem) => {
setEditingLesson(lesson); setEditingLesson(lesson);
setEditLessonTitle(lesson.title ?? ""); setEditLessonTitle(lesson.title ?? "");
@ -694,6 +734,7 @@ export function ModuleDetailPage() {
onSaveAsDraft={() => onSaveAsDraft={() =>
void handlePracticePublishStatus(practice.id, "DRAFT") void handlePracticePublishStatus(practice.id, "DRAFT")
} }
onUnlink={() => setPracticeToUnlink(practice)}
/> />
))} ))}
</div> </div>
@ -888,6 +929,55 @@ export function ModuleDetailPage() {
</div> </div>
)} )}
{practiceToUnlink && moduleParent ? (
<Dialog
open={practiceToUnlink != null}
onOpenChange={(open) => {
if (!open && !unlinkingPractice) setPracticeToUnlink(null);
}}
>
<DialogContent className="max-w-md rounded-2xl">
<DialogHeader>
<DialogTitle>Remove from this module?</DialogTitle>
<DialogDescription>
<span className="font-semibold text-grayScale-800">
{practiceToUnlink.title}
</span>{" "}
will be detached from{" "}
<span className="font-semibold text-grayScale-800">
{displayModuleName}
</span>
.
{parentsFromPractice(practiceToUnlink).filter(
(p) =>
!(
p.parent_kind === moduleParent.parent_kind &&
p.parent_id === moduleParent.parent_id
),
).length === 0
? " The practice will be unlinked until re-attached."
: " Other locations are unaffected."}
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => setPracticeToUnlink(null)}
disabled={unlinkingPractice}
>
Cancel
</Button>
<Button
onClick={() => void confirmUnlinkPractice()}
disabled={unlinkingPractice}
>
{unlinkingPractice ? "Removing…" : "Remove from module"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
) : null}
{lessonPracticeChoice && lessonPracticeChoicePaths ? ( {lessonPracticeChoice && lessonPracticeChoicePaths ? (
<PracticeActionChoiceDialog <PracticeActionChoiceDialog
open={lessonPracticeChoice != null} open={lessonPracticeChoice != null}

View File

@ -8,6 +8,12 @@ import {
setExamPrepPracticePublishStatus, setExamPrepPracticePublishStatus,
} from "../../../api/courses.api" } from "../../../api/courses.api"
import { unwrapPracticesList } from "../../../lib/parentContextPractice" import { unwrapPracticesList } from "../../../lib/parentContextPractice"
import { parentsFromPractice } from "../../../lib/practiceParents"
import {
isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError,
unlinkPracticeFromParent,
} from "../../../lib/practiceParentUnlink"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
import { import {
Dialog, Dialog,
@ -24,6 +30,7 @@ import {
} from "../../../lib/contentListFilters" } from "../../../lib/contentListFilters"
import type { import type {
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../../types/course.types" } from "../../../types/course.types"
@ -58,7 +65,9 @@ export function CatalogCoursePracticesPanel({
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState<string | null>(null) const [loadError, setLoadError] = useState<string | null>(null)
const [practiceToDelete, setPracticeToDelete] = useState<ParentContextPractice | null>(null) const [practiceToDelete, setPracticeToDelete] = useState<ParentContextPractice | null>(null)
const [practiceToUnlink, setPracticeToUnlink] = useState<ParentContextPractice | null>(null)
const [deleting, setDeleting] = useState(false) const [deleting, setDeleting] = useState(false)
const [unlinking, setUnlinking] = useState(false)
const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState<number | null>(null) const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState<number | null>(null)
const [listSearch, setListSearch] = useState("") const [listSearch, setListSearch] = useState("")
const [publishStatusFilter, setPublishStatusFilter] = useState<PublishStatusFilter>("all") const [publishStatusFilter, setPublishStatusFilter] = useState<PublishStatusFilter>("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 () => { const confirmDeletePractice = async () => {
if (!practiceToDelete) return if (!practiceToDelete) return
setDeleting(true) setDeleting(true)
@ -214,23 +255,60 @@ export function CatalogCoursePracticesPanel({
onEdit={() => navigate(editPracticeHref(practice.id))} onEdit={() => navigate(editPracticeHref(practice.id))}
onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")}
onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")}
onUnlink={() => setPracticeToUnlink(practice)}
onDelete={() => setPracticeToDelete(practice)} onDelete={() => setPracticeToDelete(practice)}
/> />
))} ))}
</div> </div>
)} )}
<Dialog
open={practiceToUnlink != null}
onOpenChange={(open) => !open && !unlinking && setPracticeToUnlink(null)}
>
<DialogContent className="max-w-md rounded-2xl">
<DialogHeader>
<DialogTitle>Remove from this catalog course?</DialogTitle>
</DialogHeader>
<p className="text-sm text-grayScale-600">
<span className="font-semibold text-grayScale-800">
{practiceToUnlink?.title || "This practice"}
</span>{" "}
will be detached from{" "}
<span className="font-semibold text-grayScale-800">{courseName}</span>.
{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."}
</p>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPracticeToUnlink(null)} disabled={unlinking}>
Cancel
</Button>
<Button onClick={() => void confirmUnlinkPractice()} disabled={unlinking}>
{unlinking ? "Removing…" : "Remove location"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={practiceToDelete != null} onOpenChange={(open) => !open && setPracticeToDelete(null)}> <Dialog open={practiceToDelete != null} onOpenChange={(open) => !open && setPracticeToDelete(null)}>
<DialogContent className="max-w-md rounded-2xl"> <DialogContent className="max-w-md rounded-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Delete practice?</DialogTitle> <DialogTitle>Delete practice permanently?</DialogTitle>
</DialogHeader> </DialogHeader>
<p className="text-sm text-grayScale-600"> <p className="text-sm text-grayScale-600">
This permanently removes{" "} This permanently removes{" "}
<span className="font-semibold text-grayScale-800"> <span className="font-semibold text-grayScale-800">
{practiceToDelete?.title || "this practice"} {practiceToDelete?.title || "this practice"}
</span> </span>{" "}
. and all of its questions.
</p> </p>
<DialogFooter className="gap-2 sm:gap-0"> <DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPracticeToDelete(null)} disabled={deleting}> <Button variant="outline" onClick={() => setPracticeToDelete(null)} disabled={deleting}>

View File

@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Edit2, Loader2, MoreVertical } from "lucide-react"; import { Edit2, Loader2, MoreVertical, Unlink } from "lucide-react";
import { Button } from "../../../components/ui/button"; import { Button } from "../../../components/ui/button";
import { Card } from "../../../components/ui/card"; import { Card } from "../../../components/ui/card";
import { import {
@ -27,6 +27,7 @@ type ModulePracticeCardProps = {
onEdit?: () => void; onEdit?: () => void;
onPublish?: () => void; onPublish?: () => void;
onSaveAsDraft?: () => void; onSaveAsDraft?: () => void;
onUnlink?: () => void;
onDelete?: () => void; onDelete?: () => void;
}; };
@ -36,6 +37,7 @@ export function ModulePracticeCard({
onEdit, onEdit,
onPublish, onPublish,
onSaveAsDraft, onSaveAsDraft,
onUnlink,
onDelete, onDelete,
}: ModulePracticeCardProps) { }: ModulePracticeCardProps) {
const isPublished = isPracticePublished(practice); const isPublished = isPracticePublished(practice);
@ -136,6 +138,18 @@ export function ModulePracticeCard({
> >
{isPublished ? "Save as draft" : "Publish practice"} {isPublished ? "Save as draft" : "Publish practice"}
</DropdownMenuItem> </DropdownMenuItem>
{onUnlink ? (
<DropdownMenuItem
disabled={statusUpdating}
onClick={(e) => {
e.stopPropagation();
onUnlink();
}}
>
<Unlink className="mr-2 h-4 w-4" />
Unlink
</DropdownMenuItem>
) : null}
{onDelete ? ( {onDelete ? (
<DropdownMenuItem <DropdownMenuItem
disabled={statusUpdating} disabled={statusUpdating}
@ -145,7 +159,7 @@ export function ModulePracticeCard({
onDelete(); onDelete();
}} }}
> >
Delete practice Delete
</DropdownMenuItem> </DropdownMenuItem>
) : null} ) : null}
</DropdownMenuContent> </DropdownMenuContent>

View File

@ -14,8 +14,11 @@ import {
} from "../../../components/ui/dialog" } from "../../../components/ui/dialog"
import { SpinnerIcon } from "../../../components/ui/spinner-icon" import { SpinnerIcon } from "../../../components/ui/spinner-icon"
import { cn } from "../../../lib/utils" import { cn } from "../../../lib/utils"
import { resolveLearnEnglishPracticeEditPath } from "../../../lib/learnEnglishPracticeEditPath" import { resolveQuestionTypeDefinitionPracticeEditPath } from "../../../lib/questionTypeDefinitionPracticeEditPath"
import { formatPracticeParentsSummary } from "../../../lib/practiceParents" import {
formatPracticeLocation,
isQuestionTypeDefinitionPracticeUnlinked,
} from "../../../lib/questionTypeDefinitionPractices"
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination" import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination"
import type { import type {
QuestionTypeDefinition, QuestionTypeDefinition,
@ -98,10 +101,13 @@ export function QuestionTypeDefinitionPracticesDialog({
const handleEditPractice = async (practice: QuestionTypeDefinitionPractice) => { const handleEditPractice = async (practice: QuestionTypeDefinitionPractice) => {
setEditingPracticeId(practice.practice_id) setEditingPracticeId(practice.practice_id)
try { try {
const path = await resolveLearnEnglishPracticeEditPath(practice) const path = await resolveQuestionTypeDefinitionPracticeEditPath(practice)
if (!path) { if (!path) {
toast.error("Could not open practice editor", { toast.error("Could not open practice editor", {
description: "This practice could not be linked to its course context.", description:
practice.practice_kind === "EXAM_PREP"
? "This exam-prep practice could not be linked to its catalog context."
: "This practice could not be linked to its course context.",
}) })
return return
} }
@ -163,9 +169,11 @@ export function QuestionTypeDefinitionPracticesDialog({
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-grayScale-100 text-grayScale-400"> <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-grayScale-100 text-grayScale-400">
<GraduationCap className="h-7 w-7" aria-hidden /> <GraduationCap className="h-7 w-7" aria-hidden />
</div> </div>
<p className="text-sm font-semibold text-grayScale-700">No practices found</p> <p className="text-sm font-semibold text-grayScale-700">
No practices use this question type yet.
</p>
<p className="max-w-sm text-xs text-grayScale-500"> <p className="max-w-sm text-xs text-grayScale-500">
No published or draft practices currently contain questions built from this definition. Create a practice shell and add questions built from this definition.
</p> </p>
{definition ? ( {definition ? (
<Button <Button
@ -181,7 +189,10 @@ export function QuestionTypeDefinitionPracticesDialog({
</div> </div>
) : ( ) : (
<ul className="divide-y divide-grayScale-100 overflow-y-auto px-2 py-2"> <ul className="divide-y divide-grayScale-100 overflow-y-auto px-2 py-2">
{practices.map((practice) => ( {practices.map((practice) => {
const location = formatPracticeLocation(practice)
const isUnlinked = isQuestionTypeDefinitionPracticeUnlinked(practice)
return (
<li key={`${practice.practice_kind}-${practice.practice_id}`} className="px-4 py-4"> <li key={`${practice.practice_kind}-${practice.practice_id}`} className="px-4 py-4">
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between"> <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0 space-y-1.5"> <div className="min-w-0 space-y-1.5">
@ -190,17 +201,12 @@ export function QuestionTypeDefinitionPracticesDialog({
<span className="font-mono">practice #{practice.practice_id}</span> <span className="font-mono">practice #{practice.practice_id}</span>
<span className="text-grayScale-300">·</span> <span className="text-grayScale-300">·</span>
<span className="font-mono">set #{practice.question_set_id}</span> <span className="font-mono">set #{practice.question_set_id}</span>
{practice.parents && practice.parents.length > 0 ? (
<>
<span className="text-grayScale-300">·</span> <span className="text-grayScale-300">·</span>
<span>{formatPracticeParentsSummary(practice.parents)}</span> <span
</> className={cn(isUnlinked && "italic text-amber-700")}
) : ( >
<> {location}
<span className="text-grayScale-300">·</span> </span>
<span className="italic text-amber-700">Unlinked</span>
</>
)}
</div> </div>
{practice.story_description?.trim() ? ( {practice.story_description?.trim() ? (
<p className="line-clamp-2 text-xs text-grayScale-500">{practice.story_description}</p> <p className="line-clamp-2 text-xs text-grayScale-500">{practice.story_description}</p>
@ -238,7 +244,7 @@ export function QuestionTypeDefinitionPracticesDialog({
</div> </div>
</div> </div>
</li> </li>
))} )})}
</ul> </ul>
)} )}

View File

@ -8,6 +8,12 @@ import {
setExamPrepPracticePublishStatus, setExamPrepPracticePublishStatus,
} from "../../../api/courses.api" } from "../../../api/courses.api"
import { unwrapPracticesList } from "../../../lib/parentContextPractice" import { unwrapPracticesList } from "../../../lib/parentContextPractice"
import { parentsFromPractice } from "../../../lib/practiceParents"
import {
isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError,
unlinkPracticeFromParent,
} from "../../../lib/practiceParentUnlink"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
import { import {
Dialog, Dialog,
@ -24,6 +30,7 @@ import {
} from "../../../lib/contentListFilters" } from "../../../lib/contentListFilters"
import type { import type {
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../../types/course.types" } from "../../../types/course.types"
@ -60,7 +67,9 @@ export function UnitPracticesPanel({
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState<string | null>(null) const [loadError, setLoadError] = useState<string | null>(null)
const [practiceToDelete, setPracticeToDelete] = useState<ParentContextPractice | null>(null) const [practiceToDelete, setPracticeToDelete] = useState<ParentContextPractice | null>(null)
const [practiceToUnlink, setPracticeToUnlink] = useState<ParentContextPractice | null>(null)
const [deleting, setDeleting] = useState(false) const [deleting, setDeleting] = useState(false)
const [unlinking, setUnlinking] = useState(false)
const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState<number | null>(null) const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState<number | null>(null)
const [listSearch, setListSearch] = useState("") const [listSearch, setListSearch] = useState("")
const [publishStatusFilter, setPublishStatusFilter] = useState<PublishStatusFilter>("all") const [publishStatusFilter, setPublishStatusFilter] = useState<PublishStatusFilter>("all")
@ -137,6 +146,38 @@ export function UnitPracticesPanel({
} }
} }
const unitParent = useMemo(
(): PracticeParent => ({ parent_kind: "UNIT", parent_id: unitId }),
[unitId],
)
const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return
setUnlinking(true)
try {
await unlinkPracticeFromParent({
practiceId: practiceToUnlink.id,
parent: unitParent,
isExamPrep: true,
})
toast.success(`Practice removed from ${unitName}`)
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 () => { const confirmDeletePractice = async () => {
if (!practiceToDelete) return if (!practiceToDelete) return
setDeleting(true) setDeleting(true)
@ -216,23 +257,60 @@ export function UnitPracticesPanel({
onEdit={() => navigate(editPracticeHref(practice.id))} onEdit={() => navigate(editPracticeHref(practice.id))}
onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")} onPublish={() => void handlePracticePublishStatus(practice.id, "PUBLISHED")}
onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")} onSaveAsDraft={() => void handlePracticePublishStatus(practice.id, "DRAFT")}
onUnlink={() => setPracticeToUnlink(practice)}
onDelete={() => setPracticeToDelete(practice)} onDelete={() => setPracticeToDelete(practice)}
/> />
))} ))}
</div> </div>
)} )}
<Dialog
open={practiceToUnlink != null}
onOpenChange={(open) => !open && !unlinking && setPracticeToUnlink(null)}
>
<DialogContent className="max-w-md rounded-2xl">
<DialogHeader>
<DialogTitle>Remove from this unit?</DialogTitle>
</DialogHeader>
<p className="text-sm text-grayScale-600">
<span className="font-semibold text-grayScale-800">
{practiceToUnlink?.title || "This practice"}
</span>{" "}
will be detached from{" "}
<span className="font-semibold text-grayScale-800">{unitName}</span>.
{practiceToUnlink &&
parentsFromPractice(practiceToUnlink).filter(
(p) =>
!(
p.parent_kind === unitParent.parent_kind &&
p.parent_id === unitParent.parent_id
),
).length === 0
? " The practice will be unlinked until re-attached."
: " Other locations are unaffected."}
</p>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPracticeToUnlink(null)} disabled={unlinking}>
Cancel
</Button>
<Button onClick={() => void confirmUnlinkPractice()} disabled={unlinking}>
{unlinking ? "Removing…" : "Remove location"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={practiceToDelete != null} onOpenChange={(open) => !open && setPracticeToDelete(null)}> <Dialog open={practiceToDelete != null} onOpenChange={(open) => !open && setPracticeToDelete(null)}>
<DialogContent className="max-w-md rounded-2xl"> <DialogContent className="max-w-md rounded-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Delete practice?</DialogTitle> <DialogTitle>Delete practice permanently?</DialogTitle>
</DialogHeader> </DialogHeader>
<p className="text-sm text-grayScale-600"> <p className="text-sm text-grayScale-600">
This permanently removes{" "} This permanently removes{" "}
<span className="font-semibold text-grayScale-800"> <span className="font-semibold text-grayScale-800">
{practiceToDelete?.title || "this practice"} {practiceToDelete?.title || "this practice"}
</span> </span>{" "}
. and all of its questions.
</p> </p>
<DialogFooter className="gap-2 sm:gap-0"> <DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPracticeToDelete(null)} disabled={deleting}> <Button variant="outline" onClick={() => setPracticeToDelete(null)} disabled={deleting}>

View File

@ -6,7 +6,7 @@ import { Input } from "../../../../components/ui/input";
import { Textarea } from "../../../../components/ui/textarea"; import { Textarea } from "../../../../components/ui/textarea";
import { toast } from "sonner"; import { toast } from "sonner";
import { uploadImageFile } from "../../../../api/files.api"; import { uploadImageFile } from "../../../../api/files.api";
import type { PracticeParent } from "../../../../types/course.types"; import type { PracticeParent, AuthoringProfile } from "../../../../types/course.types";
import { PracticeParentsField } from "./PracticeParentsField"; import { PracticeParentsField } from "./PracticeParentsField";
import { formatPracticeParentsSummary } from "../../../../lib/practiceParents"; import { formatPracticeParentsSummary } from "../../../../lib/practiceParents";
@ -17,6 +17,7 @@ interface ContextStepProps {
storyImageUrl?: string; storyImageUrl?: string;
shuffleQuestions?: boolean; shuffleQuestions?: boolean;
tips?: string; tips?: string;
authoringProfile?: AuthoringProfile;
parents?: PracticeParent[]; parents?: PracticeParent[];
}; };
setFormData: (data: ContextStepProps["formData"]) => void; setFormData: (data: ContextStepProps["formData"]) => void;
@ -34,6 +35,9 @@ interface ContextStepProps {
/** Use exam-prep parent kinds in the locations editor. */ /** Use exam-prep parent kinds in the locations editor. */
isExamPrepParents?: boolean; isExamPrepParents?: boolean;
parentsCollapsedDefault?: boolean; parentsCollapsedDefault?: boolean;
/** When editing an existing practice, enable per-parent DELETE unlink. */
practiceId?: number;
onParentsUnlinked?: (parents: PracticeParent[]) => void;
} }
/** /**
@ -52,6 +56,8 @@ export function ContextStep({
parentsOptional = false, parentsOptional = false,
parentsCollapsedDefault = false, parentsCollapsedDefault = false,
isExamPrepParents = false, isExamPrepParents = false,
practiceId,
onParentsUnlinked,
}: ContextStepProps) { }: ContextStepProps) {
const storyFileRef = useRef<HTMLInputElement>(null); const storyFileRef = useRef<HTMLInputElement>(null);
const [uploadingStory, setUploadingStory] = useState(false); const [uploadingStory, setUploadingStory] = useState(false);
@ -169,6 +175,8 @@ export function ContextStep({
lockedParentKey={lockedParentKey} lockedParentKey={lockedParentKey}
optional optional
isExamPrep={isExamPrepParents} isExamPrep={isExamPrepParents}
practiceId={practiceId}
onUnlinked={onParentsUnlinked}
onChange={(parents) => setFormData({ ...formData, parents })} onChange={(parents) => setFormData({ ...formData, parents })}
/> />
) : null} ) : null}
@ -178,6 +186,8 @@ export function ContextStep({
parents={formData.parents ?? []} parents={formData.parents ?? []}
lockedParentKey={lockedParentKey} lockedParentKey={lockedParentKey}
isExamPrep={isExamPrepParents} isExamPrep={isExamPrepParents}
practiceId={practiceId}
onUnlinked={onParentsUnlinked}
onChange={(parents) => setFormData({ ...formData, parents })} onChange={(parents) => setFormData({ ...formData, parents })}
/> />
) )
@ -283,6 +293,58 @@ export function ContextStep({
/> />
<span>Shuffle questions in the set</span> <span>Shuffle questions in the set</span>
</label> </label>
<div className="rounded-xl border border-sky-100 bg-sky-50/50 px-4 py-4">
<label className="flex cursor-pointer items-start gap-3 text-sm text-grayScale-800">
<input
type="checkbox"
className="mt-0.5 h-4 w-4 rounded border-grayScale-300 text-sky-600 focus:ring-sky-500"
checked={formData.authoringProfile === "IELTS_SHARED_STIMULUS"}
onChange={(e) => {
const nextProfile: AuthoringProfile = e.target.checked
? "IELTS_SHARED_STIMULUS"
: "STANDALONE";
if (
!e.target.checked &&
formData.authoringProfile === "IELTS_SHARED_STIMULUS"
) {
const hasBlocks =
Array.isArray((formData as { stimulusBlocks?: unknown[] }).stimulusBlocks) &&
((formData as { stimulusBlocks?: unknown[] }).stimulusBlocks?.length ?? 0) > 0;
if (hasBlocks) {
const proceed = window.confirm(
"Switching off IELTS shared stimulus mode will remove stimulus blocks on save. Continue?",
);
if (!proceed) return;
}
}
setFormData({
...formData,
authoringProfile: nextProfile,
...(nextProfile === "STANDALONE"
? {
stimulusBlocks: [],
questions: Array.isArray((formData as { questions?: { stimulusBlockKey?: string | null }[] }).questions)
? (formData as { questions: { stimulusBlockKey?: string | null }[] }).questions.map(
(q) => ({ ...q, stimulusBlockKey: null }),
)
: undefined,
}
: {}),
});
}}
/>
<span>
<span className="font-semibold text-sky-900">
Use shared stimulus sections (IELTS mode)
</span>
<span className="mt-1 block text-xs leading-relaxed text-sky-900/80">
Authors define shared audio, passages, or instructions per section. Questions
link to a block and edit response fields only.
</span>
</span>
</label>
</div>
</div> </div>
<div className="flex items-center justify-between border-t border-grayScale-100 bg-[#F8FAFC] p-4 px-12"> <div className="flex items-center justify-between border-t border-grayScale-100 bg-[#F8FAFC] p-4 px-12">

View File

@ -1,8 +1,22 @@
import { Plus, Trash2 } from "lucide-react" import { useState } from "react"
import { Loader2, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Button } from "../../../../components/ui/button" import { Button } from "../../../../components/ui/button"
import { Input } from "../../../../components/ui/input" import { Input } from "../../../../components/ui/input"
import type { PracticeParent, PracticeParentKind } from "../../../../types/course.types" import type { PracticeParent, PracticeParentKind } from "../../../../types/course.types"
import { dedupeParents, newParentRow } from "../../../../lib/practiceParents" import {
dedupeParents,
formatPracticeParentLabel,
isPracticeParentKind,
newParentRow,
parentsFromPractice,
} from "../../../../lib/practiceParents"
import {
isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError,
unlinkParentConfirmMessage,
unlinkPracticeFromParent,
} from "../../../../lib/practiceParentUnlink"
const LMS_KIND_OPTIONS: { value: PracticeParentKind; label: string }[] = [ const LMS_KIND_OPTIONS: { value: PracticeParentKind; label: string }[] = [
{ value: "COURSE", label: "Course" }, { value: "COURSE", label: "Course" },
@ -26,6 +40,10 @@ interface PracticeParentsFieldProps {
optional?: boolean optional?: boolean
/** Use exam-prep parent kinds instead of Learn English. */ /** Use exam-prep parent kinds instead of Learn English. */
isExamPrep?: boolean isExamPrep?: boolean
/** When set, removing a saved location calls DELETE .../parents immediately. */
practiceId?: number
/** Called after a successful per-parent unlink with the remaining parents. */
onUnlinked?: (parents: PracticeParent[]) => void
} }
function parentKey(parent: PracticeParent): string { function parentKey(parent: PracticeParent): string {
@ -39,16 +57,21 @@ export function PracticeParentsField({
lockedParentKey = null, lockedParentKey = null,
optional = false, optional = false,
isExamPrep = false, isExamPrep = false,
practiceId,
onUnlinked,
}: PracticeParentsFieldProps) { }: PracticeParentsFieldProps) {
const kindOptions = isExamPrep ? EXAM_PREP_KIND_OPTIONS : LMS_KIND_OPTIONS const kindOptions = isExamPrep ? EXAM_PREP_KIND_OPTIONS : LMS_KIND_OPTIONS
const rows = parents.length > 0 ? parents : [newParentRow(isExamPrep ? "CATALOG_COURSE" : "LESSON")] const rows = parents.length > 0 ? parents : [newParentRow(isExamPrep ? "CATALOG_COURSE" : "LESSON")]
const [unlinkingKey, setUnlinkingKey] = useState<string | null>(null)
const canPersistUnlink =
practiceId != null && Number.isFinite(practiceId) && practiceId > 0
const updateRow = (index: number, patch: Partial<PracticeParent>) => { const updateRow = (index: number, patch: Partial<PracticeParent>) => {
const next = rows.map((row, i) => (i === index ? { ...row, ...patch } : row)) const next = rows.map((row, i) => (i === index ? { ...row, ...patch } : row))
onChange(dedupeParents(next)) onChange(dedupeParents(next))
} }
const removeRow = (index: number) => { const removeRowLocally = (index: number) => {
const row = rows[index] const row = rows[index]
if (lockedParentKey && parentKey(row) === lockedParentKey) return if (lockedParentKey && parentKey(row) === lockedParentKey) return
if (rows.length <= 1) { if (rows.length <= 1) {
@ -58,6 +81,62 @@ export function PracticeParentsField({
onChange(rows.filter((_, i) => i !== index)) onChange(rows.filter((_, i) => i !== index))
} }
const removeRow = async (index: number) => {
const row = rows[index]
if (lockedParentKey && parentKey(row) === lockedParentKey) return
if (disabled || unlinkingKey) return
const hasSavedParent = row.parent_id > 0 && isPracticeParentKind(row.parent_kind)
if (canPersistUnlink && hasSavedParent) {
const label = formatPracticeParentLabel(row)
const remaining = parentsFromPractice({ parents }).filter(
(p) => parentKey(p) !== parentKey(row),
)
const proceed = window.confirm(
unlinkParentConfirmMessage(label, {
isLastParent: remaining.length === 0,
}),
)
if (!proceed) return
const key = parentKey(row)
setUnlinkingKey(key)
try {
const updated = await unlinkPracticeFromParent({
practiceId: practiceId!,
parent: row,
isExamPrep,
})
const nextParents = parentsFromPractice(updated)
onChange(nextParents)
onUnlinked?.(nextParents)
toast.success(
remaining.length === 0
? "Practice is now unlinked"
: `Removed from ${label}`,
)
} catch (err) {
if (isPracticeParentUnlinkNotLinkedError(err)) {
const nextParents = parentsFromPractice({ parents }).filter(
(p) => parentKey(p) !== parentKey(row),
)
onChange(nextParents)
onUnlinked?.(nextParents)
toast.info("This location was already removed.")
return
}
toast.error("Could not remove location", {
description: mapPracticeParentUnlinkError(err),
})
} finally {
setUnlinkingKey(null)
}
return
}
removeRowLocally(index)
}
const addRow = () => { const addRow = () => {
onChange([...rows, newParentRow()]) onChange([...rows, newParentRow()])
} }
@ -67,13 +146,15 @@ export function PracticeParentsField({
<div className="space-y-1"> <div className="space-y-1">
<p className="text-sm font-semibold text-grayScale-800">Attached locations</p> <p className="text-sm font-semibold text-grayScale-800">Attached locations</p>
<p className="text-xs text-grayScale-500"> <p className="text-xs text-grayScale-500">
{optional {canPersistUnlink
? "Remove a location with × to detach immediately. Add new locations here, then save the practice."
: optional
? isExamPrep ? isExamPrep
? "Attach now or leave empty and link this practice to catalog courses, units, or lessons later." ? "Attach now or leave empty and link this practice to catalog courses, units, or lessons later."
: "Attach now or leave empty and link this practice later." : "Attach now or leave empty and link this practice later."
: isExamPrep : isExamPrep
? "Link this practice to one or more catalog courses, units, or lessons." ? "Link this practice to one or more catalog courses, units, or lessons."
: "Link this practice to one or more courses, modules, or lessons. Each location can only have one practice."} : "Link this practice to one or more courses, modules, or lessons."}
</p> </p>
</div> </div>
@ -81,6 +162,7 @@ export function PracticeParentsField({
{rows.map((row, index) => { {rows.map((row, index) => {
const key = parentKey(row) const key = parentKey(row)
const isLocked = Boolean(lockedParentKey && key === lockedParentKey && row.parent_id > 0) const isLocked = Boolean(lockedParentKey && key === lockedParentKey && row.parent_id > 0)
const isUnlinking = unlinkingKey === key
return ( return (
<li <li
key={`${index}-${row.parent_kind}`} key={`${index}-${row.parent_kind}`}
@ -88,7 +170,7 @@ export function PracticeParentsField({
> >
<select <select
value={row.parent_kind} value={row.parent_kind}
disabled={disabled || isLocked} disabled={disabled || isLocked || isUnlinking}
onChange={(e) => onChange={(e) =>
updateRow(index, { parent_kind: e.target.value as PracticeParentKind }) updateRow(index, { parent_kind: e.target.value as PracticeParentKind })
} }
@ -103,7 +185,7 @@ export function PracticeParentsField({
<Input <Input
type="number" type="number"
min={1} min={1}
disabled={disabled || isLocked} disabled={disabled || isLocked || isUnlinking}
value={row.parent_id > 0 ? row.parent_id : ""} value={row.parent_id > 0 ? row.parent_id : ""}
onChange={(e) => onChange={(e) =>
updateRow(index, { parent_id: Number(e.target.value) || 0 }) updateRow(index, { parent_id: Number(e.target.value) || 0 })
@ -119,11 +201,20 @@ export function PracticeParentsField({
variant="ghost" variant="ghost"
size="sm" size="sm"
className="ml-auto h-8 w-8 p-0 text-grayScale-400 hover:text-red-600" className="ml-auto h-8 w-8 p-0 text-grayScale-400 hover:text-red-600"
disabled={disabled || rows.length <= 1 || isLocked} disabled={
onClick={() => removeRow(index)} disabled ||
isLocked ||
isUnlinking ||
(!canPersistUnlink && !optional && rows.length <= 1)
}
onClick={() => void removeRow(index)}
aria-label="Remove location" aria-label="Remove location"
> >
{isUnlinking ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
)}
</Button> </Button>
</li> </li>
) )
@ -134,7 +225,7 @@ export function PracticeParentsField({
type="button" type="button"
variant="outline" variant="outline"
size="sm" size="sm"
disabled={disabled} disabled={disabled || Boolean(unlinkingKey)}
onClick={addRow} onClick={addRow}
className="rounded-[8px] border-grayScale-200 text-xs font-semibold" className="rounded-[8px] border-grayScale-200 text-xs font-semibold"
> >

View File

@ -48,6 +48,11 @@ import {
import { cn } from "../../../../lib/utils"; import { cn } from "../../../../lib/utils";
import { toast } from "sonner"; import { toast } from "sonner";
import { QuestionAssociationField } from "./QuestionAssociationField"; import { QuestionAssociationField } from "./QuestionAssociationField";
import { StimulusBlocksPanel } from "./StimulusBlocksPanel";
import {
isIeltsSharedStimulusMode,
validatePracticeStimulusBlocks,
} from "../../../../lib/practiceStimulusBlocks";
function syncQuestionDisplayOrders<T extends { displayOrder?: number }>( function syncQuestionDisplayOrders<T extends { displayOrder?: number }>(
questions: T[], questions: T[],
@ -173,6 +178,7 @@ function createEmptyQuestionRow(id: string, displayOrder = 1, inheritAnchor?: {
associatedQuestionId: inheritAnchor?.associatedQuestionId ?? null, associatedQuestionId: inheritAnchor?.associatedQuestionId ?? null,
associatedAnchorRowId: inheritAnchor?.associatedAnchorRowId ?? null, associatedAnchorRowId: inheritAnchor?.associatedAnchorRowId ?? null,
prerequisiteQuestionIds: [] as number[], prerequisiteQuestionIds: [] as number[],
stimulusBlockKey: null as string | null,
questionTypeDefinitionId: null as number | null, questionTypeDefinitionId: null as number | null,
text: "", text: "",
difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD",
@ -318,18 +324,37 @@ export function QuestionsStep({
setExpandedQuestionIds(new Set([id])); 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)) { if (definitionUsesDynamicPayload(def)) {
return ( return (
<div className="space-y-3 rounded-lg border border-violet-200 bg-violet-50/40 p-3"> <div className="space-y-3 rounded-lg border border-violet-200 bg-violet-50/40 p-3">
<p className="text-xs leading-snug text-grayScale-600"> <p className="text-xs leading-snug text-grayScale-600">
{responseOnly ? (
<>
Shared stimulus comes from the linked block. Edit{" "}
<span className="font-medium text-grayScale-800">response</span> fields below.
Use overrides only when this question needs different stimulus than the block.
</>
) : (
<>
<span className="font-medium text-grayScale-800">Image, audio, and PDF</span> use upload or URL.{" "} <span className="font-medium text-grayScale-800">Image, audio, and PDF</span> use upload or URL.{" "}
<span className="font-medium text-grayScale-800">Table</span> uses the visual table builder. Timer and <span className="font-medium text-grayScale-800">Table</span> uses the visual table builder. Timer and
prep-time slots use seconds. Other slots use text or structured JSON where noted. prep-time slots use seconds. Other slots use text or structured JSON where noted.
</>
)}
</p> </p>
{def.stimulus_schema.length > 0 ? ( {!responseOnly ? (
def.stimulus_schema.length > 0 ? (
<div className="space-y-2"> <div className="space-y-2">
<p className="text-[10px] font-bold uppercase tracking-wide text-violet-800">Stimulus</p> <p className="text-[10px] font-bold uppercase tracking-wide text-violet-800">
Stimulus
</p>
{def.stimulus_schema.map((row) => ( {def.stimulus_schema.map((row) => (
<div <div
key={`stimulus-${row.id}`} key={`stimulus-${row.id}`}
@ -349,6 +374,33 @@ export function QuestionsStep({
</div> </div>
))} ))}
</div> </div>
) : null
) : def.stimulus_schema.length > 0 ? (
<details className="rounded-lg border border-violet-100 bg-white/80 p-3">
<summary className="cursor-pointer text-xs font-semibold text-violet-900">
Override block stimulus for this question (optional)
</summary>
<div className="mt-3 space-y-2">
{def.stimulus_schema.map((row) => (
<div
key={`stimulus-${row.id}`}
className="rounded-lg border border-grayScale-200 bg-white p-2.5"
>
<DynamicSchemaSlotField
row={row}
side="stimulus"
value={q.dynamicFieldValues?.[`stimulus:${row.id}`] ?? ""}
onChange={(next) =>
setDynamicValue(i, `stimulus:${row.id}`, next)
}
allFieldValues={q.dynamicFieldValues}
stimulusSchema={def.stimulus_schema}
responseSchema={def.response_schema}
/>
</div>
))}
</div>
</details>
) : null} ) : null}
{def.response_schema.length > 0 ? ( {def.response_schema.length > 0 ? (
<div className="space-y-2"> <div className="space-y-2">
@ -535,17 +587,41 @@ export function QuestionsStep({
); );
}; };
const ieltsMode = isIeltsSharedStimulusMode(formData.authoringProfile);
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="space-y-1 px-2"> <div className="space-y-1 px-2">
<h2 className="text-2xl font-bold text-grayScale-700">Questions</h2> <h2 className="text-2xl font-bold text-grayScale-700">Questions</h2>
<p className="text-grayScale-400 text-lg"> <p className="text-grayScale-400 text-lg">
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. Group questions into sections so learners complete earlier blocks before later ones unlock.
Collapse cards to compare and drag them into order. Collapse cards to compare and drag them into order.
</p> </p>
</div> </div>
{ieltsMode ? (
<div className="px-2">
<StimulusBlocksPanel
blocks={formData.stimulusBlocks ?? []}
questions={formData.questions}
onChange={(stimulusBlocks) => setFormData({ ...formData, stimulusBlocks })}
onClearQuestionBlockKeys={(blockKey) => {
setFormData({
...formData,
questions: formData.questions.map((row: { stimulusBlockKey?: string | null }) =>
row.stimulusBlockKey?.trim() === blockKey.trim()
? { ...row, stimulusBlockKey: null }
: row,
),
});
}}
/>
</div>
) : null}
{formData.questions.length > 1 ? ( {formData.questions.length > 1 ? (
<div className="flex flex-wrap items-center justify-end gap-2 px-2"> <div className="flex flex-wrap items-center justify-end gap-2 px-2">
<Button <Button
@ -651,6 +727,11 @@ export function QuestionsStep({
<span className="rounded-full bg-sky-100 px-2.5 py-0.5 text-[11px] font-semibold text-sky-800"> <span className="rounded-full bg-sky-100 px-2.5 py-0.5 text-[11px] font-semibold text-sky-800">
{sectionBadgeLabel(q, formData.questions)} {sectionBadgeLabel(q, formData.questions)}
</span> </span>
{q.stimulusBlockKey ? (
<span className="rounded-full bg-violet-100 px-2.5 py-0.5 text-[11px] font-semibold text-violet-800">
{q.stimulusBlockKey}
</span>
) : null}
<span className="text-xs font-medium text-grayScale-500"> <span className="text-xs font-medium text-grayScale-500">
{q.points ?? 1} pt{(q.points ?? 1) === 1 ? "" : "s"} {q.points ?? 1} pt{(q.points ?? 1) === 1 ? "" : "s"}
</span> </span>
@ -722,6 +803,39 @@ export function QuestionsStep({
}} }}
/> />
{ieltsMode ? (
<div className="space-y-2">
<label className="text-[10px] font-bold uppercase tracking-widest text-grayScale-700">
Shared stimulus block
</label>
<select
className="h-11 w-full max-w-xl rounded-lg border border-grayScale-200 bg-white px-3 text-sm font-medium text-grayScale-800"
value={q.stimulusBlockKey ?? ""}
onChange={(e) => {
const newQuestions = [...formData.questions];
newQuestions[i] = {
...newQuestions[i],
stimulusBlockKey: e.target.value ? e.target.value : null,
};
setFormData({ ...formData, questions: newQuestions });
}}
>
<option value="">None (standalone)</option>
{(formData.stimulusBlocks ?? [])
.slice()
.sort(
(a: { displayOrder?: number }, b: { displayOrder?: number }) =>
(a.displayOrder ?? 0) - (b.displayOrder ?? 0),
)
.map((block: { blockKey: string }) => (
<option key={block.blockKey} value={block.blockKey}>
{block.blockKey}
</option>
))}
</select>
</div>
) : null}
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2"> <div className="space-y-2">
<label className="text-[10px] font-bold uppercase tracking-widest text-grayScale-700"> <label className="text-[10px] font-bold uppercase tracking-widest text-grayScale-700">
@ -828,7 +942,9 @@ export function QuestionsStep({
</p> </p>
) : null} ) : null}
{def ? renderTypeSpecificFields(q, i, def) : null} {def ? renderTypeSpecificFields(q, i, def, {
responseOnly: ieltsMode && Boolean(q.stimulusBlockKey),
}) : null}
</div> </div>
</QuestionCollapsibleBody> </QuestionCollapsibleBody>
</div> </div>
@ -918,6 +1034,7 @@ export function QuestionsStep({
displayOrder: row.displayOrder, displayOrder: row.displayOrder,
associatedQuestionId: row.associatedQuestionId ?? null, associatedQuestionId: row.associatedQuestionId ?? null,
associatedAnchorRowId: row.associatedAnchorRowId ?? null, associatedAnchorRowId: row.associatedAnchorRowId ?? null,
stimulusBlockKey: row.stimulusBlockKey ?? null,
mcqOptions: (row.mcqOptions ?? []).map( mcqOptions: (row.mcqOptions ?? []).map(
(o: { text?: string; isCorrect?: boolean }) => ({ (o: { text?: string; isCorrect?: boolean }) => ({
option_text: String(o.text ?? ""), option_text: String(o.text ?? ""),
@ -940,10 +1057,21 @@ export function QuestionsStep({
toast.error("Check question sections", { description: associationErr }); toast.error("Check question sections", { description: associationErr });
return; return;
} }
const msg = validateLearnEnglishQuestionsWithDefinitions( const blockErr = isIeltsSharedStimulusMode(formData.authoringProfile)
? validatePracticeStimulusBlocks(
formData.authoringProfile ?? "STANDALONE",
formData.stimulusBlocks ?? [],
mapped, mapped,
typeDefinitions, typeDefinitions,
); )
: null;
if (blockErr) {
toast.error("Check stimulus blocks", { description: blockErr });
return;
}
const msg = isIeltsSharedStimulusMode(formData.authoringProfile)
? null
: validateLearnEnglishQuestionsWithDefinitions(mapped, typeDefinitions);
if (msg) { if (msg) {
toast.error("Check your questions", { description: msg }); toast.error("Check your questions", { description: msg });
return; return;

View File

@ -105,6 +105,54 @@ export function ScenarioStep({
/> />
<span>Shuffle questions in the set</span> <span>Shuffle questions in the set</span>
</label> </label>
<div className="rounded-xl border border-sky-100 bg-sky-50/50 px-4 py-4">
<label className="flex cursor-pointer items-start gap-3 text-sm text-grayScale-800">
<input
type="checkbox"
className="mt-0.5 h-4 w-4 rounded border-grayScale-300 text-sky-600 focus:ring-sky-500"
checked={formData.authoringProfile === "IELTS_SHARED_STIMULUS"}
onChange={(e) => {
const nextProfile = e.target.checked
? "IELTS_SHARED_STIMULUS"
: "STANDALONE";
if (
!e.target.checked &&
formData.authoringProfile === "IELTS_SHARED_STIMULUS" &&
(formData.stimulusBlocks?.length ?? 0) > 0
) {
const proceed = window.confirm(
"Switching off IELTS shared stimulus mode will remove stimulus blocks on save. Continue?",
);
if (!proceed) return;
}
setFormData({
...formData,
authoringProfile: nextProfile,
...(nextProfile === "STANDALONE"
? {
stimulusBlocks: [],
questions: (formData.questions ?? []).map(
(q: { stimulusBlockKey?: string | null }) => ({
...q,
stimulusBlockKey: null,
}),
),
}
: {}),
});
}}
/>
<span>
<span className="font-semibold text-sky-900">
Use shared stimulus sections (IELTS mode)
</span>
<span className="mt-1 block text-xs leading-relaxed text-sky-900/80">
Authors define shared audio, passages, or instructions per section.
</span>
</span>
</label>
</div>
</Card> </Card>
<Card className="p-8 space-y-6 border-grayScale-200 rounded-2xl bg-white"> <Card className="p-8 space-y-6 border-grayScale-200 rounded-2xl bg-white">

View File

@ -0,0 +1,257 @@
import { useState } from "react"
import { ChevronDown, Plus, Trash2 } from "lucide-react"
import { Button } from "../../../../components/ui/button"
import { Card } from "../../../../components/ui/card"
import { Input } from "../../../../components/ui/input"
import { DynamicSchemaSlotField } from "../../../../components/content-management/DynamicSchemaSlotField"
import { cn } from "../../../../lib/utils"
import {
countQuestionsReferencingBlock,
createEmptyBlockElement,
createEmptyStimulusBlock,
STIMULUS_BLOCK_KINDS,
stimulusBlockKindLabel,
type PracticeFormStimulusBlock,
} from "../../../../lib/practiceStimulusBlocks"
import { getStimulusKindPresentation } from "../question-type-steps/componentKindUi"
interface StimulusBlocksPanelProps {
blocks: PracticeFormStimulusBlock[]
questions: { stimulusBlockKey?: string | null }[]
onChange: (blocks: PracticeFormStimulusBlock[]) => void
onClearQuestionBlockKeys?: (blockKey: string) => void
}
export function StimulusBlocksPanel({
blocks,
questions,
onChange,
onClearQuestionBlockKeys,
}: StimulusBlocksPanelProps) {
const [expandedBlockKeys, setExpandedBlockKeys] = useState<Set<string>>(
() => new Set(blocks[0]?.blockKey ? [blocks[0].blockKey] : []),
)
const toggleBlock = (blockKey: string) => {
setExpandedBlockKeys((prev) => {
const next = new Set(prev)
if (next.has(blockKey)) next.delete(blockKey)
else next.add(blockKey)
return next
})
}
const updateBlock = (index: number, patch: Partial<PracticeFormStimulusBlock>) => {
const next = [...blocks]
next[index] = { ...next[index], ...patch }
onChange(next)
}
const removeBlock = (index: number) => {
const block = blocks[index]
const refCount = countQuestionsReferencingBlock(block.blockKey, questions)
if (refCount > 0) {
const proceed = window.confirm(
`${refCount} question(s) reference block "${block.blockKey}". Remove the block and clear those links?`,
)
if (!proceed) return
onClearQuestionBlockKeys?.(block.blockKey)
}
const next = blocks.filter((_, i) => i !== index)
onChange(
next.map((b, i) => ({
...b,
displayOrder: i + 1,
})),
)
}
const addBlock = () => {
const block = createEmptyStimulusBlock(blocks)
onChange([...blocks, block])
setExpandedBlockKeys(new Set([block.blockKey]))
}
return (
<div className="space-y-4">
<div className="space-y-1">
<h3 className="text-lg font-bold text-grayScale-800">Shared stimulus blocks</h3>
<p className="text-sm text-grayScale-500">
Define audio, passages, or instructions once per section. Link questions to a block
so they share that content.
</p>
</div>
{blocks.length === 0 ? (
<div className="rounded-xl border border-dashed border-sky-200 bg-sky-50/40 px-4 py-6 text-center text-sm text-sky-900">
No stimulus blocks yet. Add a block for each listening or reading section.
</div>
) : null}
<div className="space-y-3">
{blocks.map((block, blockIndex) => {
const expanded = expandedBlockKeys.has(block.blockKey)
const refCount = countQuestionsReferencingBlock(block.blockKey, questions)
return (
<Card
key={`${block.blockKey}-${blockIndex}`}
className="overflow-hidden rounded-2xl border border-sky-100 bg-white shadow-soft"
>
<div className="flex items-start gap-3 border-b border-grayScale-50 px-4 py-3 sm:px-5">
<button
type="button"
className="flex min-w-0 flex-1 items-start gap-3 text-left"
onClick={() => toggleBlock(block.blockKey)}
>
<ChevronDown
className={cn(
"mt-1 h-5 w-5 shrink-0 text-grayScale-400 transition-transform",
expanded && "rotate-180",
)}
/>
<div className="min-w-0 space-y-1">
<p className="text-base font-bold text-grayScale-800">
Block {block.displayOrder}
</p>
<p className="font-mono text-xs text-sky-700">{block.blockKey}</p>
<p className="text-xs text-grayScale-500">
{block.elements.length} element{block.elements.length === 1 ? "" : "s"}
{refCount > 0 ? ` · ${refCount} linked question${refCount === 1 ? "" : "s"}` : ""}
</p>
</div>
</button>
<Button
type="button"
variant="ghost"
size="icon"
className="shrink-0 text-brand-500 hover:bg-brand-50"
onClick={() => removeBlock(blockIndex)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
{expanded ? (
<div className="space-y-4 px-4 py-4 sm:px-5 sm:py-5">
<div className="space-y-2">
<label className="text-[10px] font-bold uppercase tracking-widest text-grayScale-700">
Block key
</label>
<Input
value={block.blockKey}
onChange={(e) =>
updateBlock(blockIndex, { blockKey: e.target.value })
}
className="font-mono text-sm"
placeholder="section-1"
/>
</div>
<div className="space-y-3">
<p className="text-[10px] font-bold uppercase tracking-wide text-sky-800">
Shared stimulus
</p>
{block.elements.map((element, elementIndex) => {
const presentation = getStimulusKindPresentation(element.kind)
const fieldValues: Record<string, string> = {
[`stimulus:${element.id}`]: element.fieldValue,
}
return (
<div
key={element.id}
className="rounded-lg border border-grayScale-200 bg-sky-50/30 p-3"
>
<div className="mb-2 flex items-center justify-between gap-2">
<div className="flex items-center gap-2 text-xs font-semibold text-grayScale-700">
<presentation.Icon className="h-4 w-4 text-sky-700" />
{presentation.label}
<span className="font-mono text-[10px] text-grayScale-400">
{element.id}
</span>
</div>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 text-grayScale-500"
onClick={() => {
const elements = block.elements.filter(
(_, i) => i !== elementIndex,
)
updateBlock(blockIndex, { elements })
}}
>
Remove
</Button>
</div>
<DynamicSchemaSlotField
row={{
id: element.id,
kind: element.kind,
label: stimulusBlockKindLabel(element.kind),
}}
side="stimulus"
value={element.fieldValue}
onChange={(next) => {
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={[]}
/>
</div>
)
})}
<div className="flex flex-wrap items-center gap-2">
<select
className="h-10 rounded-lg border border-grayScale-200 bg-white px-3 text-sm"
defaultValue=""
onChange={(e) => {
const kind = e.target.value
e.target.value = ""
if (!kind) return
const elements = [
...block.elements,
createEmptyBlockElement(kind, block.elements),
]
updateBlock(blockIndex, { elements })
}}
>
<option value="">Add stimulus element…</option>
{STIMULUS_BLOCK_KINDS.map((kind) => (
<option key={kind} value={kind}>
{stimulusBlockKindLabel(kind)}
</option>
))}
</select>
</div>
</div>
</div>
) : null}
</Card>
)
})}
</div>
<button
type="button"
onClick={addBlock}
className="flex items-center gap-3 text-base font-bold text-sky-700 transition-all hover:opacity-80"
>
<div className="flex h-5 w-5 items-center justify-center rounded-full border-2 border-sky-600">
<Plus className="h-3 w-3 stroke-[4]" />
</div>
Add stimulus block
</button>
</div>
)
}

View File

@ -762,16 +762,27 @@ export interface UpdatePracticeParentsResponse {
metadata: unknown | null 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. */ /** Question row in GET/PUT /practices/:id/full and /exam-prep/practices/:id/full. */
export interface PracticeFullQuestionItem { export interface PracticeFullQuestionItem {
id?: number | null id?: number | null
display_order: number display_order: number
associated_question_id?: number | null associated_question_id?: number | null
prerequisite_question_ids?: number[] prerequisite_question_ids?: number[]
stimulus_block_key?: string | null
question_text?: string question_text?: string
question_type: string question_type: string
question_type_definition_id?: number | null question_type_definition_id?: number | null
dynamic_payload?: DynamicQuestionPayload | null dynamic_payload?: DynamicQuestionPayload | null
effective_dynamic_payload?: DynamicQuestionPayload | null
difficulty_level?: string difficulty_level?: string
points?: number points?: number
status?: PracticePublishStatus | string status?: PracticePublishStatus | string
@ -810,6 +821,7 @@ export interface PracticeFullPractice {
story_image?: string story_image?: string
persona_id?: number | null persona_id?: number | null
question_set_id: number question_set_id: number
authoring_profile?: AuthoringProfile | string | null
publish_status?: PracticePublishStatus | string | null publish_status?: PracticePublishStatus | string | null
quick_tips?: string quick_tips?: string
parents?: PracticeParent[] parents?: PracticeParent[]
@ -825,6 +837,7 @@ export interface PracticeFullPractice {
export interface PracticeFullData { export interface PracticeFullData {
practice: PracticeFullPractice practice: PracticeFullPractice
question_set: PracticeFullQuestionSet question_set: PracticeFullQuestionSet
stimulus_blocks?: PracticeStimulusBlock[]
questions: PracticeFullQuestionItem[] questions: PracticeFullQuestionItem[]
} }
@ -836,6 +849,12 @@ export interface GetPracticeFullResponse {
metadata: unknown | null metadata: unknown | null
} }
export interface UpdatePracticeFullStimulusBlockItem {
block_key: string
display_order?: number
stimulus: import("./questionTypeDefinition.types").DynamicElementInstance[]
}
export interface UpdatePracticeFullRequest { export interface UpdatePracticeFullRequest {
practice: { practice: {
title: string title: string
@ -844,6 +863,7 @@ export interface UpdatePracticeFullRequest {
persona_id: number persona_id: number
quick_tips: string quick_tips: string
publish_status: PracticePublishStatus publish_status: PracticePublishStatus
authoring_profile?: AuthoringProfile
} }
question_set: { question_set: {
title: string title: string
@ -854,6 +874,7 @@ export interface UpdatePracticeFullRequest {
status: PracticePublishStatus status: PracticePublishStatus
intro_video_url?: string | null intro_video_url?: string | null
} }
stimulus_blocks?: UpdatePracticeFullStimulusBlockItem[]
questions: PracticeFullQuestionItem[] questions: PracticeFullQuestionItem[]
} }

View File

@ -61,17 +61,25 @@ export interface DynamicQuestionPayload {
response: DynamicElementInstance[] response: DynamicElementInstance[]
} }
export type QuestionTypeDefinitionPracticeKind = "LMS" | "EXAM_PREP"
/** Row from GET /questions/type-definitions/:id/practices */ /** Row from GET /questions/type-definitions/:id/practices */
export interface QuestionTypeDefinitionPractice { export interface QuestionTypeDefinitionPractice {
practice_kind: string practice_kind: QuestionTypeDefinitionPracticeKind
practice_id: number practice_id: number
question_set_id: number question_set_id: number
title: string title: string
story_description?: string story_description?: string
story_image?: string story_image?: string
persona_id?: number
quick_tips?: string quick_tips?: string
publish_status?: string publish_status?: "DRAFT" | "PUBLISHED" | string
/** LMS hierarchy links — read when `practice_kind === "LMS"`. */
parents: PracticeParent[] | null 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[] */ /** @deprecated use parents[] */
parent_kind?: string parent_kind?: string
/** @deprecated use parents[] */ /** @deprecated use parents[] */