Add NO_INPUT question types and fix cross-page client search.
Support No input stimulus/response slots in dynamic question type definitions, allow saving unmappable types on review, and load full datasets before client-side search so filters work across paginated lists. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
ad75a06284
commit
c587ea90d8
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<string, string> = { ...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,
|
||||
|
|
|
|||
36
src/lib/fetchAllOffsetPages.ts
Normal file
36
src/lib/fetchAllOffsetPages.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
export type OffsetPageResult<T> = {
|
||||
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<T>(
|
||||
fetchPage: (offset: number, limit: number) => Promise<OffsetPageResult<T>>,
|
||||
batchSize = DEFAULT_BATCH_SIZE,
|
||||
): Promise<T[]> {
|
||||
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
|
||||
}
|
||||
|
|
@ -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<string, string> {
|
||||
const o: Record<string, string> = {}
|
||||
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)) {
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
33
src/lib/questionComponentKinds.ts
Normal file
33
src/lib/questionComponentKinds.ts
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ const KIND_DEFAULT_LABELS: Record<string, string> = {
|
|||
MATCHING_ANSWER: "Matching answer",
|
||||
LABEL_SELECTION: "Label selection",
|
||||
SEQUENCE_ORDER: "Sequence order",
|
||||
NO_INPUT: "No input",
|
||||
}
|
||||
|
||||
export function humanizeKind(kind: string): string {
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
<QuestionTypeConfigStep
|
||||
draft={draft}
|
||||
setDraft={setDraft}
|
||||
stimulusCatalogKinds={componentCatalog.stimulus_component_kinds}
|
||||
responseCatalogKinds={componentCatalog.response_component_kinds}
|
||||
stimulusCatalogKinds={stimulusCatalogKinds}
|
||||
responseCatalogKinds={responseCatalogKinds}
|
||||
catalogLoading={catalogLoading}
|
||||
catalogError={catalogError}
|
||||
errors={stepErrors}
|
||||
|
|
|
|||
|
|
@ -52,8 +52,6 @@ const SCOPE_OPTIONS: { value: ScopeFilter; label: string }[] = [
|
|||
{ value: "custom", label: "Custom only" },
|
||||
]
|
||||
|
||||
const SYSTEM_SCOPE_FETCH_LIMIT = 100
|
||||
|
||||
export function QuestionTypeLibraryPage() {
|
||||
const navigate = useNavigate()
|
||||
const [searchParams] = useSearchParams()
|
||||
|
|
@ -62,7 +60,6 @@ export function QuestionTypeLibraryPage() {
|
|||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [definitions, setDefinitions] = useState<QuestionTypeDefinition[]>([])
|
||||
const [totalCount, setTotalCount] = useState<number | undefined>(undefined)
|
||||
const [query, setQuery] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
|
||||
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("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() {
|
|||
<Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="h-11 pl-11 pr-10 rounded-[10px] border-grayScale-200 bg-white placeholder:text-grayScale-400 text-sm shadow-sm"
|
||||
placeholder="Search by display name, key, or id on this page…"
|
||||
placeholder="Search by display name, key, or id…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
|
|
@ -353,7 +342,7 @@ export function QuestionTypeLibraryPage() {
|
|||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-5 px-6 py-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{filtered.map((d) => (
|
||||
{paginated.map((d) => (
|
||||
<QuestionTypeCard
|
||||
key={d.id}
|
||||
id={d.id}
|
||||
|
|
@ -379,13 +368,13 @@ export function QuestionTypeLibraryPage() {
|
|||
<div className="flex flex-wrap items-center justify-between gap-4 border-t border-grayScale-100 bg-white px-6 py-4">
|
||||
<div className="flex flex-wrap items-center gap-3 text-xs text-grayScale-500">
|
||||
<span>
|
||||
{totalCount != null
|
||||
? `Showing ${pageStart}–${pageEnd} of ${totalCount}`
|
||||
: `Showing ${pageStart}–${pageEnd}`}
|
||||
{totalCount === 0
|
||||
? "No results"
|
||||
: `Showing ${pageStart}–${pageEnd} of ${totalCount}`}
|
||||
</span>
|
||||
{query.trim() && filtered.length !== definitions.length ? (
|
||||
<span className="rounded-full bg-brand-50 px-2.5 py-0.5 text-[11px] font-semibold text-brand-600">
|
||||
{filtered.length} match{filtered.length === 1 ? "" : "es"} on this page
|
||||
{filtered.length} match{filtered.length === 1 ? "" : "es"} total
|
||||
</span>
|
||||
) : null}
|
||||
{!isSystemScope ? (
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -17,8 +17,9 @@ export function DefinitionRuntimeHint({
|
|||
<div>
|
||||
<p className="font-semibold">May not be publishable</p>
|
||||
<p className="mt-0.5 text-amber-800/90">
|
||||
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.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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) ? (
|
||||
<div className="flex items-center justify-between gap-2 px-0.5 min-h-[32px]">
|
||||
<span className="text-[12px] text-grayScale-500 font-medium">
|
||||
{slotCount} slot{slotCount === 1 ? "" : "s"}
|
||||
|
|
@ -310,7 +342,7 @@ export function QuestionTypeConfigStep({
|
|||
selected={selected}
|
||||
onClick={() => handleResponseKindClick(kind)}
|
||||
/>
|
||||
{selected ? (
|
||||
{selected && !isNoInputComponentKind(kind) ? (
|
||||
<div className="flex items-center justify-between gap-2 px-0.5 min-h-[32px]">
|
||||
<span className="text-[12px] text-grayScale-500 font-medium">
|
||||
{slotCount} slot{slotCount === 1 ? "" : "s"}
|
||||
|
|
|
|||
|
|
@ -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({
|
|||
</p>
|
||||
) : null}
|
||||
|
||||
<DefinitionRuntimeHint
|
||||
definitionKey={payload.key}
|
||||
responseKinds={payload.response_component_kinds}
|
||||
/>
|
||||
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Key</dt>
|
||||
|
|
@ -136,7 +123,7 @@ export function QuestionTypeReviewPublishStep({
|
|||
</div>
|
||||
<div>
|
||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Runtime type</dt>
|
||||
<dd className="font-medium text-grayScale-900 mt-1">{runtime ?? "Unmappable"}</dd>
|
||||
<dd className="font-medium text-grayScale-900 mt-1">{runtime ?? "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Stimulus kinds</dt>
|
||||
|
|
@ -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({
|
|||
<Button
|
||||
type="button"
|
||||
className="h-11 bg-[#9E2891] hover:bg-[#8A237E] text-white"
|
||||
disabled={submitting || runtime == null}
|
||||
disabled={submitting}
|
||||
onClick={() => void submit("ACTIVE")}
|
||||
>
|
||||
{submitting ? (
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
getResponseKindPresentation,
|
||||
getStimulusKindPresentation,
|
||||
} from "./componentKindUi"
|
||||
import { isNoInputComponentKind } from "../../../../lib/questionComponentKinds"
|
||||
|
||||
type Side = "stimulus" | "response"
|
||||
|
||||
|
|
@ -119,7 +120,9 @@ export function SchemaBuilderSection({
|
|||
) : null}
|
||||
|
||||
<div className="space-y-3">
|
||||
{rows.map((row, index) => (
|
||||
{rows.map((row, index) => {
|
||||
const noInput = isNoInputComponentKind(row.kind)
|
||||
return (
|
||||
<div
|
||||
key={`${side}-${index}`}
|
||||
className="rounded-xl border border-grayScale-200 bg-[#F8FAFC] p-4 space-y-3"
|
||||
|
|
@ -135,6 +138,7 @@ export function SchemaBuilderSection({
|
|||
className="h-8 w-8 p-0 text-grayScale-500 hover:text-red-600"
|
||||
onClick={() => removeRow(index)}
|
||||
aria-label="Remove row"
|
||||
disabled={noInput}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
|
|
@ -170,6 +174,13 @@ export function SchemaBuilderSection({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{noInput ? (
|
||||
<p className="text-[12px] text-grayScale-500">
|
||||
No author input is collected for this side. Deselect No input in the component picker to use
|
||||
other kinds.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[12px] font-semibold text-grayScale-600">
|
||||
|
|
@ -204,10 +215,12 @@ export function SchemaBuilderSection({
|
|||
/>
|
||||
<p className="text-[11px] text-grayScale-400">Tab out of the field to apply JSON config.</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{rowErrors?.[index] ? <p className="text-sm text-red-600">{rowErrors[index]}</p> : null}
|
||||
</div>
|
||||
))}
|
||||
)})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label className="text-[12px] font-semibold text-grayScale-600">
|
||||
Field label <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Input
|
||||
value={row.label ?? ""}
|
||||
onChange={(e) => onChange(updateRowLabel(rows, index, e.target.value))}
|
||||
placeholder={defaultLabelForKind(row.kind)}
|
||||
className="h-10 bg-white"
|
||||
/>
|
||||
<p className="text-[11px] text-grayScale-400">
|
||||
Shown to authors when they create questions from this type.
|
||||
</p>
|
||||
{isNoInputComponentKind(row.kind) ? (
|
||||
<p className="text-[12px] text-grayScale-500">
|
||||
No author input is collected for this side.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="text-[12px] font-semibold text-grayScale-600">
|
||||
Field label <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Input
|
||||
value={row.label ?? ""}
|
||||
onChange={(e) => onChange(updateRowLabel(rows, index, e.target.value))}
|
||||
placeholder={defaultLabelForKind(row.kind)}
|
||||
className="h-10 bg-white"
|
||||
/>
|
||||
<p className="text-[11px] text-grayScale-400">
|
||||
Shown to authors when they create questions from this type.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{rowError ? <p className="text-sm text-red-600">{rowError}</p> : null}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
ListOrdered,
|
||||
ListTodo,
|
||||
Mic2,
|
||||
Minus,
|
||||
MousePointer2,
|
||||
Table as TableIcon,
|
||||
Type,
|
||||
|
|
@ -35,6 +36,7 @@ const STIMULUS_LABELS: Record<string, string> = {
|
|||
SELECT_MISSING_WORDS: defaultLabelForKind("SELECT_MISSING_WORDS"),
|
||||
TABLE: defaultLabelForKind("TABLE"),
|
||||
PDF_ATTACHMENT: defaultLabelForKind("PDF_ATTACHMENT"),
|
||||
NO_INPUT: defaultLabelForKind("NO_INPUT"),
|
||||
}
|
||||
|
||||
const RESPONSE_LABELS: Record<string, string> = {
|
||||
|
|
@ -49,6 +51,7 @@ const RESPONSE_LABELS: Record<string, string> = {
|
|||
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<string, LucideIcon> = {
|
|||
SELECT_MISSING_WORDS: ListTodo,
|
||||
TABLE: TableIcon,
|
||||
PDF_ATTACHMENT: FileUp,
|
||||
NO_INPUT: Minus,
|
||||
}
|
||||
|
||||
const RESPONSE_ICONS: Record<string, LucideIcon> = {
|
||||
|
|
@ -78,6 +82,7 @@ const RESPONSE_ICONS: Record<string, LucideIcon> = {
|
|||
MATCHING_ANSWER: GitCompare,
|
||||
LABEL_SELECTION: MousePointer2,
|
||||
SEQUENCE_ORDER: ListOrdered,
|
||||
NO_INPUT: Minus,
|
||||
}
|
||||
|
||||
const DEFAULT_ICON = FileText
|
||||
|
|
|
|||
|
|
@ -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<string, string>
|
||||
|
||||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<FAQ[]>([])
|
||||
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={
|
||||
<div className="relative w-full">
|
||||
|
|
@ -323,7 +328,7 @@ export function FaqsPage() {
|
|||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filtered.map((faq) => (
|
||||
{paginated.map((faq) => (
|
||||
<TableRow key={faq.id}>
|
||||
<TableCell className="max-w-xs">
|
||||
<p className="line-clamp-2 font-medium text-grayScale-900">
|
||||
|
|
|
|||
|
|
@ -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<Issue[]>([]);
|
||||
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() {
|
|||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filteredIssues.map((issue) => {
|
||||
paginatedIssues.map((issue) => {
|
||||
const typeConfig = getIssueTypeConfig(issue.issue_type);
|
||||
const statusConfig = getStatusConfig(issue.status);
|
||||
const TypeIcon = typeConfig.icon;
|
||||
|
|
|
|||
|
|
@ -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<Notification[]>([])
|
||||
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={
|
||||
<div className="relative w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
|
|
@ -665,7 +678,7 @@ export function NotificationsPage() {
|
|||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -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<LmsPersona[]>([])
|
||||
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<LmsPersona | null>(null)
|
||||
const [togglingId, setTogglingId] = useState<number | null>(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() {
|
|||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filtered.map((persona) => (
|
||||
paginated.map((persona) => (
|
||||
<TableRow key={persona.id}>
|
||||
<TableCell className="py-3.5">
|
||||
<img
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
Star,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { loadRatingsPage } from "../../api/ratings.api"
|
||||
import { fetchAllRatingsByTarget } from "../../api/ratings.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
|
|
@ -77,7 +77,7 @@ export function AppReviewsPage() {
|
|||
setPermissionDenied(false)
|
||||
|
||||
try {
|
||||
const data = await loadRatingsPage(APP_TARGET_TYPE, page, pageSize, APP_TARGET_ID)
|
||||
const data = await fetchAllRatingsByTarget(APP_TARGET_TYPE, APP_TARGET_ID)
|
||||
setSummary(data.summary)
|
||||
setReviews(data.reviews)
|
||||
|
||||
|
|
@ -98,7 +98,7 @@ export function AppReviewsPage() {
|
|||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [canList, page, pageSize])
|
||||
}, [canList])
|
||||
|
||||
useEffect(() => {
|
||||
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 <RatingsAccessDenied />
|
||||
|
|
@ -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() {
|
|||
<p className="text-sm font-medium text-grayScale-500">
|
||||
{totalCount === 0
|
||||
? "No reviews yet"
|
||||
: "No reviews match your filters on this page"}
|
||||
: "No reviews match your filters"}
|
||||
</p>
|
||||
<p className="text-xs text-grayScale-400">
|
||||
{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."}
|
||||
</p>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filteredReviews.map((rating) => {
|
||||
paginatedReviews.map((rating) => {
|
||||
const profile = reviewerProfiles.get(rating.user_id)
|
||||
return (
|
||||
<TableRow key={rating.id}>
|
||||
|
|
|
|||
|
|
@ -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<AppVersion[]>([])
|
||||
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() {
|
|||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-grayScale-50">
|
||||
{filtered.map((version) => (
|
||||
{paginated.map((version) => (
|
||||
<tr key={version.id} className="group transition-colors hover:bg-grayScale-50/60">
|
||||
<td className="whitespace-nowrap px-3 py-3 sm:px-4 sm:py-4">
|
||||
<p className="font-semibold text-grayScale-900">
|
||||
|
|
|
|||
|
|
@ -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<ActivityLog[]>([]);
|
||||
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 (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
|
|
@ -399,7 +406,7 @@ export function UserLogPage() {
|
|||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filteredLogs.map((log) => {
|
||||
paginatedLogs.map((log) => {
|
||||
const ActionIcon = getActionIcon(log.action);
|
||||
return (
|
||||
<TableRow key={log.id} className="group">
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user