diff --git a/src/api/ratings.api.ts b/src/api/ratings.api.ts index 0fe99b2..1745e64 100644 --- a/src/api/ratings.api.ts +++ b/src/api/ratings.api.ts @@ -1,4 +1,5 @@ import http from "./http" +import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages" import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination" import type { AppReviewsPageData, @@ -121,6 +122,30 @@ export async function loadRatingsPage( return { summary, reviews } } +/** Fetch every review for a target (for client-side search across pagination). */ +export async function fetchAllRatingsByTarget( + targetType: RatingTargetType, + targetId?: number, +): Promise<{ summary: RatingSummary; reviews: Rating[] }> { + const normalizedTargetId = normalizeTargetId(targetType, targetId) + const summary = await getRatingSummary({ + target_type: targetType, + target_id: normalizedTargetId, + }) + + const reviews = await fetchAllOffsetPages(async (offset, limit) => ({ + items: await listRatingsByTarget({ + target_type: targetType, + target_id: normalizedTargetId, + limit, + offset, + }), + total_count: summary.total_count, + })) + + return { summary, reviews } +} + /** @deprecated Use listRatingsByTarget — kept for legacy callers. */ export function getRatings(params: { target_type: string diff --git a/src/components/content-management/PracticeQuestionEditorFields.tsx b/src/components/content-management/PracticeQuestionEditorFields.tsx index 8676330..af67909 100644 --- a/src/components/content-management/PracticeQuestionEditorFields.tsx +++ b/src/components/content-management/PracticeQuestionEditorFields.tsx @@ -21,6 +21,7 @@ import { Select } from "../ui/select" import { Button } from "../ui/button" import { SpinnerIcon } from "../ui/spinner-icon" import { cn } from "../../lib/utils" +import { isNoInputComponentKind } from "../../lib/questionComponentKinds" import { ResolvedAudio } from "../media/ResolvedAudio" import { ResolvedImage } from "../media/ResolvedImage" import { DynamicSchemaSlotField } from "./DynamicSchemaSlotField" @@ -670,13 +671,17 @@ export function PracticeQuestionEditorFields({ return } const fieldValues: Record = { ...value.dynamicFieldValues } - const dynamicStimulusRows: PracticeQuestionDynamicRow[] = def.stimulus_schema.map((r) => ({ + const dynamicStimulusRows: PracticeQuestionDynamicRow[] = def.stimulus_schema + .filter((r) => !isNoInputComponentKind(r.kind)) + .map((r) => ({ id: r.id, kind: r.kind, label: r.label, required: r.required, })) - const dynamicResponseRows: PracticeQuestionDynamicRow[] = def.response_schema.map((r) => ({ + const dynamicResponseRows: PracticeQuestionDynamicRow[] = def.response_schema + .filter((r) => !isNoInputComponentKind(r.kind)) + .map((r) => ({ id: r.id, kind: r.kind, label: r.label, diff --git a/src/lib/fetchAllOffsetPages.ts b/src/lib/fetchAllOffsetPages.ts new file mode 100644 index 0000000..ff04944 --- /dev/null +++ b/src/lib/fetchAllOffsetPages.ts @@ -0,0 +1,36 @@ +export type OffsetPageResult = { + items: T[] + total_count?: number +} + +const DEFAULT_BATCH_SIZE = 100 + +/** + * Fetches every page from an offset/limit API so client-side search can run across the full dataset. + */ +export async function fetchAllOffsetPages( + fetchPage: (offset: number, limit: number) => Promise>, + batchSize = DEFAULT_BATCH_SIZE, +): Promise { + const all: T[] = [] + let offset = 0 + let totalCount = Number.POSITIVE_INFINITY + + while (offset < totalCount) { + const { items, total_count } = await fetchPage(offset, batchSize) + all.push(...items) + + if (typeof total_count === "number" && Number.isFinite(total_count)) { + totalCount = total_count + } else if (items.length === 0) { + break + } else if (items.length < batchSize) { + break + } + + if (items.length === 0) break + offset += items.length + } + + return all +} diff --git a/src/lib/learnEnglishDefinitionQuestion.ts b/src/lib/learnEnglishDefinitionQuestion.ts index 919766b..790739a 100644 --- a/src/lib/learnEnglishDefinitionQuestion.ts +++ b/src/lib/learnEnglishDefinitionQuestion.ts @@ -33,6 +33,7 @@ import { validateSelectMissingWordsResponseSlotValue, validateSelectMissingWordsStimulusSlotValue, } from "./selectMissingWordsSlotValue" +import { isNoInputComponentKind } from "./questionComponentKinds" function isMultipleChoiceKind(kind: string): boolean { const u = kind.trim().toUpperCase() @@ -64,6 +65,7 @@ function defaultValueForSchemaSlot( kind: string, side: "stimulus" | "response", ): string { + if (isNoInputComponentKind(kind)) return "" const u = kind.trim().toUpperCase() if (u === "TABLE") { return serializeTableSlotValue(createEmptyTable(2, 1)) @@ -89,7 +91,9 @@ function defaultValueForSchemaSlot( } export function definitionUsesDynamicPayload(def: QuestionTypeDefinition): boolean { - return def.stimulus_schema.length > 0 || def.response_schema.length > 0 + const stimulus = def.stimulus_schema.filter((r) => !isNoInputComponentKind(r.kind)) + const response = def.response_schema.filter((r) => !isNoInputComponentKind(r.kind)) + return stimulus.length > 0 || response.length > 0 } export function emptyDynamicFieldValuesForDefinition( @@ -97,9 +101,11 @@ export function emptyDynamicFieldValuesForDefinition( ): Record { const o: Record = {} for (const r of def.stimulus_schema) { + if (isNoInputComponentKind(r.kind)) continue o[`stimulus:${r.id}`] = defaultValueForSchemaSlot(r.kind, "stimulus") } for (const r of def.response_schema) { + if (isNoInputComponentKind(r.kind)) continue o[`response:${r.id}`] = defaultValueForSchemaSlot(r.kind, "response") } return o @@ -190,6 +196,7 @@ export function questionRowHasContent( if (q.questionText.trim()) return true const fv = q.dynamicFieldValues ?? {} for (const row of def.stimulus_schema) { + if (isNoInputComponentKind(row.kind)) continue if (isMultipleChoiceKind(row.kind)) { if ( multipleChoiceSlotHasContent( @@ -233,6 +240,7 @@ export function questionRowHasContent( if (fv[`stimulus:${row.id}`]?.trim()) return true } for (const row of def.response_schema) { + if (isNoInputComponentKind(row.kind)) continue if (isMultipleChoiceKind(row.kind)) { if ( multipleChoiceSlotHasContent( @@ -404,6 +412,7 @@ export function validateDefinitionQuestion( return `Question ${n}: enter prompt text (${promptRow.label || promptRow.id}).` } for (const row of def.stimulus_schema) { + if (isNoInputComponentKind(row.kind)) continue if (isStructuredDynamicSlotKind(row.kind)) continue if (!row.required) continue const v = fieldValues[`stimulus:${row.id}`]?.trim() @@ -411,6 +420,7 @@ export function validateDefinitionQuestion( return `Question ${n}: fill required stimulus "${row.label || row.id}" (${row.kind}).` } for (const row of def.response_schema) { + if (isNoInputComponentKind(row.kind)) continue if (isStructuredDynamicSlotKind(row.kind)) continue if (!row.required) continue const v = fieldValues[`response:${row.id}`]?.trim() @@ -427,6 +437,7 @@ export function validateDefinitionQuestion( def.stimulus_schema, ) for (const row of def.stimulus_schema) { + if (isNoInputComponentKind(row.kind)) continue if (isMultipleChoiceKind(row.kind)) { const val = parseMultipleChoiceSlotValue(fieldValues[`stimulus:${row.id}`]) if (!multipleChoiceSlotHasContent(val)) { @@ -486,6 +497,7 @@ export function validateDefinitionQuestion( } } for (const row of def.response_schema) { + if (isNoInputComponentKind(row.kind)) continue if (isMultipleChoiceKind(row.kind)) { const val = parseMultipleChoiceSlotValue(fieldValues[`response:${row.id}`]) if (!multipleChoiceSlotHasContent(val)) { diff --git a/src/lib/practiceDynamicQuestionPayload.ts b/src/lib/practiceDynamicQuestionPayload.ts index 7d0ae69..981dc54 100644 --- a/src/lib/practiceDynamicQuestionPayload.ts +++ b/src/lib/practiceDynamicQuestionPayload.ts @@ -23,6 +23,7 @@ import { normalizeMultipleChoiceValue, parseMultipleChoiceSlotValue, } from "./multipleChoiceSlotValue" +import { isNoInputComponentKind } from "./questionComponentKinds" /** Parse a single slot value: plain string/URL, or JSON object/array when input looks like JSON. */ export function parseDynamicSlotValue(raw: string | undefined): unknown { @@ -154,7 +155,9 @@ export function buildDynamicQuestionPayload(input: { const mcqOptionsConsumed = { current: false } return { - stimulus: input.stimulusRows.map((row) => ({ + stimulus: input.stimulusRows + .filter((row) => !isNoInputComponentKind(row.kind)) + .map((row) => ({ id: row.id, kind: row.kind, value: slotValueForRow( @@ -167,7 +170,9 @@ export function buildDynamicQuestionPayload(input: { input.responseRows, ), })), - response: input.responseRows.map((row) => ({ + response: input.responseRows + .filter((row) => !isNoInputComponentKind(row.kind)) + .map((row) => ({ id: row.id, kind: row.kind, value: slotValueForRow( diff --git a/src/lib/questionComponentKinds.ts b/src/lib/questionComponentKinds.ts new file mode 100644 index 0000000..1b911f0 --- /dev/null +++ b/src/lib/questionComponentKinds.ts @@ -0,0 +1,33 @@ +/** Placeholder component — authors do not configure content for this side. */ +export const NO_INPUT_COMPONENT_KIND = "NO_INPUT" + +export function isNoInputComponentKind(kind: string): boolean { + return kind.trim().toUpperCase() === NO_INPUT_COMPONENT_KIND +} + +export function effectiveComponentKinds(kinds: string[]): string[] { + return kinds.filter((kind) => !isNoInputComponentKind(kind)) +} + +export function sideIsNoInputOnly(kinds: string[]): boolean { + return kinds.length > 0 && kinds.every(isNoInputComponentKind) +} + +export function mergeCatalogWithNoInput(kinds: string[]): string[] { + if (kinds.some(isNoInputComponentKind)) return kinds + return [...kinds, NO_INPUT_COMPONENT_KIND] +} + +export function noInputSchemaRow(id = "no_input_1"): { + id: string + kind: string + label: string + required: boolean +} { + return { + id, + kind: NO_INPUT_COMPONENT_KIND, + label: "No input", + required: false, + } +} diff --git a/src/lib/schemaSlotLabel.ts b/src/lib/schemaSlotLabel.ts index bb7948d..54a06a0 100644 --- a/src/lib/schemaSlotLabel.ts +++ b/src/lib/schemaSlotLabel.ts @@ -20,6 +20,7 @@ const KIND_DEFAULT_LABELS: Record = { MATCHING_ANSWER: "Matching answer", LABEL_SELECTION: "Label selection", SEQUENCE_ORDER: "Sequence order", + NO_INPUT: "No input", } export function humanizeKind(kind: string): string { diff --git a/src/pages/content-management/CreateQuestionTypeFlow.tsx b/src/pages/content-management/CreateQuestionTypeFlow.tsx index d69443d..dc76db8 100644 --- a/src/pages/content-management/CreateQuestionTypeFlow.tsx +++ b/src/pages/content-management/CreateQuestionTypeFlow.tsx @@ -26,11 +26,17 @@ import { validateDefinitionSchemas, type FieldErrorMap, } from "./lib/questionTypeDefinitionValidation" +import { defaultLabelForKind } from "../../lib/schemaSlotLabel" import { QuestionTypeBasicInfoStep } from "./components/question-type-steps/QuestionTypeBasicInfoStep" import { QuestionTypeConfigStep } from "./components/question-type-steps/QuestionTypeConfigStep" import { QuestionTypeValidatePreviewStep } from "./components/question-type-steps/QuestionTypeValidatePreviewStep" import { QuestionTypeReviewPublishStep } from "./components/question-type-steps/QuestionTypeReviewPublishStep" -import { defaultLabelForKind } from "../../lib/schemaSlotLabel" +import { + isNoInputComponentKind, + mergeCatalogWithNoInput, + noInputSchemaRow, + sideIsNoInputOnly, +} from "../../lib/questionComponentKinds" const initialDraft = (): QuestionTypeDefinitionCreatePayload => ({ key: "", @@ -170,10 +176,19 @@ export function CreateQuestionTypeFlow() { }, [isEdit]) const catalogForSchemaValidation = { - stimulus: new Set(componentCatalog.stimulus_component_kinds), - response: new Set(componentCatalog.response_component_kinds), + stimulus: new Set(mergeCatalogWithNoInput(componentCatalog.stimulus_component_kinds)), + response: new Set(mergeCatalogWithNoInput(componentCatalog.response_component_kinds)), } + const stimulusCatalogKinds = useMemo( + () => mergeCatalogWithNoInput(componentCatalog.stimulus_component_kinds), + [componentCatalog.stimulus_component_kinds], + ) + const responseCatalogKinds = useMemo( + () => mergeCatalogWithNoInput(componentCatalog.response_component_kinds), + [componentCatalog.response_component_kinds], + ) + const handleNextFromStep1 = () => { const e1 = validateDefinitionBasic(draft) setStepErrors(e1) @@ -194,10 +209,26 @@ export function CreateQuestionTypeFlow() { } const nextDraft: QuestionTypeDefinitionCreatePayload = { ...draft } - if (!nextDraft.stimulus_schema.length && nextDraft.stimulus_component_kinds.length) { + if ( + !nextDraft.stimulus_schema.length && + sideIsNoInputOnly(nextDraft.stimulus_component_kinds) + ) { + nextDraft.stimulus_schema = [noInputSchemaRow()] + } else if ( + !nextDraft.stimulus_schema.length && + nextDraft.stimulus_component_kinds.length + ) { nextDraft.stimulus_schema = seedSchemaFromKinds(nextDraft.stimulus_component_kinds) } - if (!nextDraft.response_schema.length && nextDraft.response_component_kinds.length) { + if ( + !nextDraft.response_schema.length && + sideIsNoInputOnly(nextDraft.response_component_kinds) + ) { + nextDraft.response_schema = [noInputSchemaRow()] + } else if ( + !nextDraft.response_schema.length && + nextDraft.response_component_kinds.length + ) { nextDraft.response_schema = seedSchemaFromKinds(nextDraft.response_component_kinds) } setDraft(nextDraft) @@ -334,8 +365,8 @@ export function CreateQuestionTypeFlow() { ([]) - const [totalCount, setTotalCount] = useState(undefined) const [query, setQuery] = useState("") const [statusFilter, setStatusFilter] = useState("All") const [scopeFilter, setScopeFilter] = useState("all") @@ -83,38 +80,30 @@ export function QuestionTypeLibraryPage() { const load = useCallback(async () => { setLoading(true) try { - const isSystemScope = scopeFilter === "system" - const { definitions: rows, total_count } = await getQuestionTypeDefinitions({ + const { definitions: rows } = await getQuestionTypeDefinitions({ include_system: scopeFilter !== "custom", ...(statusFilter !== "All" ? { status: statusFilter } : {}), - limit: isSystemScope ? SYSTEM_SCOPE_FETCH_LIMIT : pageSize, - offset: isSystemScope ? 0 : offset, }) - const visibleRows = isSystemScope ? rows.filter((d) => d.is_system) : rows + const visibleRows = + scopeFilter === "system" ? rows.filter((d) => d.is_system) : rows setDefinitions(visibleRows) - if (isSystemScope) { - setTotalCount(visibleRows.length) - } else if (total_count != null) { - setTotalCount(total_count) - } else if (rows.length < pageSize) { - setTotalCount(offset + rows.length) - } else { - setTotalCount(undefined) - } } catch (e) { console.error(e) toast.error("Failed to load question type definitions") setDefinitions([]) - setTotalCount(0) } finally { setLoading(false) } - }, [offset, pageSize, scopeFilter, statusFilter]) + }, [scopeFilter, statusFilter]) useEffect(() => { void load() }, [load]) + useEffect(() => { + setOffset(0) + }, [query, pageSize, scopeFilter, statusFilter]) + useEffect(() => { if (createdId) { toast.success("Definition created", { description: `Id ${createdId}` }) @@ -127,6 +116,8 @@ export function QuestionTypeLibraryPage() { } }, [updatedId]) + const isSystemScope = scopeFilter === "system" + const filtered = useMemo(() => { const q = query.trim().toLowerCase() if (!q) return definitions @@ -137,19 +128,17 @@ export function QuestionTypeLibraryPage() { }) }, [definitions, query]) - const isSystemScope = scopeFilter === "system" + const paginated = useMemo(() => { + if (isSystemScope) return filtered + return filtered.slice(offset, offset + pageSize) + }, [filtered, isSystemScope, offset, pageSize]) + + const totalCount = filtered.length const canPrev = !isSystemScope && offset > 0 - const canNext = - !isSystemScope && - (totalCount != null ? offset + pageSize < totalCount : definitions.length === pageSize) + const canNext = !isSystemScope && offset + pageSize < totalCount const pageStart = totalCount === 0 ? 0 : isSystemScope ? 1 : offset + 1 - const pageEnd = - isSystemScope - ? filtered.length - : totalCount != null - ? Math.min(offset + definitions.length, totalCount) - : offset + definitions.length + const pageEnd = isSystemScope ? filtered.length : Math.min(offset + paginated.length, totalCount) const resetPagination = () => setOffset(0) @@ -255,7 +244,7 @@ export function QuestionTypeLibraryPage() { setQuery(e.target.value)} /> @@ -353,7 +342,7 @@ export function QuestionTypeLibraryPage() { ) : (
- {filtered.map((d) => ( + {paginated.map((d) => (
- {totalCount != null - ? `Showing ${pageStart}–${pageEnd} of ${totalCount}` - : `Showing ${pageStart}–${pageEnd}`} + {totalCount === 0 + ? "No results" + : `Showing ${pageStart}–${pageEnd} of ${totalCount}`} {query.trim() && filtered.length !== definitions.length ? ( - {filtered.length} match{filtered.length === 1 ? "" : "es"} on this page + {filtered.length} match{filtered.length === 1 ? "" : "es"} total ) : null} {!isSystemScope ? ( diff --git a/src/pages/content-management/SpeakingPage.tsx b/src/pages/content-management/SpeakingPage.tsx index bda1b67..55e920a 100644 --- a/src/pages/content-management/SpeakingPage.tsx +++ b/src/pages/content-management/SpeakingPage.tsx @@ -32,6 +32,7 @@ import { import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types" import { toast } from "sonner" import { countActiveFilters } from "../../lib/adminFilterUtils" +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024 @@ -250,31 +251,38 @@ export function SpeakingPage() { let total = 0 if (selectedPracticeId) { - const offset = (safePage - 1) * audioPageSize - const practiceRes = await getPracticeQuestionsByPractice(Number(selectedPracticeId), { - limit: audioPageSize, - offset, - question_type: "AUDIO", - }) - const practiceData = practiceRes.data?.data const selectedPractice = practiceOptions.find((p) => p.id === Number(selectedPracticeId)) - rows = (practiceData?.questions ?? []).map((q) => ({ - id: q.question_id || q.id, - question_text: q.question_text, - question_type: q.question_type, - difficulty_level: q.difficulty_level ?? undefined, - points: q.points ?? 0, - explanation: q.explanation ?? undefined, - tips: q.tips ?? undefined, - voice_prompt: q.voice_prompt ?? undefined, - sample_answer_voice_prompt: q.sample_answer_voice_prompt ?? undefined, - image_url: q.image_url ?? undefined, - status: q.question_status ?? "DRAFT", - created_at: "", - audio_correct_answer_text: q.audio_correct_answer_text ?? undefined, - practice_id: Number(selectedPracticeId), - practice_title: selectedPractice?.title ?? `Practice #${selectedPracticeId}`, - })) + const practiceId = Number(selectedPracticeId) + const allRows = await fetchAllOffsetPages(async (batchOffset, limit) => { + const practiceRes = await getPracticeQuestionsByPractice(practiceId, { + limit, + offset: batchOffset, + question_type: "AUDIO", + }) + const practiceData = practiceRes.data?.data + const questions = practiceData?.questions ?? [] + return { + items: questions.map((q) => ({ + id: q.question_id || q.id, + question_text: q.question_text, + question_type: q.question_type, + difficulty_level: q.difficulty_level ?? undefined, + points: q.points ?? 0, + explanation: q.explanation ?? undefined, + tips: q.tips ?? undefined, + voice_prompt: q.voice_prompt ?? undefined, + sample_answer_voice_prompt: q.sample_answer_voice_prompt ?? undefined, + image_url: q.image_url ?? undefined, + status: q.question_status ?? "DRAFT", + created_at: "", + audio_correct_answer_text: q.audio_correct_answer_text ?? undefined, + practice_id: practiceId, + practice_title: selectedPractice?.title ?? `Practice #${selectedPracticeId}`, + })), + total_count: practiceData?.total_count, + } + }) + rows = allRows const q = searchQuery.trim().toLowerCase() if (q) { rows = rows.filter((question) => { @@ -283,17 +291,25 @@ export function SpeakingPage() { return haystack.includes(q) }) } - total = searchQuery.trim() ? rows.length : (practiceData?.total_count ?? rows.length) + total = rows.length + const offset = (safePage - 1) * audioPageSize + rows = rows.slice(offset, offset + audioPageSize) } else { const groupedRows = await Promise.all( practiceOptions.map(async (practice) => { try { - const res = await getPracticeQuestionsByPractice(practice.id, { - limit: 100, - offset: 0, - question_type: "AUDIO", + const questions = await fetchAllOffsetPages(async (batchOffset, limit) => { + const res = await getPracticeQuestionsByPractice(practice.id, { + limit, + offset: batchOffset, + question_type: "AUDIO", + }) + const data = res.data?.data + return { + items: data?.questions ?? [], + total_count: data?.total_count, + } }) - const questions = res.data?.data?.questions ?? [] return questions.map((q) => ({ id: q.question_id || q.id, question_text: q.question_text, diff --git a/src/pages/content-management/components/question-type-steps/DefinitionRuntimeHint.tsx b/src/pages/content-management/components/question-type-steps/DefinitionRuntimeHint.tsx index 94d59b7..d667c9c 100644 --- a/src/pages/content-management/components/question-type-steps/DefinitionRuntimeHint.tsx +++ b/src/pages/content-management/components/question-type-steps/DefinitionRuntimeHint.tsx @@ -17,8 +17,9 @@ export function DefinitionRuntimeHint({

May not be publishable

- The server requires a mappable runtime question type. Add at least one non-timer response - kind (e.g. OPTION, TEXT_INPUT). Timer-only definitions are rejected. + The server requires a mappable runtime question type. Add at least one non-timer + response kind (e.g. OPTION, TEXT_INPUT), or use No input only when the definition is + intentionally display-only.

diff --git a/src/pages/content-management/components/question-type-steps/QuestionTypeConfigStep.tsx b/src/pages/content-management/components/question-type-steps/QuestionTypeConfigStep.tsx index e3aac4e..559f480 100644 --- a/src/pages/content-management/components/question-type-steps/QuestionTypeConfigStep.tsx +++ b/src/pages/content-management/components/question-type-steps/QuestionTypeConfigStep.tsx @@ -16,6 +16,10 @@ import { getResponseKindPresentation, getStimulusKindPresentation, } from "./componentKindUi" +import { + isNoInputComponentKind, + noInputSchemaRow, +} from "../../../../lib/questionComponentKinds" interface QuestionTypeConfigStepProps { draft: QuestionTypeDefinitionCreatePayload @@ -29,10 +33,6 @@ interface QuestionTypeConfigStepProps { onBack: () => void } -function toggleKind(list: string[], kind: string): string[] { - return list.includes(kind) ? list.filter((k) => k !== kind) : [...list, kind] -} - function slugFragmentFromKind(kind: string): string { const s = (kind || "field").toLowerCase().replace(/[^a-z0-9]+/g, "_") return s.replace(/^_|_$/g, "") || "field" @@ -93,10 +93,26 @@ export function QuestionTypeConfigStep({ const handleStimulusKindClick = (kind: string) => { setDraft((d) => { + if (isNoInputComponentKind(kind)) { + const wasSelected = d.stimulus_component_kinds.includes(kind) + if (wasSelected) { + return { ...d, stimulus_component_kinds: [], stimulus_schema: [] } + } + return { + ...d, + stimulus_component_kinds: [kind], + stimulus_schema: [noInputSchemaRow()], + } + } + const wasSelected = d.stimulus_component_kinds.includes(kind) - const stimulus_component_kinds = toggleKind(d.stimulus_component_kinds, kind) + const baseKinds = d.stimulus_component_kinds.filter((k) => !isNoInputComponentKind(k)) + const stimulus_component_kinds = wasSelected + ? baseKinds.filter((k) => k !== kind) + : [...baseKinds, kind] + if (!wasSelected) { - const stimulus_schema = [...d.stimulus_schema] + const stimulus_schema = d.stimulus_schema.filter((r) => !isNoInputComponentKind(r.kind)) if (!stimulus_schema.some((r) => r.kind === kind)) { stimulus_schema.push({ id: nextUniqueSchemaElementId(stimulus_schema, kind), @@ -117,10 +133,26 @@ export function QuestionTypeConfigStep({ const handleResponseKindClick = (kind: string) => { setDraft((d) => { + if (isNoInputComponentKind(kind)) { + const wasSelected = d.response_component_kinds.includes(kind) + if (wasSelected) { + return { ...d, response_component_kinds: [], response_schema: [] } + } + return { + ...d, + response_component_kinds: [kind], + response_schema: [noInputSchemaRow()], + } + } + const wasSelected = d.response_component_kinds.includes(kind) - const response_component_kinds = toggleKind(d.response_component_kinds, kind) + const baseKinds = d.response_component_kinds.filter((k) => !isNoInputComponentKind(k)) + const response_component_kinds = wasSelected + ? baseKinds.filter((k) => k !== kind) + : [...baseKinds, kind] + if (!wasSelected) { - const response_schema = [...d.response_schema] + const response_schema = d.response_schema.filter((r) => !isNoInputComponentKind(r.kind)) if (!response_schema.some((r) => r.kind === kind)) { response_schema.push({ id: nextUniqueSchemaElementId(response_schema, kind), @@ -246,7 +278,7 @@ export function QuestionTypeConfigStep({ selected={selected} onClick={() => handleStimulusKindClick(kind)} /> - {selected ? ( + {selected && !isNoInputComponentKind(kind) ? (
{slotCount} slot{slotCount === 1 ? "" : "s"} @@ -310,7 +342,7 @@ export function QuestionTypeConfigStep({ selected={selected} onClick={() => handleResponseKindClick(kind)} /> - {selected ? ( + {selected && !isNoInputComponentKind(kind) ? (
{slotCount} slot{slotCount === 1 ? "" : "s"} diff --git a/src/pages/content-management/components/question-type-steps/QuestionTypeReviewPublishStep.tsx b/src/pages/content-management/components/question-type-steps/QuestionTypeReviewPublishStep.tsx index cc2f696..93e43db 100644 --- a/src/pages/content-management/components/question-type-steps/QuestionTypeReviewPublishStep.tsx +++ b/src/pages/content-management/components/question-type-steps/QuestionTypeReviewPublishStep.tsx @@ -16,7 +16,6 @@ import { buildValidateKindsPayload, inferRuntimeQuestionType, } from "../../lib/questionTypeDefinitionValidation" -import { DefinitionRuntimeHint } from "./DefinitionRuntimeHint" import { slotLabel } from "./componentKindUi" interface QuestionTypeReviewPublishStepProps { @@ -41,13 +40,6 @@ export function QuestionTypeReviewPublishStep({ const runtime = inferRuntimeQuestionType(payload.key, payload.response_component_kinds) const submit = async (status: "ACTIVE" | "INACTIVE") => { - if (runtime == null) { - toast.error("Definition cannot be saved", { - description: "Add at least one non-timer response kind so the server can map a runtime question type.", - }) - return - } - const body = { ...payload, status } setSubmitting(true) try { @@ -112,11 +104,6 @@ export function QuestionTypeReviewPublishStep({

) : null} - -
Key
@@ -136,7 +123,7 @@ export function QuestionTypeReviewPublishStep({
Runtime type
-
{runtime ?? "Unmappable"}
+
{runtime ?? "—"}
Stimulus kinds
@@ -158,7 +145,7 @@ export function QuestionTypeReviewPublishStep({ type="button" variant="outline" className="h-11" - disabled={submitting || runtime == null} + disabled={submitting} onClick={() => void submit("INACTIVE")} > {submitting ? ( @@ -172,7 +159,7 @@ export function QuestionTypeReviewPublishStep({ @@ -170,6 +174,13 @@ export function SchemaBuilderSection({
+ {noInput ? ( +

+ No author input is collected for this side. Deselect No input in the component picker to use + other kinds. +

+ ) : ( + <>
+ + )} {rowErrors?.[index] ?

{rowErrors[index]}

: null}
- ))} + )})}
) diff --git a/src/pages/content-management/components/question-type-steps/SchemaSlotLabelsPanel.tsx b/src/pages/content-management/components/question-type-steps/SchemaSlotLabelsPanel.tsx index a576bf7..21fd51f 100644 --- a/src/pages/content-management/components/question-type-steps/SchemaSlotLabelsPanel.tsx +++ b/src/pages/content-management/components/question-type-steps/SchemaSlotLabelsPanel.tsx @@ -7,6 +7,7 @@ import { getResponseKindPresentation, getStimulusKindPresentation, } from "./componentKindUi" +import { isNoInputComponentKind } from "../../../../lib/questionComponentKinds" interface SchemaSlotLabelsPanelProps { stimulusRows: DynamicElementDefinition[] @@ -71,23 +72,32 @@ function SlotLabelGroup({ className="h-8 w-8 shrink-0 p-0 text-grayScale-500 hover:text-red-600" onClick={() => onChange(removeRow(rows, index))} aria-label={`Remove ${presentation.label} slot`} + disabled={isNoInputComponentKind(row.kind)} >
- - onChange(updateRowLabel(rows, index, e.target.value))} - placeholder={defaultLabelForKind(row.kind)} - className="h-10 bg-white" - /> -

- Shown to authors when they create questions from this type. -

+ {isNoInputComponentKind(row.kind) ? ( +

+ No author input is collected for this side. +

+ ) : ( + <> + + onChange(updateRowLabel(rows, index, e.target.value))} + placeholder={defaultLabelForKind(row.kind)} + className="h-10 bg-white" + /> +

+ Shown to authors when they create questions from this type. +

+ + )}
{rowError ?

{rowError}

: null} diff --git a/src/pages/content-management/components/question-type-steps/componentKindUi.ts b/src/pages/content-management/components/question-type-steps/componentKindUi.ts index 213e0a7..d0ab83b 100644 --- a/src/pages/content-management/components/question-type-steps/componentKindUi.ts +++ b/src/pages/content-management/components/question-type-steps/componentKindUi.ts @@ -14,6 +14,7 @@ import { ListOrdered, ListTodo, Mic2, + Minus, MousePointer2, Table as TableIcon, Type, @@ -35,6 +36,7 @@ const STIMULUS_LABELS: Record = { SELECT_MISSING_WORDS: defaultLabelForKind("SELECT_MISSING_WORDS"), TABLE: defaultLabelForKind("TABLE"), PDF_ATTACHMENT: defaultLabelForKind("PDF_ATTACHMENT"), + NO_INPUT: defaultLabelForKind("NO_INPUT"), } const RESPONSE_LABELS: Record = { @@ -49,6 +51,7 @@ const RESPONSE_LABELS: Record = { MATCHING_ANSWER: defaultLabelForKind("MATCHING_ANSWER"), LABEL_SELECTION: defaultLabelForKind("LABEL_SELECTION"), SEQUENCE_ORDER: defaultLabelForKind("SEQUENCE_ORDER"), + NO_INPUT: defaultLabelForKind("NO_INPUT"), } /** Legacy screenshot labels → map to closest API kind for display only (same code path). */ @@ -64,6 +67,7 @@ const STIMULUS_ICONS: Record = { SELECT_MISSING_WORDS: ListTodo, TABLE: TableIcon, PDF_ATTACHMENT: FileUp, + NO_INPUT: Minus, } const RESPONSE_ICONS: Record = { @@ -78,6 +82,7 @@ const RESPONSE_ICONS: Record = { MATCHING_ANSWER: GitCompare, LABEL_SELECTION: MousePointer2, SEQUENCE_ORDER: ListOrdered, + NO_INPUT: Minus, } const DEFAULT_ICON = FileText diff --git a/src/pages/content-management/lib/questionTypeDefinitionValidation.ts b/src/pages/content-management/lib/questionTypeDefinitionValidation.ts index 8680f4f..f3a9ea4 100644 --- a/src/pages/content-management/lib/questionTypeDefinitionValidation.ts +++ b/src/pages/content-management/lib/questionTypeDefinitionValidation.ts @@ -4,6 +4,12 @@ import type { QuestionTypeDefinitionCreatePayload, } from "../../../types/questionTypeDefinition.types" import { defaultLabelForKind } from "../../../lib/schemaSlotLabel" +import { + effectiveComponentKinds, + isNoInputComponentKind, + sideIsNoInputOnly, + noInputSchemaRow, +} from "../../../lib/questionComponentKinds" export type FieldErrorMap = Record @@ -32,13 +38,24 @@ export function validateDefinitionKinds( const errors: FieldErrorMap = {} const { stimulus_component_kinds: sk, response_component_kinds: rk } = payload - if (!sk.length) errors.stimulus_kinds = "Select at least one stimulus component kind." - if (!rk.length) errors.response_kinds = "Select at least one response component kind." + if (sk.length === 0 && rk.length === 0) { + errors.stimulus_kinds = + "Select at least one stimulus or response component kind (including No input)." + errors.response_kinds = errors.stimulus_kinds + return errors + } if (sk.length && !uniqueStrings(sk)) errors.stimulus_kinds = "Stimulus kinds must be unique (no duplicates)." if (rk.length && !uniqueStrings(rk)) errors.response_kinds = "Response kinds must be unique (no duplicates)." - if (rk.length === 1 && rk[0] === "ANSWER_TIMER") { + const responseEffective = effectiveComponentKinds(rk) + const responseTimers = rk.filter((k) => k === "ANSWER_TIMER") + if ( + rk.length > 0 && + responseEffective.length === 0 && + responseTimers.length === 1 && + rk.length === 1 + ) { errors.response_kinds = "ANSWER_TIMER cannot be the only response kind." } @@ -58,14 +75,14 @@ export function validateDefinitionKinds( const sCat = new Set(catalog.stimulus_component_kinds) const rCat = new Set(catalog.response_component_kinds) if (sCat.size > 0 && sk.length) { - const invalid = sk.filter((k) => !sCat.has(k)) + const invalid = sk.filter((k) => !sCat.has(k) && !isNoInputComponentKind(k)) if (invalid.length) { const msg = `Not in stimulus catalog: ${invalid.join(", ")}.` errors.stimulus_kinds = errors.stimulus_kinds ? `${errors.stimulus_kinds} ${msg}` : msg } } if (rCat.size > 0 && rk.length) { - const invalid = rk.filter((k) => !rCat.has(k)) + const invalid = rk.filter((k) => !rCat.has(k) && !isNoInputComponentKind(k)) if (invalid.length) { const msg = `Not in response catalog: ${invalid.join(", ")}.` errors.response_kinds = errors.response_kinds ? `${errors.response_kinds} ${msg}` : msg @@ -91,8 +108,28 @@ export function validateDefinitionSchemas( side: "stimulus" | "response", ) => { const prefix = side + if (allowed.length === 0) return + + if (sideIsNoInputOnly(allowed)) { + if (rows.length > 1) { + errors[`${prefix}_schema`] = "At most one no-input slot is allowed for this section." + return + } + if (rows.length === 1) { + const row = rows[0] + if (!isNoInputComponentKind(row.kind)) { + errors[`${prefix}_schema`] = "This section only allows the No input component." + return + } + if (!row.id?.trim()) { + errors[`${prefix}_0`] = "Element id is required." + } + } + return + } + if (!rows.length) { - errors[`${prefix}_schema`] = `Add at least one ${side} schema row.` + errors[`${prefix}_schema`] = `Add at least one ${side} schema row, or choose No input for this section.` return } idsUniqueAndNonEmpty(rows, prefix, errors) @@ -101,14 +138,17 @@ export function validateDefinitionSchemas( const catalogSet = side === "stimulus" ? catalog.stimulus : catalog.response rows.forEach((row, i) => { const rowMessages: string[] = [] + if (isNoInputComponentKind(row.kind)) { + rowMessages.push("Remove No input rows or switch this section to No input only.") + } if (!row.kind) rowMessages.push("Kind is required.") else if (allowedSet.size && !allowedSet.has(row.kind)) { rowMessages.push(`Kind "${row.kind}" is not in selected ${side} kinds.`) } - if (catalogSet.size && row.kind && !catalogSet.has(row.kind)) { + if (catalogSet.size && row.kind && !catalogSet.has(row.kind) && !isNoInputComponentKind(row.kind)) { rowMessages.push(`Kind "${row.kind}" is not in the ${side} component catalog.`) } - if (!row.label?.trim()) { + if (!isNoInputComponentKind(row.kind) && !row.label?.trim()) { rowMessages.push("Label is required — this is the field title authors see when creating questions.") } if (rowMessages.length) errors[`${prefix}_${i}`] = rowMessages.join(" ") @@ -144,7 +184,7 @@ function uniqueKindsFromSchemaRows(rows: DynamicElementDefinition[]): string[] { return [...set].sort((a, b) => a.localeCompare(b)) } -const AUXILIARY_RESPONSE_KINDS = new Set(["ANSWER_TIMER"]) +const AUXILIARY_RESPONSE_KINDS = new Set(["ANSWER_TIMER", "NO_INPUT"]) const SHORT_ANSWER_RESPONSE_KINDS = new Set([ "SHORT_ANSWER", "TEXT_INPUT", @@ -183,24 +223,43 @@ export function buildValidateKindsPayload( export function buildCreatePayload( draft: QuestionTypeDefinitionCreatePayload, ): QuestionTypeDefinitionCreatePayload { - const stimulus_schema = draft.stimulus_schema.map((r) => ({ + const stimulus_schema = draft.stimulus_schema + .filter((r) => !isNoInputComponentKind(r.kind) || sideIsNoInputOnly(draft.stimulus_component_kinds)) + .map((r) => ({ ...r, id: r.id.trim(), kind: r.kind.trim(), - label: r.label?.trim() || defaultLabelForKind(r.kind), + label: isNoInputComponentKind(r.kind) + ? r.label?.trim() || defaultLabelForKind(r.kind) + : r.label?.trim() || defaultLabelForKind(r.kind), + required: isNoInputComponentKind(r.kind) ? false : r.required, config: r.config && Object.keys(r.config).length ? r.config : undefined, })) - const response_schema = draft.response_schema.map((r) => ({ + const response_schema = draft.response_schema + .filter((r) => !isNoInputComponentKind(r.kind) || sideIsNoInputOnly(draft.response_component_kinds)) + .map((r) => ({ ...r, id: r.id.trim(), kind: r.kind.trim(), - label: r.label?.trim() || defaultLabelForKind(r.kind), + label: isNoInputComponentKind(r.kind) + ? r.label?.trim() || defaultLabelForKind(r.kind) + : r.label?.trim() || defaultLabelForKind(r.kind), + required: isNoInputComponentKind(r.kind) ? false : r.required, config: r.config && Object.keys(r.config).length ? r.config : undefined, })) const stimulusKindsFromSchema = uniqueKindsFromSchemaRows(stimulus_schema) const responseKindsFromSchema = uniqueKindsFromSchemaRows(response_schema) + const finalStimulusSchema = + sideIsNoInputOnly(draft.stimulus_component_kinds) && stimulus_schema.length === 0 + ? [noInputSchemaRow()] + : stimulus_schema + const finalResponseSchema = + sideIsNoInputOnly(draft.response_component_kinds) && response_schema.length === 0 + ? [noInputSchemaRow()] + : response_schema + return { ...draft, key: draft.key.trim(), @@ -210,7 +269,7 @@ export function buildCreatePayload( stimulusKindsFromSchema.length > 0 ? stimulusKindsFromSchema : [...draft.stimulus_component_kinds], response_component_kinds: responseKindsFromSchema.length > 0 ? responseKindsFromSchema : [...draft.response_component_kinds], - stimulus_schema, - response_schema, + stimulus_schema: finalStimulusSchema, + response_schema: finalResponseSchema, } } diff --git a/src/pages/faqs/FaqsPage.tsx b/src/pages/faqs/FaqsPage.tsx index e159b79..dafc742 100644 --- a/src/pages/faqs/FaqsPage.tsx +++ b/src/pages/faqs/FaqsPage.tsx @@ -39,6 +39,7 @@ import { } from "../../lib/faqDisplay" import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors" import { countActiveFilters } from "../../lib/adminFilterUtils" +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" import { cn } from "../../lib/utils" import type { FAQ, FAQStatus } from "../../types/faq.types" @@ -57,7 +58,6 @@ export function FaqsPage() { const [error, setError] = useState(false) const [permissionDenied, setPermissionDenied] = useState(false) const [faqs, setFaqs] = useState([]) - const [totalCount, setTotalCount] = useState(0) const [page, setPage] = useState(1) const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [query, setQuery] = useState("") @@ -70,8 +70,6 @@ export function FaqsPage() { const [createOpen, setCreateOpen] = useState(false) const [suggestedDisplayOrder, setSuggestedDisplayOrder] = useState(1) - const offset = (page - 1) * pageSize - const load = useCallback(async () => { if (!canList) { setLoading(false) @@ -82,14 +80,19 @@ export function FaqsPage() { setError(false) setPermissionDenied(false) try { - const res = await getFAQs({ - status: statusFilter === "all" ? undefined : statusFilter, - category: categoryFilter || undefined, - limit: pageSize, - offset, + const allFaqs = await fetchAllOffsetPages(async (batchOffset, limit) => { + const res = await getFAQs({ + status: statusFilter === "all" ? undefined : statusFilter, + category: categoryFilter || undefined, + limit, + offset: batchOffset, + }) + return { + items: res.data.faqs, + total_count: res.data.total_count, + } }) - setFaqs(res.data.faqs) - setTotalCount(res.data.total_count) + setFaqs(allFaqs) const categoryRes = await getFAQs({ limit: 200, offset: 0 }) setAllCategories(deriveFaqCategories(categoryRes.data.faqs)) @@ -98,7 +101,6 @@ export function FaqsPage() { console.error(e) setError(true) setFaqs([]) - setTotalCount(0) if (isFaqForbiddenError(e)) { setPermissionDenied(true) toast.error(getFaqApiErrorMessage(e, "You do not have permission to view FAQs")) @@ -108,7 +110,7 @@ export function FaqsPage() { } finally { setLoading(false) } - }, [canList, statusFilter, categoryFilter, pageSize, offset]) + }, [canList, statusFilter, categoryFilter]) useEffect(() => { void load() @@ -116,7 +118,7 @@ export function FaqsPage() { useEffect(() => { setPage(1) - }, [statusFilter, categoryFilter, pageSize]) + }, [statusFilter, categoryFilter, pageSize, query]) const filtered = useMemo(() => { const q = query.trim().toLowerCase() @@ -129,9 +131,12 @@ export function FaqsPage() { }) }, [faqs, query]) + const totalCount = filtered.length const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)) - const pageStart = totalCount === 0 ? 0 : offset + 1 - const pageEnd = Math.min(offset + faqs.length, totalCount) + const safePage = Math.min(page, totalPages) + const paginated = filtered.slice((safePage - 1) * pageSize, safePage * pageSize) + const pageStart = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 + const pageEnd = Math.min(safePage * pageSize, totalCount) const canPrev = page > 1 const canNext = page < totalPages @@ -222,7 +227,7 @@ export function FaqsPage() { summary={ loading ? "Loading…" - : `${filtered.length} shown on page · ${totalCount} total` + : `${totalCount} shown · ${faqs.length} loaded` } search={
@@ -323,7 +328,7 @@ export function FaqsPage() { - {filtered.map((faq) => ( + {paginated.map((faq) => (

diff --git a/src/pages/issues/IssuesPage.tsx b/src/pages/issues/IssuesPage.tsx index 1201d5e..eed4cd4 100644 --- a/src/pages/issues/IssuesPage.tsx +++ b/src/pages/issues/IssuesPage.tsx @@ -25,6 +25,7 @@ import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"; import { Button } from "../../components/ui/button"; import { Input } from "../../components/ui/input"; import { countActiveFilters } from "../../lib/adminFilterUtils"; +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"; import { Table, TableBody, @@ -51,7 +52,7 @@ import { deleteIssue, createIssue, } from "../../api/issues.api"; -import type { Issue, IssueFilters } from "../../types/issue.types"; +import type { Issue } from "../../types/issue.types"; // ── Status configuration ─────────────────────────────────────────── const STATUSES = ["pending", "in_progress", "resolved", "closed"] as const; @@ -188,7 +189,6 @@ function formatRoleLabel(role: string | null | undefined): string { // ── Main Component ───────────────────────────────────────────────── export function IssuesPage() { const [issues, setIssues] = useState([]); - const [totalCount, setTotalCount] = useState(0); const [loading, setLoading] = useState(false); const [page, setPage] = useState(1); const [pageSize, setPageSize] = useState(10); @@ -221,27 +221,31 @@ export function IssuesPage() { const fetchIssues = useCallback(async () => { setLoading(true); try { - const filters: IssueFilters = { - limit: pageSize, - offset: (page - 1) * pageSize, - }; - const res = await getIssues(filters); - const payload = res.data?.data; - setIssues(Array.isArray(payload?.issues) ? payload.issues : []); - setTotalCount(typeof payload?.total_count === "number" ? payload.total_count : 0); + const allIssues = await fetchAllOffsetPages(async (offset, limit) => { + const res = await getIssues({ limit, offset }); + const payload = res.data?.data; + return { + items: Array.isArray(payload?.issues) ? payload.issues : [], + total_count: typeof payload?.total_count === "number" ? payload.total_count : undefined, + }; + }); + setIssues(allIssues); } catch (error) { console.error("Failed to fetch issues:", error); setIssues([]); - setTotalCount(0); } finally { setLoading(false); } - }, [page, pageSize]); + }, []); useEffect(() => { fetchIssues(); }, [fetchIssues]); + useEffect(() => { + setPage(1); + }, [searchQuery, statusFilter, typeFilter, pageSize]); + const handleViewDetail = async (issueId: number) => { setDialogOpen(true); setDetailLoading(true); @@ -326,9 +330,12 @@ export function IssuesPage() { return true; }); + const totalCount = filteredIssues.length; + // Pagination const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)); const safePage = Math.min(page, pageCount); + const paginatedIssues = filteredIssues.slice((safePage - 1) * pageSize, safePage * pageSize); const handlePrev = () => safePage > 1 && setPage(safePage - 1); const handleNext = () => safePage < pageCount && setPage(safePage + 1); @@ -528,7 +535,7 @@ export function IssuesPage() { ) : ( - filteredIssues.map((issue) => { + paginatedIssues.map((issue) => { const typeConfig = getIssueTypeConfig(issue.issue_type); const statusConfig = getStatusConfig(issue.status); const TypeIcon = typeConfig.icon; diff --git a/src/pages/notifications/NotificationsPage.tsx b/src/pages/notifications/NotificationsPage.tsx index 19cb976..1ed1fbf 100644 --- a/src/pages/notifications/NotificationsPage.tsx +++ b/src/pages/notifications/NotificationsPage.tsx @@ -27,6 +27,7 @@ import { DropdownMenuTrigger, } from "../../components/ui/dropdown-menu" import { countActiveFilters } from "../../lib/adminFilterUtils" +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { cn } from "../../lib/utils" import { SpinnerIcon } from "../../components/ui/spinner-icon" import { useNavigate } from "react-router-dom" @@ -174,7 +175,7 @@ function NotificationItem({ export function NotificationsPage() { const navigate = useNavigate() const [notifications, setNotifications] = useState([]) - const [totalCount, setTotalCount] = useState(0) + const [allCount, setAllCount] = useState(0) const [globalUnread, setGlobalUnread] = useState(0) const [offset, setOffset] = useState(0) const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) @@ -195,27 +196,37 @@ export function NotificationsPage() { const [typeFilter, setTypeFilter] = useState<"all" | string>("all") const [levelFilter, setLevelFilter] = useState<"all" | string>("all") - const fetchData = useCallback(async (currentOffset: number) => { + const fetchData = useCallback(async () => { setLoading(true) setError(false) try { - const [notifRes, unreadRes] = await Promise.all([ - getNotifications(pageSize, currentOffset), + const [allNotifications, unreadRes] = await Promise.all([ + fetchAllOffsetPages(async (batchOffset, limit) => { + const notifRes = await getNotifications(limit, batchOffset) + return { + items: notifRes.data.notifications ?? [], + total_count: notifRes.data.total_count, + } + }), getUnreadCount(), ]) - setNotifications(notifRes.data.notifications ?? []) - setTotalCount(notifRes.data.total_count) + setNotifications(allNotifications) + setAllCount(allNotifications.length) setGlobalUnread(unreadRes.data.unread) } catch { setError(true) } finally { setLoading(false) } - }, [pageSize]) + }, []) useEffect(() => { - fetchData(offset) - }, [offset, pageSize, fetchData]) + void fetchData() + }, [fetchData]) + + useEffect(() => { + setOffset(0) + }, [searchTerm, channelFilter, activeStatusTab, typeFilter, levelFilter, pageSize]) const handleToggleRead = useCallback(async (id: string, currentlyRead: boolean) => { setTogglingIds((prev) => new Set(prev).add(id)) @@ -258,32 +269,13 @@ export function NotificationsPage() { try { await markAllUnread() setNotifications((prev) => prev.map((n) => ({ ...n, is_read: false }))) - setGlobalUnread(totalCount) + setGlobalUnread(allCount) } catch { // silently fail } finally { setBulkLoading(false) } - }, [totalCount]) - - const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)) - const currentPage = Math.floor(offset / pageSize) + 1 - const startEntry = totalCount === 0 ? 0 : offset + 1 - const endEntry = Math.min(offset + pageSize, totalCount) - - const getPageNumbers = () => { - const pages: (number | string)[] = [] - if (totalPages <= 7) { - for (let i = 1; i <= totalPages; i++) pages.push(i) - } else { - pages.push(1, 2, 3) - if (currentPage > 4) pages.push("...") - if (currentPage > 3 && currentPage < totalPages - 2) pages.push(currentPage) - if (currentPage < totalPages - 3) pages.push("...") - pages.push(totalPages) - } - return pages - } + }, [allCount]) const filteredNotifications = notifications.filter((n) => { if (channelFilter !== "all" && n.delivery_channel !== channelFilter) return false @@ -308,6 +300,27 @@ export function NotificationsPage() { return true }) + const totalCount = filteredNotifications.length + const paginatedNotifications = filteredNotifications.slice(offset, offset + pageSize) + const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)) + const currentPage = Math.floor(offset / pageSize) + 1 + const startEntry = totalCount === 0 ? 0 : offset + 1 + const endEntry = Math.min(offset + paginatedNotifications.length, totalCount) + + const getPageNumbers = () => { + const pages: (number | string)[] = [] + if (totalPages <= 7) { + for (let i = 1; i <= totalPages; i++) pages.push(i) + } else { + pages.push(1, 2, 3) + if (currentPage > 4) pages.push("...") + if (currentPage > 3 && currentPage < totalPages - 2) pages.push(currentPage) + if (currentPage < totalPages - 3) pages.push("...") + pages.push(totalPages) + } + return pages + } + const activeFilterCount = countActiveFilters([ { value: activeStatusTab, defaultValue: "all" }, { value: channelFilter, defaultValue: "all" }, @@ -524,7 +537,7 @@ export function NotificationsPage() { className="mb-3" activeFilterCount={activeFilterCount} onClearFilters={clearFilters} - summary={`${filteredNotifications.length} shown · ${totalCount} total`} + summary={`${totalCount} shown · ${allCount} total`} search={

@@ -665,7 +678,7 @@ export function NotificationsPage() { ) : ( - filteredNotifications.map((n) => { + paginatedNotifications.map((n) => { const config = NOTIFICATION_TYPE_CONFIG[n.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG const Icon = config.icon const isToggling = togglingIds.has(n.id) diff --git a/src/pages/personas/PersonasPage.tsx b/src/pages/personas/PersonasPage.tsx index 75c57f6..1b32877 100644 --- a/src/pages/personas/PersonasPage.tsx +++ b/src/pages/personas/PersonasPage.tsx @@ -29,6 +29,7 @@ import { } from "../../components/ui/table" import { usePersonaPermissions } from "../../hooks/usePersonaPermissions" import { countActiveFilters } from "../../lib/adminFilterUtils" +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { formatPersonaDate, personaAvatarUrl, @@ -61,7 +62,6 @@ export function PersonasPage() { const [error, setError] = useState(false) const [permissionDenied, setPermissionDenied] = useState(false) const [personas, setPersonas] = useState([]) - const [totalCount, setTotalCount] = useState(0) const [page, setPage] = useState(1) const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [query, setQuery] = useState("") @@ -71,8 +71,6 @@ export function PersonasPage() { const [personaPendingDelete, setPersonaPendingDelete] = useState(null) const [togglingId, setTogglingId] = useState(null) - const offset = (page - 1) * pageSize - const load = useCallback(async () => { if (!canList) { setLoading(false) @@ -84,18 +82,22 @@ export function PersonasPage() { setPermissionDenied(false) try { - const res = await listPersonas({ - active_only: statusFilter === "active", - limit: pageSize, - offset, + const allPersonas = await fetchAllOffsetPages(async (batchOffset, limit) => { + const res = await listPersonas({ + active_only: statusFilter === "active", + limit, + offset: batchOffset, + }) + return { + items: res.data.personas, + total_count: res.data.total_count, + } }) - setPersonas(res.data.personas) - setTotalCount(res.data.total_count) + setPersonas(allPersonas) } catch (e) { console.error(e) setError(true) setPersonas([]) - setTotalCount(0) if (isPersonaForbiddenError(e)) { setPermissionDenied(true) toast.error(getPersonaApiErrorMessage(e, "You do not have permission to view personas")) @@ -105,7 +107,7 @@ export function PersonasPage() { } finally { setLoading(false) } - }, [canList, statusFilter, pageSize, offset]) + }, [canList, statusFilter]) useEffect(() => { void load() @@ -113,7 +115,7 @@ export function PersonasPage() { useEffect(() => { setPage(1) - }, [statusFilter, pageSize]) + }, [statusFilter, pageSize, query]) const filtered = useMemo(() => { let rows = personas @@ -142,13 +144,16 @@ export function PersonasPage() { const clearFilters = () => { setStatusFilter("all") + setQuery("") setPage(1) } + const totalCount = filtered.length const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)) const safePage = Math.min(page, totalPages) - const startEntry = totalCount === 0 ? 0 : offset + 1 - const endEntry = Math.min(offset + personas.length, totalCount) + const paginated = filtered.slice((safePage - 1) * pageSize, safePage * pageSize) + const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 + const endEntry = Math.min(safePage * pageSize, totalCount) const handleToggleActive = async (persona: LmsPersona) => { if (!canUpdate) { @@ -291,7 +296,7 @@ export function PersonasPage() { ) : ( - filtered.map((persona) => ( + paginated.map((persona) => ( { void load() @@ -106,7 +106,7 @@ export function AppReviewsPage() { useEffect(() => { setPage(1) - }, [pageSize, starsFilter]) + }, [pageSize, starsFilter, query]) const filteredReviews = useMemo(() => { const q = query.trim().toLowerCase() @@ -134,13 +134,14 @@ export function AppReviewsPage() { setPage(1) } - const totalCount = summary.total_count + const totalCount = filteredReviews.length const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)) const safePage = Math.min(page, totalPages) + const paginatedReviews = filteredReviews.slice((safePage - 1) * pageSize, safePage * pageSize) const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 const endEntry = Math.min(safePage * pageSize, totalCount) - const writtenOnPage = reviews.filter((r) => r.review?.trim()).length + const writtenOnPage = paginatedReviews.filter((r) => r.review?.trim()).length if (!permissionsLoading && !canList) { return @@ -211,7 +212,7 @@ export function AppReviewsPage() { className="border-0 shadow-none" activeFilterCount={activeFilterCount} onClearFilters={clearFilters} - footer="Star and text filters apply to the current page only. Server-side search is not available yet." + footer="Star and text filters apply across all reviews." summary={ totalCount > 0 ? `Showing ${startEntry}–${endEntry} of ${totalCount}` @@ -279,18 +280,18 @@ export function AppReviewsPage() {

{totalCount === 0 ? "No reviews yet" - : "No reviews match your filters on this page"} + : "No reviews match your filters"}

- {totalCount === 0 + {summary.total_count === 0 ? "Learners can submit ratings from the mobile or web app." - : "Try different filters or go to another page."} + : "Try different filters or search terms."}

) : ( - filteredReviews.map((rating) => { + paginatedReviews.map((rating) => { const profile = reviewerProfiles.get(rating.user_id) return ( diff --git a/src/pages/settings/AppVersionsTab.tsx b/src/pages/settings/AppVersionsTab.tsx index da87ee9..590b949 100644 --- a/src/pages/settings/AppVersionsTab.tsx +++ b/src/pages/settings/AppVersionsTab.tsx @@ -24,6 +24,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca import { Input } from "../../components/ui/input" import { SpinnerIcon } from "../../components/ui/spinner-icon" import { countActiveFilters } from "../../lib/adminFilterUtils" +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages" import { cn } from "../../lib/utils" import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" import { @@ -64,7 +65,6 @@ export function AppVersionsTab() { const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const [versions, setVersions] = useState([]) - const [totalCount, setTotalCount] = useState(0) const [offset, setOffset] = useState(0) const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [query, setQuery] = useState("") @@ -78,24 +78,32 @@ export function AppVersionsTab() { setLoading(true) setError(false) try { - const res = await getAppVersions({ limit: pageSize, offset }) - setVersions(res.data.versions) - setTotalCount(res.data.total_count) + const allVersions = await fetchAllOffsetPages(async (batchOffset, limit) => { + const res = await getAppVersions({ limit, offset: batchOffset }) + return { + items: res.data.versions, + total_count: res.data.total_count, + } + }) + setVersions(allVersions) } catch (e) { console.error(e) setError(true) setVersions([]) - setTotalCount(0) toast.error("Failed to load app versions") } finally { setLoading(false) } - }, [offset, pageSize]) + }, []) useEffect(() => { void load() }, [load]) + useEffect(() => { + setOffset(0) + }, [query, platformFilter, statusFilter, pageSize]) + const filtered = useMemo(() => { const q = query.trim().toLowerCase() return [...versions] @@ -123,8 +131,10 @@ export function AppVersionsTab() { const activeCount = versions.filter((v) => v.status.toUpperCase() === "ACTIVE").length const forceCount = versions.filter((v) => v.update_type.toUpperCase() === "FORCE").length + const totalCount = filtered.length + const paginated = filtered.slice(offset, offset + pageSize) const pageStart = totalCount === 0 ? 0 : offset + 1 - const pageEnd = Math.min(offset + versions.length, totalCount) + const pageEnd = Math.min(offset + paginated.length, totalCount) const canPrev = offset > 0 const canNext = offset + pageSize < totalCount @@ -364,7 +374,7 @@ export function AppVersionsTab() { - {filtered.map((version) => ( + {paginated.map((version) => (

diff --git a/src/pages/user-log/UserLogPage.tsx b/src/pages/user-log/UserLogPage.tsx index 34d70b6..c899013 100644 --- a/src/pages/user-log/UserLogPage.tsx +++ b/src/pages/user-log/UserLogPage.tsx @@ -36,6 +36,7 @@ import { DialogDescription, } from "../../components/ui/dialog"; import { countActiveFilters } from "../../lib/adminFilterUtils"; +import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"; import { cn } from "../../lib/utils"; import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"; import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api"; @@ -133,7 +134,6 @@ function formatRoleLabel(role: string): string { // ── Main Component ───────────────────────────────────────────────── export function UserLogPage() { const [logs, setLogs] = useState([]); - const [totalCount, setTotalCount] = useState(0); const [loading, setLoading] = useState(false); const [page, setPage] = useState(1); const [pageSize, setPageSize] = useState(10); @@ -150,30 +150,35 @@ export function UserLogPage() { const fetchLogs = useCallback(async () => { setLoading(true); try { - const filters: ActivityLogFilters = { - limit: pageSize, - offset: (page - 1) * pageSize, - }; - if (actionFilter) filters.action = actionFilter; - if (dateAfter) filters.after = new Date(dateAfter).toISOString(); - if (dateBefore) filters.before = new Date(dateBefore).toISOString(); + const allLogs = await fetchAllOffsetPages(async (offset, limit) => { + const filters: ActivityLogFilters = { limit, offset }; + if (actionFilter) filters.action = actionFilter; + if (dateAfter) filters.after = new Date(dateAfter).toISOString(); + if (dateBefore) filters.before = new Date(dateBefore).toISOString(); - const res = await getActivityLogs(filters); - setLogs(res.data.data.logs); - setTotalCount(res.data.data.total_count); + const res = await getActivityLogs(filters); + return { + items: res.data.data.logs, + total_count: res.data.data.total_count, + }; + }); + setLogs(allLogs); } catch (error) { console.error("Failed to fetch activity logs:", error); setLogs([]); - setTotalCount(0); } finally { setLoading(false); } - }, [page, pageSize, actionFilter, dateAfter, dateBefore]); + }, [actionFilter, dateAfter, dateBefore]); useEffect(() => { fetchLogs(); }, [fetchLogs]); + useEffect(() => { + setPage(1); + }, [searchQuery, pageSize]); + const handleViewDetail = async (logId: number) => { setDialogOpen(true); setDetailLoading(true); @@ -207,9 +212,24 @@ export function UserLogPage() { const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim()); + // Filter logs by search (client-side on the message field) + const filteredLogs = searchQuery + ? logs.filter( + (log) => + log.message?.toLowerCase().includes(searchQuery.toLowerCase()) || + log.action.toLowerCase().includes(searchQuery.toLowerCase()) || + log.actor_role?.toLowerCase().includes(searchQuery.toLowerCase()) + ) + : logs; + + const totalCount = filteredLogs.length; + // Pagination const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)); const safePage = Math.min(page, pageCount); + const paginatedLogs = filteredLogs.slice((safePage - 1) * pageSize, safePage * pageSize); + const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1; + const endEntry = Math.min(safePage * pageSize, totalCount); const handlePrev = () => safePage > 1 && setPage(safePage - 1); const handleNext = () => safePage < pageCount && setPage(safePage + 1); @@ -228,19 +248,6 @@ export function UserLogPage() { return pages; }; - // Filter logs by search (client-side on the message field) - const filteredLogs = searchQuery - ? logs.filter( - (log) => - log.message?.toLowerCase().includes(searchQuery.toLowerCase()) || - log.action.toLowerCase().includes(searchQuery.toLowerCase()) || - log.actor_role?.toLowerCase().includes(searchQuery.toLowerCase()) - ) - : logs; - - const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1; - const endEntry = Math.min(safePage * pageSize, totalCount); - return (

{/* Header */} @@ -399,7 +406,7 @@ export function UserLogPage() { ) : ( - filteredLogs.map((log) => { + paginatedLogs.map((log) => { const ActionIcon = getActionIcon(log.action); return (