diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index 4b1d5b3..85a1f9c 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -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(`/practices/${practiceId}/full`) + http.get(`/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(`/exam-prep/practices/${practiceId}/full`) + http.get(`/exam-prep/practices/${practiceId}/full`, { + skipErrorToast: true, + }) /** PUT /exam-prep/practices/:id/full */ export const updateExamPrepPracticeFull = ( diff --git a/src/lib/apiErrors.ts b/src/lib/apiErrors.ts index 7aa0dd3..f30ca8b 100644 --- a/src/lib/apiErrors.ts +++ b/src/lib/apiErrors.ts @@ -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 } diff --git a/src/lib/learnEnglishDefinitionQuestion.ts b/src/lib/learnEnglishDefinitionQuestion.ts index e988e63..04d370c 100644 --- a/src/lib/learnEnglishDefinitionQuestion.ts +++ b/src/lib/learnEnglishDefinitionQuestion.ts @@ -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 @@ -204,6 +206,12 @@ export interface LearnEnglishDefinitionQuestionInput { sampleAnswerVoiceUrl?: string } +export function isExistingBankQuestion( + q: Pick, +): boolean { + return q.serverQuestionId != null && Number(q.serverQuestionId) > 0 +} + export function questionRowHasContent( q: LearnEnglishDefinitionQuestionInput, def: QuestionTypeDefinition, diff --git a/src/lib/practiceCreationOrchestrator.ts b/src/lib/practiceCreationOrchestrator.ts index 3e3af55..14d46aa 100644 --- a/src/lib/practiceCreationOrchestrator.ts +++ b/src/lib/practiceCreationOrchestrator.ts @@ -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() + 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 = { diff --git a/src/lib/practiceFullMapper.ts b/src/lib/practiceFullMapper.ts index d11a340..0deacb4 100644 --- a/src/lib/practiceFullMapper.ts +++ b/src/lib/practiceFullMapper.ts @@ -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 } diff --git a/src/lib/practiceStimulusBlocks.ts b/src/lib/practiceStimulusBlocks.ts index d2acf51..2c684ce 100644 --- a/src/lib/practiceStimulusBlocks.ts +++ b/src/lib/practiceStimulusBlocks.ts @@ -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.` diff --git a/src/lib/questionBankDisplay.ts b/src/lib/questionBankDisplay.ts new file mode 100644 index 0000000..c26f099 --- /dev/null +++ b/src/lib/questionBankDisplay.ts @@ -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 = { + 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 = { + EASY: "Easy", + MEDIUM: "Medium", + HARD: "Hard", +} + +const STATUS_LABELS: Record = { + 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 { + return value != null && typeof value === "object" && !Array.isArray(value) +} + +function pickStr(record: Record, ...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() + 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())) +} diff --git a/src/pages/content-management/AddPracticeFlow.tsx b/src/pages/content-management/AddPracticeFlow.tsx index ae547cd..6da1c29 100644 --- a/src/pages/content-management/AddPracticeFlow.tsx +++ b/src/pages/content-management/AddPracticeFlow.tsx @@ -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 diff --git a/src/pages/content-management/EditPracticeFlow.tsx b/src/pages/content-management/EditPracticeFlow.tsx index 493d717..b601e98 100644 --- a/src/pages/content-management/EditPracticeFlow.tsx +++ b/src/pages/content-management/EditPracticeFlow.tsx @@ -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 = diff --git a/src/pages/content-management/components/practice-steps/QuestionBankAttachDialog.tsx b/src/pages/content-management/components/practice-steps/QuestionBankAttachDialog.tsx new file mode 100644 index 0000000..b377cf5 --- /dev/null +++ b/src/pages/content-management/components/practice-steps/QuestionBankAttachDialog.tsx @@ -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 | 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 + const direct = Number(record.total_count ?? record.TotalCount) + if (Number.isFinite(direct)) return direct + return undefined +} + +async function fetchAllBankQuestions(): Promise { + 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 { + 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( + () => bankCache?.questions ?? [], + ) + const [searchQuery, setSearchQuery] = useState("") + const [selectedIds, setSelectedIds] = useState([]) + + 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 ( + + + + + + Attach from question bank + + + Pick existing questions to include in this practice. Search filters this list on your + device — matching words are highlighted as you type. + + + +
+
+ + 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 + /> +
+

+ {selectedIds.length > 0 + ? `${selectedIds.length} selected` + : loading + ? "Loading…" + : searchQuery.trim() + ? `${filtered.length} of ${searchableRows.length} match` + : `${filtered.length} available`} +

+
+ +
+ {loading ? ( +

+ Loading question bank… +

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

+ No matching questions in the bank. +

+ ) : ( +
    + {filtered.map(({ question: q, labels }) => { + const checked = selectedIds.includes(q.id) + return ( +
  • + +
  • + ) + })} +
+ )} +
+ + + + + +
+
+ ) +} diff --git a/src/pages/content-management/components/practice-steps/QuestionsStep.tsx b/src/pages/content-management/components/practice-steps/QuestionsStep.tsx index b50561b..69d5b8c 100644 --- a/src/pages/content-management/components/practice-steps/QuestionsStep.tsx +++ b/src/pages/content-management/components/practice-steps/QuestionsStep.tsx @@ -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(null); + const [bankDialogOpen, setBankDialogOpen] = useState(false); const [expandedQuestionIds, setExpandedQuestionIds] = useState>( () => 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; + }) => { + 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({

{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.

@@ -691,6 +774,13 @@ export function QuestionsStep({ Question {q.displayOrder ?? i + 1} + {q.serverQuestionId != null && + Number(q.serverQuestionId) > 0 ? ( + + + Bank #{q.serverQuestionId} + + ) : null} {q.difficultyLevel ?? "EASY"} @@ -969,6 +1059,16 @@ export function QuestionsStep({ Add question + + +