Fix IELTS shared-stimulus practice edit and add question-bank attach.

Restore the missing stimulus hydration import so Listening/Reading MC practices load, and allow attaching existing bank questions while surfacing clearer edit-load errors.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-08-06 22:14:48 +03:00
parent 776f7a2872
commit 72384a5980
12 changed files with 1058 additions and 16 deletions

View File

@ -977,7 +977,9 @@ export const updateParentLinkedPractice = (
/** GET /practices/:id/full — Learn English practice with question set and questions. */
export const getLearnEnglishPracticeFull = (practiceId: number) =>
http.get<GetPracticeFullResponse>(`/practices/${practiceId}/full`)
http.get<GetPracticeFullResponse>(`/practices/${practiceId}/full`, {
skipErrorToast: true,
})
/** PUT /practices/:id/full — atomic update of practice, question set, and questions. */
export const updateLearnEnglishPracticeFull = (
@ -988,7 +990,9 @@ export const updateLearnEnglishPracticeFull = (
/** GET /exam-prep/practices/:id/full */
export const getExamPrepPracticeFull = (practiceId: number) =>
http.get<GetPracticeFullResponse>(`/exam-prep/practices/${practiceId}/full`)
http.get<GetPracticeFullResponse>(`/exam-prep/practices/${practiceId}/full`, {
skipErrorToast: true,
})
/** PUT /exam-prep/practices/:id/full */
export const updateExamPrepPracticeFull = (

View File

@ -24,6 +24,13 @@ export function getApiErrorMessage(error: unknown, fallback: string): string {
if (axios.isAxiosError(error)) {
const message = readApiResponseMessage(error.response?.data)
if (message) return message
if (error.message?.trim()) return error.message.trim()
}
if (error instanceof Error && error.message.trim()) {
return error.message.trim()
}
if (typeof error === "string" && error.trim()) {
return error.trim()
}
return fallback
}

View File

@ -185,6 +185,8 @@ export type QuestionDifficultyLevel = "EASY" | "MEDIUM" | "HARD"
export interface LearnEnglishDefinitionQuestionInput {
clientRowId?: string
/** When set, practice creation attaches this bank question instead of creating a new one. */
serverQuestionId?: number | null
questionText: string
questionTypeDefinitionId: number
dynamicFieldValues: Record<string, string>
@ -204,6 +206,12 @@ export interface LearnEnglishDefinitionQuestionInput {
sampleAnswerVoiceUrl?: string
}
export function isExistingBankQuestion(
q: Pick<LearnEnglishDefinitionQuestionInput, "serverQuestionId">,
): boolean {
return q.serverQuestionId != null && Number(q.serverQuestionId) > 0
}
export function questionRowHasContent(
q: LearnEnglishDefinitionQuestionInput,
def: QuestionTypeDefinition,

View File

@ -17,6 +17,7 @@ import {
} from "./practiceParents"
import {
buildCreateQuestionFromDefinition,
isExistingBankQuestion,
questionRowHasContent,
validateDefinitionQuestion,
type LearnEnglishDefinitionQuestionInput,
@ -71,12 +72,16 @@ export function validatePracticeQuestionsWithDefinitions(
): string | null {
const byId = new Map(definitions.map((d) => [d.id, d]))
const filled = questions.filter((q) => {
if (isExistingBankQuestion(q)) return true
const def = byId.get(q.questionTypeDefinitionId)
return def ? questionRowHasContent(q, def) : false
})
if (filled.length === 0) return "Add at least one question with content."
if (filled.length === 0) {
return "Add at least one question with content, or attach questions from the bank."
}
for (let i = 0; i < filled.length; i++) {
const q = filled[i]
if (isExistingBankQuestion(q)) continue
if (!Number.isFinite(q.questionTypeDefinitionId) || q.questionTypeDefinitionId <= 0) {
return `Question ${i + 1}: select a question type from the list.`
}
@ -137,6 +142,7 @@ export async function executePracticeCreation(
: index + 1,
}))
.filter(({ q }) => {
if (isExistingBankQuestion(q)) return true
const def = byId.get(q.questionTypeDefinitionId)
return def ? questionRowHasContent(q, def) : false
})
@ -144,7 +150,7 @@ export async function executePracticeCreation(
const associationRows = toCreate.map(({ q, sortOrder }) => ({
id: q.clientRowId ?? `row-${sortOrder}`,
serverQuestionId: null as number | null,
serverQuestionId: isExistingBankQuestion(q) ? Number(q.serverQuestionId) : null,
displayOrder: sortOrder,
associatedQuestionId: q.associatedQuestionId ?? null,
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
@ -152,17 +158,27 @@ export async function executePracticeCreation(
const associationErr = validateQuestionAssociations(associationRows)
if (associationErr) throw new Error(associationErr)
// Steps 2 & 3 — create questions and attach to set (order from step 3 drag-and-drop)
// Steps 2 & 3 — create new questions (or reuse bank IDs) and attach to set
let displayOrder = 0
const rowIdToServerId = new Map<string, number>()
for (const row of associationRows) {
if (row.serverQuestionId != null && row.serverQuestionId > 0) {
rowIdToServerId.set(row.id, row.serverQuestionId)
}
}
for (const { q, sortOrder } of toCreate) {
const def = byId.get(q.questionTypeDefinitionId)
if (!def) throw new Error(`Missing definition #${q.questionTypeDefinitionId}`)
displayOrder += 1
const payload = buildCreateQuestionFromDefinition(def, q, opts.status)
const qRes = await createQuestion(payload)
const questionId = extractCreatedResourceId(qRes, "Could not create question")
const rowKey = q.clientRowId ?? `row-${sortOrder}`
let questionId: number
if (isExistingBankQuestion(q)) {
questionId = Number(q.serverQuestionId)
} else {
const def = byId.get(q.questionTypeDefinitionId)
if (!def) throw new Error(`Missing definition #${q.questionTypeDefinitionId}`)
const payload = buildCreateQuestionFromDefinition(def, q, opts.status)
const qRes = await createQuestion(payload)
questionId = extractCreatedResourceId(qRes, "Could not create question")
}
rowIdToServerId.set(rowKey, questionId)
const associationRow = {

View File

@ -7,6 +7,7 @@ import type {
PracticeParent,
PracticePublishStatus,
AuthoringProfile,
QuestionDetail,
QuestionOption,
QuestionShortAnswer,
UpdatePracticeFullRequest,
@ -566,6 +567,34 @@ function mapFullQuestionToFormRow(
}
}
/** Map a question-bank detail into a practice form row for attach-from-bank. */
export function mapQuestionDetailToPracticeFormRow(
detail: QuestionDetail,
typeDefinitions: QuestionTypeDefinition[],
displayOrder: number,
): PracticeFormQuestionRow {
const item: PracticeFullQuestionItem = {
id: detail.id,
display_order: displayOrder,
question_text: detail.question_text,
question_type: detail.question_type,
question_type_definition_id: detail.question_type_definition_id ?? null,
dynamic_payload: detail.dynamic_payload ?? null,
difficulty_level: detail.difficulty_level ?? undefined,
points: detail.points ?? undefined,
status: detail.status,
options: detail.options,
short_answers: detail.short_answers,
voice_prompt: detail.voice_prompt ?? undefined,
sample_answer_voice_prompt: detail.sample_answer_voice_prompt ?? undefined,
audio_correct_answer_text: detail.audio_correct_answer_text ?? undefined,
image_url: detail.image_url ?? undefined,
tips: detail.tips ?? undefined,
explanation: detail.explanation ?? undefined,
}
return mapFullQuestionToFormRow(item, typeDefinitions)
}
function parsePersonaIdValue(value: unknown): number | null {
if (value == null) return null
const n = Number(value)
@ -758,6 +787,7 @@ export function buildPracticeFullUpdateRequest(
: index + 1,
}))
.filter(({ q }) => {
if (q.serverQuestionId != null && Number(q.serverQuestionId) > 0) return true
const def = byId.get(q.questionTypeDefinitionId)
return def ? questionRowHasContent(q, def) : false
})
@ -777,7 +807,39 @@ export function buildPracticeFullUpdateRequest(
const questions: PracticeFullQuestionItem[] = []
for (const { q, sortOrder } of toUpdate) {
const def = byId.get(q.questionTypeDefinitionId)
if (!def) continue
if (!def) {
if (q.serverQuestionId != null && Number(q.serverQuestionId) > 0) {
displayOrder += 1
const associationRow = {
id: q.clientRowId ?? `update-${sortOrder}`,
serverQuestionId: q.serverQuestionId ?? null,
displayOrder: sortOrder,
associatedQuestionId: q.associatedQuestionId ?? null,
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
}
questions.push({
id: Number(q.serverQuestionId),
display_order: displayOrder,
associated_question_id: resolveAssociatedQuestionId(
associationRow,
associationRows,
new Map(
associationRows
.filter((r) => r.serverQuestionId != null && r.serverQuestionId > 0)
.map((r) => [r.id, r.serverQuestionId as number]),
),
),
question_type: "DYNAMIC",
difficulty_level: q.difficultyLevel ?? "EASY",
points: q.points ?? 1,
status: opts.status,
...(q.stimulusBlockKey?.trim()
? { stimulus_block_key: q.stimulusBlockKey.trim() }
: {}),
})
}
continue
}
displayOrder += 1
const associationRow = {
id: q.clientRowId ?? `update-${sortOrder}`,
@ -834,5 +896,16 @@ export function unwrapPracticeFullData(
if (!body) return null
const raw = body.data ?? body.Data ?? null
if (!raw) return null
return normalizePracticeFullData(raw) ?? (raw as PracticeFullData)
const normalized = normalizePracticeFullData(raw)
if (normalized) return normalized
// Fall back only when the payload already looks usable.
const record = asRecord(raw)
if (!record) return null
const practice = record.practice ?? record.Practice
const questionSet = record.question_set ?? record.QuestionSet ?? record.questionSet
const questions = record.questions ?? record.Questions
if (!asRecord(practice) || !asRecord(questionSet) || !Array.isArray(questions)) {
return null
}
return raw as PracticeFullData
}

View File

@ -4,10 +4,14 @@ import type {
DynamicQuestionPayload,
QuestionTypeDefinition,
} from "../types/questionTypeDefinition.types"
import { buildDynamicQuestionPayload } from "./practiceDynamicQuestionPayload"
import {
buildDynamicQuestionPayload,
dynamicPayloadToFieldValues,
} from "./practiceDynamicQuestionPayload"
import {
validateDefinitionQuestion,
questionRowHasContent,
isExistingBankQuestion,
type LearnEnglishDefinitionQuestionInput,
} from "./learnEnglishDefinitionQuestion"
import { isNoInputComponentKind } from "./questionComponentKinds"
@ -196,12 +200,16 @@ export function validatePracticeStimulusBlocks(
if (keyErr) return keyErr
const byId = new Map(definitions.map((d) => [d.id, d]))
const filled = questions.filter((q) => {
if (isExistingBankQuestion(q)) return true
const def = byId.get(q.questionTypeDefinitionId)
return def ? questionRowHasContent(q, def) : false
})
if (filled.length === 0) return "Add at least one question with content."
if (filled.length === 0) {
return "Add at least one question with content, or attach questions from the bank."
}
for (let i = 0; i < filled.length; i++) {
const q = filled[i]
if (isExistingBankQuestion(q)) continue
const def = byId.get(q.questionTypeDefinitionId)
if (!def) {
return `Question ${i + 1}: type definition #${q.questionTypeDefinitionId} was not found. Refresh and try again.`

View File

@ -0,0 +1,434 @@
import { getSearchTokens } from "../components/SearchHighlight"
import { questionTypeDefinitionListLabel } from "../api/questionTypeDefinitions.api"
import type { QuestionDetail } from "../types/course.types"
import type {
DynamicElementInstance,
DynamicQuestionPayload,
QuestionTypeDefinition,
} from "../types/questionTypeDefinition.types"
const LEGACY_TYPE_LABELS: Record<string, string> = {
MCQ: "Multiple choice",
MULTIPLE_CHOICE: "Multiple choice",
TRUE_FALSE: "True / False",
SHORT_ANSWER: "Short answer",
SHORT: "Short answer",
AUDIO: "Audio",
DYNAMIC: "Interactive",
}
const DIFFICULTY_LABELS: Record<string, string> = {
EASY: "Easy",
MEDIUM: "Medium",
HARD: "Hard",
}
const STATUS_LABELS: Record<string, string> = {
DRAFT: "Draft",
PUBLISHED: "Published",
INACTIVE: "Inactive",
}
const PREFERRED_STIMULUS_KINDS = [
"QUESTION_TEXT",
"INSTRUCTION",
"TEXT_PASSAGE",
"TEXT",
] as const
function titleCaseWords(value: string): string {
return value
.trim()
.toLowerCase()
.split(/[_\s-]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(" ")
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === "object" && !Array.isArray(value)
}
function pickStr(record: Record<string, unknown>, ...keys: string[]): string {
for (const key of keys) {
const value = record[key]
if (typeof value === "string" && value.trim()) return value.trim()
if (typeof value === "number" && Number.isFinite(value)) return String(value)
}
return ""
}
function elementStringValue(value: unknown): string {
if (typeof value === "string") {
const trimmed = value.trim()
if (!trimmed) return ""
if (
(trimmed.startsWith("{") && trimmed.endsWith("}")) ||
(trimmed.startsWith("[") && trimmed.endsWith("]"))
) {
try {
return elementStringValue(JSON.parse(trimmed))
} catch {
return trimmed
}
}
return trimmed
}
if (typeof value === "number" && Number.isFinite(value)) return String(value)
if (Array.isArray(value)) {
for (const item of value) {
const nested = elementStringValue(item)
if (nested) return nested
}
return ""
}
if (isRecord(value)) {
for (const key of [
"text",
"content",
"value",
"label",
"prompt",
"instruction",
"question_text",
"questionText",
"option_text",
"optionText",
]) {
const nested = elementStringValue(value[key])
if (nested) return nested
}
}
return ""
}
function collectStringsFromValue(value: unknown, into: string[]): void {
if (typeof value === "string") {
const text = elementStringValue(value)
if (text && !/^https?:\/\//i.test(text) && text.length < 500) into.push(text)
return
}
if (typeof value === "number" && Number.isFinite(value)) {
into.push(String(value))
return
}
if (Array.isArray(value)) {
for (const item of value) collectStringsFromValue(item, into)
return
}
if (isRecord(value)) {
for (const nested of Object.values(value)) collectStringsFromValue(nested, into)
}
}
function asDynamicPayload(raw: unknown): DynamicQuestionPayload | null {
if (!isRecord(raw)) return null
const stimulus = Array.isArray(raw.stimulus)
? raw.stimulus
: Array.isArray(raw.Stimulus)
? raw.Stimulus
: []
const response = Array.isArray(raw.response)
? raw.response
: Array.isArray(raw.Response)
? raw.Response
: []
if (stimulus.length === 0 && response.length === 0) return null
return {
stimulus: stimulus.filter(isRecord).map((el) => ({
id: String(el.id ?? el.ID ?? ""),
kind: String(el.kind ?? el.Kind ?? ""),
value: el.value ?? el.Value,
meta: isRecord(el.meta) ? el.meta : isRecord(el.Meta) ? el.Meta : undefined,
})),
response: response.filter(isRecord).map((el) => ({
id: String(el.id ?? el.ID ?? ""),
kind: String(el.kind ?? el.Kind ?? ""),
value: el.value ?? el.Value,
meta: isRecord(el.meta) ? el.meta : isRecord(el.Meta) ? el.Meta : undefined,
})),
}
}
function stimulusTextFromPayload(payload: DynamicQuestionPayload | null | undefined): string {
if (!payload?.stimulus?.length) return ""
for (const want of PREFERRED_STIMULUS_KINDS) {
for (const el of payload.stimulus) {
if (String(el.kind ?? "").toUpperCase() !== want) continue
const text = elementStringValue(el.value)
if (text) return text
}
}
for (const el of payload.stimulus) {
const text = elementStringValue(el.value)
if (text) return text
}
return ""
}
function uniqueNonEmpty(values: string[]): string[] {
const seen = new Set<string>()
const out: string[] = []
for (const raw of values) {
const text = String(raw ?? "").trim()
if (!text) continue
if (/^https?:\/\//i.test(text)) continue
if (text.length > 400) continue
const key = text.toLowerCase()
if (seen.has(key)) continue
seen.add(key)
out.push(text)
}
return out
}
/** Prefer human-readable phrases; drop option ids / bare numbers from list display. */
function isUsefulDisplaySnippet(text: string): boolean {
const t = text.trim()
if (t.length < 2) return false
if (/^[a-z0-9]$/i.test(t)) return false
if (/^\d{1,4}$/.test(t)) return false
if (/^[a-z]$/i.test(t)) return false
return true
}
function textsFromElements(elements: DynamicElementInstance[] | undefined): string[] {
if (!elements?.length) return []
const out: string[] = []
for (const el of elements) {
collectStringsFromValue(el.value, out)
}
return uniqueNonEmpty(out)
}
/** All readable strings from stimulus slots. */
export function questionBankStimulusTexts(
question: QuestionDetail,
): string[] {
return textsFromElements(question.dynamic_payload?.stimulus)
}
/** All readable strings from response slots (choices, matches, prompts, etc.). */
export function questionBankResponseTexts(
question: QuestionDetail,
): string[] {
const fromPayload = textsFromElements(question.dynamic_payload?.response)
const fromOptions = (question.options ?? [])
.map((o) => String(o.option_text ?? "").trim())
.filter(Boolean)
return uniqueNonEmpty([...fromPayload, ...fromOptions])
}
function payloadSearchStrings(payload: DynamicQuestionPayload | null | undefined): string[] {
if (!payload) return []
return uniqueNonEmpty([
...textsFromElements(payload.stimulus),
...textsFromElements(payload.response),
])
}
function joinPreviewParts(parts: string[], max = 3): string {
return parts.slice(0, max).join(" · ")
}
/** Normalize a list/detail API row into a consistent QuestionDetail for bank UI. */
export function normalizeQuestionBankItem(raw: unknown): QuestionDetail | null {
if (!isRecord(raw)) return null
const id = Number(raw.id ?? raw.ID ?? raw.question_id ?? raw.QuestionID)
if (!Number.isFinite(id) || id <= 0) return null
const payload =
asDynamicPayload(raw.effective_dynamic_payload) ??
asDynamicPayload(raw.EffectiveDynamicPayload) ??
asDynamicPayload(raw.dynamic_payload) ??
asDynamicPayload(raw.DynamicPayload)
const previewText = pickStr(raw, "preview_text", "PreviewText", "previewText")
const stimulusTexts = textsFromElements(payload?.stimulus)
const responseTexts = textsFromElements(payload?.response)
const questionText =
pickStr(raw, "question_text", "QuestionText", "questionText") ||
previewText ||
stimulusTextFromPayload(payload) ||
stimulusTexts[0] ||
responseTexts[0] ||
""
const optionsRaw = raw.options ?? raw.Options
const options = Array.isArray(optionsRaw)
? optionsRaw
.filter(isRecord)
.map((o, index) => ({
option_order: Number(o.option_order ?? o.OptionOrder ?? index + 1),
option_text: pickStr(o, "option_text", "OptionText", "text", "label"),
is_correct: Boolean(o.is_correct ?? o.IsCorrect),
}))
.filter((o) => o.option_text)
: undefined
const defId = Number(
raw.question_type_definition_id ??
raw.QuestionTypeDefinitionID ??
raw.questionTypeDefinitionId,
)
const resolvedPreview =
previewText ||
questionText ||
joinPreviewParts(stimulusTexts) ||
joinPreviewParts(responseTexts) ||
undefined
return {
id,
question_text: questionText,
preview_text: resolvedPreview,
question_type: pickStr(raw, "question_type", "QuestionType", "questionType") || "DYNAMIC",
difficulty_level:
pickStr(raw, "difficulty_level", "DifficultyLevel", "difficultyLevel") || null,
points: Number(raw.points ?? raw.Points ?? 1) || 1,
status:
pickStr(raw, "status", "Status", "question_status", "QuestionStatus") || undefined,
tips: pickStr(raw, "tips", "Tips") || null,
explanation: pickStr(raw, "explanation", "Explanation") || null,
options,
question_type_definition_id:
Number.isFinite(defId) && defId > 0 ? defId : null,
dynamic_payload: payload,
}
}
export function formatQuestionBankTypeLabel(
question: QuestionDetail,
definitions: QuestionTypeDefinition[] = [],
): string {
const defId = question.question_type_definition_id
if (defId != null && Number(defId) > 0) {
const def = definitions.find((d) => d.id === Number(defId))
if (def) return questionTypeDefinitionListLabel(def)
}
const raw = String(question.question_type ?? "").trim().toUpperCase()
if (!raw) return "Question"
return LEGACY_TYPE_LABELS[raw] ?? titleCaseWords(raw)
}
export function formatQuestionBankDifficultyLabel(
difficulty: string | null | undefined,
): string {
const raw = String(difficulty ?? "").trim().toUpperCase()
if (!raw) return ""
return DIFFICULTY_LABELS[raw] ?? titleCaseWords(raw)
}
export function formatQuestionBankStatusLabel(
status: string | null | undefined,
): string {
const raw = String(status ?? "").trim().toUpperCase()
if (!raw) return ""
return STATUS_LABELS[raw] ?? titleCaseWords(raw)
}
/** Learner-facing prompt text for list rows (stimulus first, then response). */
export function questionBankPreviewText(question: QuestionDetail): string {
const preview = String(question.preview_text ?? "").trim()
if (preview) return preview
const flat = String(question.question_text ?? "").trim()
if (flat) return flat
const stimulus = questionBankStimulusTexts(question)
if (stimulus.length > 0) return joinPreviewParts(stimulus)
const response = questionBankResponseTexts(question)
if (response.length > 0) return joinPreviewParts(response)
const tip = String(question.tips ?? "").trim()
if (tip) return tip
return "Untitled question"
}
/** Response-side wording shown under the main preview (choices, match items, etc.). */
export function questionBankResponsePreviewText(question: QuestionDetail): string {
const stimulus = new Set(
questionBankStimulusTexts(question).map((t) => t.toLowerCase()),
)
const primary = questionBankPreviewText(question).toLowerCase()
const response = questionBankResponseTexts(question).filter((text) => {
const key = text.toLowerCase()
if (key === primary || stimulus.has(key)) return false
return isUsefulDisplaySnippet(text)
})
if (response.length === 0) return ""
return joinPreviewParts(response, 4)
}
export interface QuestionBankListLabels {
/** Primary list line — mainly stimulus / prompt text. */
preview: string
/** Secondary list line — response content (options, matches, etc.). */
responsePreview: string
typeLabel: string
difficultyLabel: string
statusLabel: string
}
export function getQuestionBankListLabels(
question: QuestionDetail,
definitions: QuestionTypeDefinition[] = [],
): QuestionBankListLabels {
return {
preview: questionBankPreviewText(question),
responsePreview: questionBankResponsePreviewText(question),
typeLabel: formatQuestionBankTypeLabel(question, definitions),
difficultyLabel: formatQuestionBankDifficultyLabel(question.difficulty_level),
statusLabel: formatQuestionBankStatusLabel(question.status),
}
}
/** Keywords used for search (stimulus + response + friendly labels). */
export function questionBankSearchKeywords(
question: QuestionDetail,
labels: QuestionBankListLabels,
): string[] {
const rawType = String(question.question_type ?? "").trim()
const rawDifficulty = String(question.difficulty_level ?? "").trim()
const rawStatus = String(question.status ?? "").trim()
return uniqueNonEmpty([
labels.preview,
labels.responsePreview,
labels.typeLabel,
labels.difficultyLabel,
labels.statusLabel,
rawType,
rawDifficulty,
rawStatus,
String(question.tips ?? "").trim(),
String(question.explanation ?? "").trim(),
...questionBankStimulusTexts(question),
...questionBankResponseTexts(question),
...payloadSearchStrings(question.dynamic_payload),
])
}
export function matchesQuestionBankSearch(
question: QuestionDetail,
query: string,
definitions: QuestionTypeDefinition[] = [],
): boolean {
const tokens = getSearchTokens(query)
if (tokens.length === 0) return true
const haystack = buildQuestionBankSearchHaystack(question, definitions)
return tokens.every((token) => haystack.includes(token.toLowerCase()))
}
/** Lowercased keyword blob for fast client-side filtering (no API calls). */
export function buildQuestionBankSearchHaystack(
question: QuestionDetail,
definitions: QuestionTypeDefinition[] = [],
): string {
const labels = getQuestionBankListLabels(question, definitions)
return questionBankSearchKeywords(question, labels).join(" ").toLowerCase()
}
export function matchesQuestionBankHaystack(haystack: string, query: string): boolean {
const tokens = getSearchTokens(query)
if (tokens.length === 0) return true
return tokens.every((token) => haystack.includes(token.toLowerCase()))
}

View File

@ -382,6 +382,7 @@ export function AddPracticeFlow() {
const persona = personaFromId(selectedPersona, personas);
const mappedQuestions = formData.questions.map((q, index) => ({
clientRowId: q.id,
serverQuestionId: q.serverQuestionId ?? null,
questionText: String(q.text ?? "").trim(),
questionTypeDefinitionId: Number(q.questionTypeDefinitionId),
difficultyLevel: (q.difficultyLevel ?? "EASY") as

View File

@ -349,13 +349,21 @@ export function EditPracticeFlow() {
// Hierarchy URLs / mislabeled kind: retry the other practice table.
try {
res = await loadFallback(practiceId);
} catch {
} catch (fallbackError) {
const primaryMsg = getApiErrorMessage(primaryError, "");
const fallbackMsg = getApiErrorMessage(fallbackError, "");
if (primaryMsg && fallbackMsg && primaryMsg !== fallbackMsg) {
throw new Error(`${primaryMsg} (also tried alternate API: ${fallbackMsg})`);
}
throw primaryError;
}
}
const full = unwrapPracticeFullData(res);
if (!full) throw new Error("Practice details were missing from the response.");
if (!full.practice || !full.question_set || !Array.isArray(full.questions)) {
throw new Error("Practice response was incomplete (missing practice, question set, or questions).");
}
const mapped = mapPracticeFullToFormState(full, typeDefinitions);
if (cancelled) return;
const loadedPersona =

View File

@ -0,0 +1,372 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { Library, Search } from "lucide-react"
import { toast } from "sonner"
import { getQuestions } from "../../../../api/courses.api"
import { SearchHighlight } from "../../../../components/SearchHighlight"
import { Button } from "../../../../components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../../../../components/ui/dialog"
import { Input } from "../../../../components/ui/input"
import { getApiErrorMessage } from "../../../../lib/apiErrors"
import {
buildQuestionBankSearchHaystack,
getQuestionBankListLabels,
matchesQuestionBankHaystack,
normalizeQuestionBankItem,
type QuestionBankListLabels,
} from "../../../../lib/questionBankDisplay"
import type { QuestionDetail } from "../../../../types/course.types"
import type { QuestionTypeDefinition } from "../../../../types/questionTypeDefinition.types"
import { cn } from "../../../../lib/utils"
const BANK_CACHE_TTL_MS = 5 * 60 * 1000
const BANK_PAGE_SIZE = 200
let bankCache: { fetchedAt: number; questions: QuestionDetail[] } | null = null
let bankFetchInFlight: Promise<QuestionDetail[]> | null = null
function unwrapQuestionsPayload(payload: unknown): unknown[] {
if (Array.isArray(payload)) return payload
if (
payload &&
typeof payload === "object" &&
Array.isArray((payload as { questions?: unknown[] }).questions)
) {
return (payload as { questions: unknown[] }).questions
}
if (
payload &&
typeof payload === "object" &&
Array.isArray((payload as { Questions?: unknown[] }).Questions)
) {
return (payload as { Questions: unknown[] }).Questions
}
return []
}
function readChunkTotal(payload: unknown, metaTotal?: number): number | undefined {
if (typeof metaTotal === "number" && Number.isFinite(metaTotal)) return metaTotal
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined
const record = payload as Record<string, unknown>
const direct = Number(record.total_count ?? record.TotalCount)
if (Number.isFinite(direct)) return direct
return undefined
}
async function fetchAllBankQuestions(): Promise<QuestionDetail[]> {
const firstRes = await getQuestions({ limit: BANK_PAGE_SIZE, offset: 0 })
const firstPayload = firstRes.data?.data as unknown
const firstMeta = firstRes.data?.metadata as { total_count?: number } | null | undefined
const firstRaw = unwrapQuestionsPayload(firstPayload)
const firstChunk = firstRaw
.map((row) => normalizeQuestionBankItem(row))
.filter((row): row is QuestionDetail => row != null)
const total =
readChunkTotal(firstPayload, firstMeta?.total_count) ?? firstChunk.length
if (firstRaw.length < BANK_PAGE_SIZE || firstChunk.length >= total) {
return firstChunk
}
const offsets: number[] = []
for (let offset = BANK_PAGE_SIZE; offset < total; offset += BANK_PAGE_SIZE) {
offsets.push(offset)
}
const pages = await Promise.all(
offsets.map(async (offset) => {
const res = await getQuestions({ limit: BANK_PAGE_SIZE, offset })
const payload = res.data?.data as unknown
return unwrapQuestionsPayload(payload)
.map((row) => normalizeQuestionBankItem(row))
.filter((row): row is QuestionDetail => row != null)
}),
)
return [...firstChunk, ...pages.flat()]
}
async function loadQuestionBank(options?: {
force?: boolean
}): Promise<QuestionDetail[]> {
const now = Date.now()
if (
!options?.force &&
bankCache &&
now - bankCache.fetchedAt < BANK_CACHE_TTL_MS
) {
return bankCache.questions
}
if (bankFetchInFlight) return bankFetchInFlight
bankFetchInFlight = fetchAllBankQuestions()
.then((questions) => {
bankCache = { fetchedAt: Date.now(), questions }
return questions
})
.finally(() => {
bankFetchInFlight = null
})
return bankFetchInFlight
}
interface BankListRow {
question: QuestionDetail
labels: QuestionBankListLabels
haystack: string
}
interface QuestionBankAttachDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Question IDs already on this practice — hidden from selection. */
excludeIds: number[]
onAttach: (questions: QuestionDetail[]) => void
typeDefinitions?: QuestionTypeDefinition[]
}
export function QuestionBankAttachDialog({
open,
onOpenChange,
excludeIds,
onAttach,
typeDefinitions = [],
}: QuestionBankAttachDialogProps) {
const [loading, setLoading] = useState(false)
const [attaching, setAttaching] = useState(false)
const [questions, setQuestions] = useState<QuestionDetail[]>(
() => bankCache?.questions ?? [],
)
const [searchQuery, setSearchQuery] = useState("")
const [selectedIds, setSelectedIds] = useState<number[]>([])
const excluded = useMemo(() => new Set(excludeIds.filter((id) => id > 0)), [excludeIds])
const hydrateBank = useCallback(async () => {
const hasWarmCache =
bankCache != null && Date.now() - bankCache.fetchedAt < BANK_CACHE_TTL_MS
if (hasWarmCache && bankCache) {
setQuestions(bankCache.questions)
setLoading(false)
return
}
setLoading(!(bankCache && bankCache.questions.length > 0))
try {
const rows = await loadQuestionBank()
setQuestions(rows)
} catch (error) {
console.error("Failed to load question bank:", error)
toast.error("Could not load question bank", {
description: getApiErrorMessage(error, "Try again in a moment."),
})
if (!bankCache?.questions.length) setQuestions([])
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
if (!open) return
setSearchQuery("")
setSelectedIds([])
void hydrateBank()
}, [open, hydrateBank])
/** Client-side index: load once from API, filter locally as the user types. */
const searchableRows = useMemo((): BankListRow[] => {
return questions
.filter((q) => !excluded.has(q.id))
.map((question) => ({
question,
labels: getQuestionBankListLabels(question, typeDefinitions),
haystack: buildQuestionBankSearchHaystack(question, typeDefinitions),
}))
}, [questions, excluded, typeDefinitions])
const filtered = useMemo(() => {
return searchableRows.filter((row) =>
matchesQuestionBankHaystack(row.haystack, searchQuery),
)
}, [searchableRows, searchQuery])
const toggleId = (id: number) => {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
)
}
const handleAttach = () => {
if (selectedIds.length === 0) return
setAttaching(true)
try {
const byId = new Map(questions.map((q) => [q.id, q]))
const details = selectedIds
.map((id) => byId.get(id))
.filter((q): q is QuestionDetail => q != null)
if (details.length === 0) {
throw new Error("Could not resolve the selected questions")
}
onAttach(details)
onOpenChange(false)
} catch (error) {
toast.error("Could not attach questions", {
description: getApiErrorMessage(error, "Try again."),
})
} finally {
setAttaching(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[85vh] max-w-2xl flex-col gap-0 overflow-hidden rounded-2xl border-grayScale-200 p-0 sm:max-w-2xl">
<DialogHeader className="border-b border-grayScale-100 px-5 py-4 pr-12 text-left sm:px-6">
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
<Library className="h-5 w-5 text-brand-500" />
Attach from question bank
</DialogTitle>
<DialogDescription className="text-sm text-grayScale-600">
Pick existing questions to include in this practice. Search filters this list on your
device — matching words are highlighted as you type.
</DialogDescription>
</DialogHeader>
<div className="space-y-3 px-5 py-4 sm:px-6">
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Type to filter by question text, type, or difficulty…"
className="h-10 rounded-xl border-grayScale-200 pl-9"
autoFocus
/>
</div>
<p className="text-xs text-grayScale-500">
{selectedIds.length > 0
? `${selectedIds.length} selected`
: loading
? "Loading…"
: searchQuery.trim()
? `${filtered.length} of ${searchableRows.length} match`
: `${filtered.length} available`}
</p>
</div>
<div className="min-h-0 flex-1 overflow-y-auto border-y border-grayScale-100 px-2 sm:px-3">
{loading ? (
<p className="px-3 py-8 text-center text-sm text-grayScale-500">
Loading question bank…
</p>
) : filtered.length === 0 ? (
<p className="px-3 py-8 text-center text-sm text-grayScale-500">
No matching questions in the bank.
</p>
) : (
<ul className="space-y-1 py-2">
{filtered.map(({ question: q, labels }) => {
const checked = selectedIds.includes(q.id)
return (
<li key={q.id}>
<label
className={cn(
"flex cursor-pointer items-start gap-3 rounded-xl border px-3 py-2.5 transition-colors",
checked
? "border-brand-200 bg-brand-100/50 ring-1 ring-brand-200"
: "border-transparent hover:bg-grayScale-50",
)}
>
<input
type="checkbox"
className="mt-1 h-4 w-4 shrink-0 rounded border-grayScale-300 accent-[#9E2891]"
checked={checked}
onChange={() => toggleId(q.id)}
/>
<span className="min-w-0 flex-1 space-y-1.5">
<span className="line-clamp-2 block text-sm font-medium text-grayScale-800">
<SearchHighlight
text={labels.preview}
query={searchQuery}
highlightClassName="rounded-sm bg-amber-200 px-0.5 text-grayScale-900"
/>
</span>
{labels.responsePreview ? (
<span className="line-clamp-1 block text-xs text-grayScale-600">
<SearchHighlight
text={labels.responsePreview}
query={searchQuery}
highlightClassName="rounded-sm bg-amber-200 px-0.5 text-grayScale-900"
/>
</span>
) : null}
<span className="flex flex-wrap items-center gap-2">
<span className="rounded-full bg-white px-2.5 py-0.5 text-[11px] font-semibold text-grayScale-700 ring-1 ring-grayScale-200">
<SearchHighlight
text={labels.typeLabel}
query={searchQuery}
highlightClassName="rounded-sm bg-amber-200 px-0.5 text-grayScale-900"
/>
</span>
{labels.difficultyLabel ? (
<span className="rounded-full bg-sky-100 px-2.5 py-0.5 text-[11px] font-semibold text-sky-800">
<SearchHighlight
text={labels.difficultyLabel}
query={searchQuery}
highlightClassName="rounded-sm bg-amber-200 px-0.5 text-grayScale-900"
/>
</span>
) : null}
{labels.statusLabel &&
labels.statusLabel.toLowerCase() !== "published" ? (
<span className="rounded-full bg-amber-50 px-2.5 py-0.5 text-[11px] font-semibold text-amber-800">
<SearchHighlight
text={labels.statusLabel}
query={searchQuery}
highlightClassName="rounded-sm bg-amber-200 px-0.5 text-grayScale-900"
/>
</span>
) : null}
</span>
</span>
</label>
</li>
)
})}
</ul>
)}
</div>
<DialogFooter className="flex-row justify-end gap-2 border-t border-grayScale-100 px-5 py-4 sm:px-6">
<Button
type="button"
variant="outline"
className="rounded-lg"
onClick={() => onOpenChange(false)}
disabled={attaching}
>
Cancel
</Button>
<Button
type="button"
className="rounded-lg bg-brand-500 text-white hover:bg-brand-600"
onClick={handleAttach}
disabled={attaching || selectedIds.length === 0}
>
{attaching
? "Attaching…"
: `Attach${selectedIds.length > 0 ? ` (${selectedIds.length})` : ""}`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@ -25,18 +25,22 @@ import {
ChevronDown,
ChevronsDownUp,
ChevronsUpDown,
Library,
} 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 type { QuestionTypeDefinition } from "../../../../types/questionTypeDefinition.types";
import type { QuestionDetail } from "../../../../types/course.types";
import { questionTypeDefinitionListLabel } from "../../../../api/questionTypeDefinitions.api";
import {
definitionUsesDynamicPayload,
emptyDynamicFieldValuesForDefinition,
legacyQuestionTypeFromDefinition,
questionRowHasContent,
} from "../../../../lib/learnEnglishDefinitionQuestion";
import { mapQuestionDetailToPracticeFormRow } from "../../../../lib/practiceFullMapper";
import { validateLearnEnglishQuestionsWithDefinitions } from "../../../../lib/learnEnglishPracticePublish";
import {
fixAssociationsAfterReorder,
@ -48,6 +52,7 @@ import {
import { cn } from "../../../../lib/utils";
import { toast } from "sonner";
import { QuestionAssociationField } from "./QuestionAssociationField";
import { QuestionBankAttachDialog } from "./QuestionBankAttachDialog";
import { StimulusBlocksPanel } from "./StimulusBlocksPanel";
import {
isIeltsSharedStimulusMode,
@ -210,6 +215,7 @@ export function QuestionsStep({
definitionsError,
}: QuestionsStepProps) {
const [activeDragId, setActiveDragId] = useState<string | null>(null);
const [bankDialogOpen, setBankDialogOpen] = useState(false);
const [expandedQuestionIds, setExpandedQuestionIds] = useState<Set<string>>(
() => new Set(formData.questions[0]?.id ? [formData.questions[0].id] : []),
);
@ -324,6 +330,83 @@ export function QuestionsStep({
setExpandedQuestionIds(new Set([id]));
};
const isBlankDraftRow = (row: {
serverQuestionId?: number | null;
text?: string;
questionTypeDefinitionId?: number | null;
dynamicFieldValues?: Record<string, string>;
}) => {
if (row.serverQuestionId != null && Number(row.serverQuestionId) > 0) return false;
const def = typeDefinitions.find((d) => d.id === row.questionTypeDefinitionId);
if (!def) {
return !String(row.text ?? "").trim();
}
return !questionRowHasContent(
{
questionText: String(row.text ?? "").trim(),
questionTypeDefinitionId: def.id,
dynamicFieldValues: { ...(row.dynamicFieldValues ?? {}) },
},
def,
);
};
const attachBankQuestions = (details: QuestionDetail[]) => {
if (details.length === 0) return;
const already = new Set(
formData.questions
.map((q: { serverQuestionId?: number | null }) => Number(q.serverQuestionId))
.filter((id: number) => Number.isFinite(id) && id > 0),
);
const fresh = details.filter((d) => d?.id && !already.has(d.id));
if (fresh.length === 0) {
toast.message("Those questions are already on this practice");
return;
}
const lastAnchor = findLastSectionAnchor(formData.questions);
let base = [...formData.questions];
if (base.length === 1 && isBlankDraftRow(base[0])) {
base = [];
}
const startOrder = base.length + 1;
const added = fresh.map((detail, index) => {
const mapped = mapQuestionDetailToPracticeFormRow(
detail,
typeDefinitions,
startOrder + index,
);
if (!lastAnchor || base.length === 0) return mapped;
const linked = setQuestionSectionAnchorRef(
{
id: mapped.id,
associatedQuestionId: mapped.associatedQuestionId,
associatedAnchorRowId: mapped.associatedAnchorRowId,
},
lastAnchor,
);
return {
...mapped,
associatedQuestionId: linked.associatedQuestionId ?? null,
associatedAnchorRowId: linked.associatedAnchorRowId ?? null,
};
});
const nextQuestions = syncQuestionDisplayOrders([...base, ...added]);
setFormData({ ...formData, questions: nextQuestions });
setExpandedQuestionIds(new Set(added.map((q) => q.id)));
toast.success(
fresh.length === 1
? "Attached 1 question from the bank"
: `Attached ${fresh.length} questions from the bank`,
);
};
const existingBankIds = formData.questions
.map((q: { serverQuestionId?: number | null }) => Number(q.serverQuestionId))
.filter((id: number) => Number.isFinite(id) && id > 0);
const renderTypeSpecificFields = (
q: any,
i: number,
@ -566,7 +649,7 @@ export function QuestionsStep({
<p className="text-grayScale-400 text-lg">
{ieltsMode
? "Create shared stimulus blocks, link questions to a block, then fill in each question's own stimulus and response fields."
: "Choose a question type for each item, then fill in the fields that type requires."}{" "}
: "Create new questions, or attach existing ones from the question bank. Choose a type for each new item, then fill in the fields that type requires."}{" "}
Group questions into sections so learners complete earlier blocks before later ones unlock.
Collapse cards to compare and drag them into order.
</p>
@ -691,6 +774,13 @@ export function QuestionsStep({
<span className="text-base font-bold text-grayScale-700">
Question {q.displayOrder ?? i + 1}
</span>
{q.serverQuestionId != null &&
Number(q.serverQuestionId) > 0 ? (
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-semibold text-emerald-800">
<Library className="h-3 w-3" />
Bank #{q.serverQuestionId}
</span>
) : null}
<span className="rounded-full bg-grayScale-100 px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-grayScale-600">
{q.difficultyLevel ?? "EASY"}
</span>
@ -969,6 +1059,16 @@ export function QuestionsStep({
</div>
Add question
</button>
<button
type="button"
onClick={() => setBankDialogOpen(true)}
className="flex items-center gap-3 text-base font-bold text-emerald-700 transition-all hover:opacity-80"
>
<div className="flex h-5 w-5 items-center justify-center rounded-full border-2 border-emerald-600">
<Library className="h-3 w-3 stroke-[2]" />
</div>
Attach from question bank
</button>
<button
type="button"
onClick={() => addQuestion(true)}
@ -982,6 +1082,14 @@ export function QuestionsStep({
</button>
</div>
<QuestionBankAttachDialog
open={bankDialogOpen}
onOpenChange={setBankDialogOpen}
excludeIds={existingBankIds}
onAttach={attachBankQuestions}
typeDefinitions={typeDefinitions}
/>
<div className="flex items-center justify-between pt-8">
<Button
type="button"
@ -996,6 +1104,7 @@ export function QuestionsStep({
onClick={() => {
const mapped = formData.questions.map((row: typeof formData.questions[0]) => ({
clientRowId: row.id,
serverQuestionId: row.serverQuestionId ?? null,
questionText: String(row.text ?? "").trim(),
questionTypeDefinitionId: Number(row.questionTypeDefinitionId),
dynamicFieldValues: { ...(row.dynamicFieldValues ?? {}) },

View File

@ -1441,6 +1441,8 @@ export interface QuestionShortAnswer {
export interface QuestionDetail {
id: number
question_text: string
/** Human-readable prompt for lists/search when question_text is omitted (DYNAMIC). */
preview_text?: string | null
question_type: "MCQ" | "TRUE_FALSE" | "SHORT_ANSWER" | "SHORT" | string
difficulty_level?: string | null
points?: number | null