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 http from "./http"
|
||||||
|
import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||||
import type {
|
import type {
|
||||||
AppReviewsPageData,
|
AppReviewsPageData,
|
||||||
|
|
@ -121,6 +122,30 @@ export async function loadRatingsPage(
|
||||||
return { summary, reviews }
|
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. */
|
/** @deprecated Use listRatingsByTarget — kept for legacy callers. */
|
||||||
export function getRatings(params: {
|
export function getRatings(params: {
|
||||||
target_type: string
|
target_type: string
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ import { Select } from "../ui/select"
|
||||||
import { Button } from "../ui/button"
|
import { Button } from "../ui/button"
|
||||||
import { SpinnerIcon } from "../ui/spinner-icon"
|
import { SpinnerIcon } from "../ui/spinner-icon"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
|
import { isNoInputComponentKind } from "../../lib/questionComponentKinds"
|
||||||
import { ResolvedAudio } from "../media/ResolvedAudio"
|
import { ResolvedAudio } from "../media/ResolvedAudio"
|
||||||
import { ResolvedImage } from "../media/ResolvedImage"
|
import { ResolvedImage } from "../media/ResolvedImage"
|
||||||
import { DynamicSchemaSlotField } from "./DynamicSchemaSlotField"
|
import { DynamicSchemaSlotField } from "./DynamicSchemaSlotField"
|
||||||
|
|
@ -670,13 +671,17 @@ export function PracticeQuestionEditorFields({
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const fieldValues: Record<string, string> = { ...value.dynamicFieldValues }
|
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,
|
id: r.id,
|
||||||
kind: r.kind,
|
kind: r.kind,
|
||||||
label: r.label,
|
label: r.label,
|
||||||
required: r.required,
|
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,
|
id: r.id,
|
||||||
kind: r.kind,
|
kind: r.kind,
|
||||||
label: r.label,
|
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,
|
validateSelectMissingWordsResponseSlotValue,
|
||||||
validateSelectMissingWordsStimulusSlotValue,
|
validateSelectMissingWordsStimulusSlotValue,
|
||||||
} from "./selectMissingWordsSlotValue"
|
} from "./selectMissingWordsSlotValue"
|
||||||
|
import { isNoInputComponentKind } from "./questionComponentKinds"
|
||||||
|
|
||||||
function isMultipleChoiceKind(kind: string): boolean {
|
function isMultipleChoiceKind(kind: string): boolean {
|
||||||
const u = kind.trim().toUpperCase()
|
const u = kind.trim().toUpperCase()
|
||||||
|
|
@ -64,6 +65,7 @@ function defaultValueForSchemaSlot(
|
||||||
kind: string,
|
kind: string,
|
||||||
side: "stimulus" | "response",
|
side: "stimulus" | "response",
|
||||||
): string {
|
): string {
|
||||||
|
if (isNoInputComponentKind(kind)) return ""
|
||||||
const u = kind.trim().toUpperCase()
|
const u = kind.trim().toUpperCase()
|
||||||
if (u === "TABLE") {
|
if (u === "TABLE") {
|
||||||
return serializeTableSlotValue(createEmptyTable(2, 1))
|
return serializeTableSlotValue(createEmptyTable(2, 1))
|
||||||
|
|
@ -89,7 +91,9 @@ function defaultValueForSchemaSlot(
|
||||||
}
|
}
|
||||||
|
|
||||||
export function definitionUsesDynamicPayload(def: QuestionTypeDefinition): boolean {
|
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(
|
export function emptyDynamicFieldValuesForDefinition(
|
||||||
|
|
@ -97,9 +101,11 @@ export function emptyDynamicFieldValuesForDefinition(
|
||||||
): Record<string, string> {
|
): Record<string, string> {
|
||||||
const o: Record<string, string> = {}
|
const o: Record<string, string> = {}
|
||||||
for (const r of def.stimulus_schema) {
|
for (const r of def.stimulus_schema) {
|
||||||
|
if (isNoInputComponentKind(r.kind)) continue
|
||||||
o[`stimulus:${r.id}`] = defaultValueForSchemaSlot(r.kind, "stimulus")
|
o[`stimulus:${r.id}`] = defaultValueForSchemaSlot(r.kind, "stimulus")
|
||||||
}
|
}
|
||||||
for (const r of def.response_schema) {
|
for (const r of def.response_schema) {
|
||||||
|
if (isNoInputComponentKind(r.kind)) continue
|
||||||
o[`response:${r.id}`] = defaultValueForSchemaSlot(r.kind, "response")
|
o[`response:${r.id}`] = defaultValueForSchemaSlot(r.kind, "response")
|
||||||
}
|
}
|
||||||
return o
|
return o
|
||||||
|
|
@ -190,6 +196,7 @@ export function questionRowHasContent(
|
||||||
if (q.questionText.trim()) return true
|
if (q.questionText.trim()) return true
|
||||||
const fv = q.dynamicFieldValues ?? {}
|
const fv = q.dynamicFieldValues ?? {}
|
||||||
for (const row of def.stimulus_schema) {
|
for (const row of def.stimulus_schema) {
|
||||||
|
if (isNoInputComponentKind(row.kind)) continue
|
||||||
if (isMultipleChoiceKind(row.kind)) {
|
if (isMultipleChoiceKind(row.kind)) {
|
||||||
if (
|
if (
|
||||||
multipleChoiceSlotHasContent(
|
multipleChoiceSlotHasContent(
|
||||||
|
|
@ -233,6 +240,7 @@ export function questionRowHasContent(
|
||||||
if (fv[`stimulus:${row.id}`]?.trim()) return true
|
if (fv[`stimulus:${row.id}`]?.trim()) return true
|
||||||
}
|
}
|
||||||
for (const row of def.response_schema) {
|
for (const row of def.response_schema) {
|
||||||
|
if (isNoInputComponentKind(row.kind)) continue
|
||||||
if (isMultipleChoiceKind(row.kind)) {
|
if (isMultipleChoiceKind(row.kind)) {
|
||||||
if (
|
if (
|
||||||
multipleChoiceSlotHasContent(
|
multipleChoiceSlotHasContent(
|
||||||
|
|
@ -404,6 +412,7 @@ export function validateDefinitionQuestion(
|
||||||
return `Question ${n}: enter prompt text (${promptRow.label || promptRow.id}).`
|
return `Question ${n}: enter prompt text (${promptRow.label || promptRow.id}).`
|
||||||
}
|
}
|
||||||
for (const row of def.stimulus_schema) {
|
for (const row of def.stimulus_schema) {
|
||||||
|
if (isNoInputComponentKind(row.kind)) continue
|
||||||
if (isStructuredDynamicSlotKind(row.kind)) continue
|
if (isStructuredDynamicSlotKind(row.kind)) continue
|
||||||
if (!row.required) continue
|
if (!row.required) continue
|
||||||
const v = fieldValues[`stimulus:${row.id}`]?.trim()
|
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}).`
|
return `Question ${n}: fill required stimulus "${row.label || row.id}" (${row.kind}).`
|
||||||
}
|
}
|
||||||
for (const row of def.response_schema) {
|
for (const row of def.response_schema) {
|
||||||
|
if (isNoInputComponentKind(row.kind)) continue
|
||||||
if (isStructuredDynamicSlotKind(row.kind)) continue
|
if (isStructuredDynamicSlotKind(row.kind)) continue
|
||||||
if (!row.required) continue
|
if (!row.required) continue
|
||||||
const v = fieldValues[`response:${row.id}`]?.trim()
|
const v = fieldValues[`response:${row.id}`]?.trim()
|
||||||
|
|
@ -427,6 +437,7 @@ export function validateDefinitionQuestion(
|
||||||
def.stimulus_schema,
|
def.stimulus_schema,
|
||||||
)
|
)
|
||||||
for (const row of def.stimulus_schema) {
|
for (const row of def.stimulus_schema) {
|
||||||
|
if (isNoInputComponentKind(row.kind)) continue
|
||||||
if (isMultipleChoiceKind(row.kind)) {
|
if (isMultipleChoiceKind(row.kind)) {
|
||||||
const val = parseMultipleChoiceSlotValue(fieldValues[`stimulus:${row.id}`])
|
const val = parseMultipleChoiceSlotValue(fieldValues[`stimulus:${row.id}`])
|
||||||
if (!multipleChoiceSlotHasContent(val)) {
|
if (!multipleChoiceSlotHasContent(val)) {
|
||||||
|
|
@ -486,6 +497,7 @@ export function validateDefinitionQuestion(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const row of def.response_schema) {
|
for (const row of def.response_schema) {
|
||||||
|
if (isNoInputComponentKind(row.kind)) continue
|
||||||
if (isMultipleChoiceKind(row.kind)) {
|
if (isMultipleChoiceKind(row.kind)) {
|
||||||
const val = parseMultipleChoiceSlotValue(fieldValues[`response:${row.id}`])
|
const val = parseMultipleChoiceSlotValue(fieldValues[`response:${row.id}`])
|
||||||
if (!multipleChoiceSlotHasContent(val)) {
|
if (!multipleChoiceSlotHasContent(val)) {
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ import {
|
||||||
normalizeMultipleChoiceValue,
|
normalizeMultipleChoiceValue,
|
||||||
parseMultipleChoiceSlotValue,
|
parseMultipleChoiceSlotValue,
|
||||||
} from "./multipleChoiceSlotValue"
|
} from "./multipleChoiceSlotValue"
|
||||||
|
import { isNoInputComponentKind } from "./questionComponentKinds"
|
||||||
|
|
||||||
/** Parse a single slot value: plain string/URL, or JSON object/array when input looks like JSON. */
|
/** Parse a single slot value: plain string/URL, or JSON object/array when input looks like JSON. */
|
||||||
export function parseDynamicSlotValue(raw: string | undefined): unknown {
|
export function parseDynamicSlotValue(raw: string | undefined): unknown {
|
||||||
|
|
@ -154,7 +155,9 @@ export function buildDynamicQuestionPayload(input: {
|
||||||
const mcqOptionsConsumed = { current: false }
|
const mcqOptionsConsumed = { current: false }
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stimulus: input.stimulusRows.map((row) => ({
|
stimulus: input.stimulusRows
|
||||||
|
.filter((row) => !isNoInputComponentKind(row.kind))
|
||||||
|
.map((row) => ({
|
||||||
id: row.id,
|
id: row.id,
|
||||||
kind: row.kind,
|
kind: row.kind,
|
||||||
value: slotValueForRow(
|
value: slotValueForRow(
|
||||||
|
|
@ -167,7 +170,9 @@ export function buildDynamicQuestionPayload(input: {
|
||||||
input.responseRows,
|
input.responseRows,
|
||||||
),
|
),
|
||||||
})),
|
})),
|
||||||
response: input.responseRows.map((row) => ({
|
response: input.responseRows
|
||||||
|
.filter((row) => !isNoInputComponentKind(row.kind))
|
||||||
|
.map((row) => ({
|
||||||
id: row.id,
|
id: row.id,
|
||||||
kind: row.kind,
|
kind: row.kind,
|
||||||
value: slotValueForRow(
|
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",
|
MATCHING_ANSWER: "Matching answer",
|
||||||
LABEL_SELECTION: "Label selection",
|
LABEL_SELECTION: "Label selection",
|
||||||
SEQUENCE_ORDER: "Sequence order",
|
SEQUENCE_ORDER: "Sequence order",
|
||||||
|
NO_INPUT: "No input",
|
||||||
}
|
}
|
||||||
|
|
||||||
export function humanizeKind(kind: string): string {
|
export function humanizeKind(kind: string): string {
|
||||||
|
|
|
||||||
|
|
@ -26,11 +26,17 @@ import {
|
||||||
validateDefinitionSchemas,
|
validateDefinitionSchemas,
|
||||||
type FieldErrorMap,
|
type FieldErrorMap,
|
||||||
} from "./lib/questionTypeDefinitionValidation"
|
} from "./lib/questionTypeDefinitionValidation"
|
||||||
|
import { defaultLabelForKind } from "../../lib/schemaSlotLabel"
|
||||||
import { QuestionTypeBasicInfoStep } from "./components/question-type-steps/QuestionTypeBasicInfoStep"
|
import { QuestionTypeBasicInfoStep } from "./components/question-type-steps/QuestionTypeBasicInfoStep"
|
||||||
import { QuestionTypeConfigStep } from "./components/question-type-steps/QuestionTypeConfigStep"
|
import { QuestionTypeConfigStep } from "./components/question-type-steps/QuestionTypeConfigStep"
|
||||||
import { QuestionTypeValidatePreviewStep } from "./components/question-type-steps/QuestionTypeValidatePreviewStep"
|
import { QuestionTypeValidatePreviewStep } from "./components/question-type-steps/QuestionTypeValidatePreviewStep"
|
||||||
import { QuestionTypeReviewPublishStep } from "./components/question-type-steps/QuestionTypeReviewPublishStep"
|
import { QuestionTypeReviewPublishStep } from "./components/question-type-steps/QuestionTypeReviewPublishStep"
|
||||||
import { defaultLabelForKind } from "../../lib/schemaSlotLabel"
|
import {
|
||||||
|
isNoInputComponentKind,
|
||||||
|
mergeCatalogWithNoInput,
|
||||||
|
noInputSchemaRow,
|
||||||
|
sideIsNoInputOnly,
|
||||||
|
} from "../../lib/questionComponentKinds"
|
||||||
|
|
||||||
const initialDraft = (): QuestionTypeDefinitionCreatePayload => ({
|
const initialDraft = (): QuestionTypeDefinitionCreatePayload => ({
|
||||||
key: "",
|
key: "",
|
||||||
|
|
@ -170,10 +176,19 @@ export function CreateQuestionTypeFlow() {
|
||||||
}, [isEdit])
|
}, [isEdit])
|
||||||
|
|
||||||
const catalogForSchemaValidation = {
|
const catalogForSchemaValidation = {
|
||||||
stimulus: new Set(componentCatalog.stimulus_component_kinds),
|
stimulus: new Set(mergeCatalogWithNoInput(componentCatalog.stimulus_component_kinds)),
|
||||||
response: new Set(componentCatalog.response_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 handleNextFromStep1 = () => {
|
||||||
const e1 = validateDefinitionBasic(draft)
|
const e1 = validateDefinitionBasic(draft)
|
||||||
setStepErrors(e1)
|
setStepErrors(e1)
|
||||||
|
|
@ -194,10 +209,26 @@ export function CreateQuestionTypeFlow() {
|
||||||
}
|
}
|
||||||
|
|
||||||
const nextDraft: QuestionTypeDefinitionCreatePayload = { ...draft }
|
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)
|
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)
|
nextDraft.response_schema = seedSchemaFromKinds(nextDraft.response_component_kinds)
|
||||||
}
|
}
|
||||||
setDraft(nextDraft)
|
setDraft(nextDraft)
|
||||||
|
|
@ -334,8 +365,8 @@ export function CreateQuestionTypeFlow() {
|
||||||
<QuestionTypeConfigStep
|
<QuestionTypeConfigStep
|
||||||
draft={draft}
|
draft={draft}
|
||||||
setDraft={setDraft}
|
setDraft={setDraft}
|
||||||
stimulusCatalogKinds={componentCatalog.stimulus_component_kinds}
|
stimulusCatalogKinds={stimulusCatalogKinds}
|
||||||
responseCatalogKinds={componentCatalog.response_component_kinds}
|
responseCatalogKinds={responseCatalogKinds}
|
||||||
catalogLoading={catalogLoading}
|
catalogLoading={catalogLoading}
|
||||||
catalogError={catalogError}
|
catalogError={catalogError}
|
||||||
errors={stepErrors}
|
errors={stepErrors}
|
||||||
|
|
|
||||||
|
|
@ -52,8 +52,6 @@ const SCOPE_OPTIONS: { value: ScopeFilter; label: string }[] = [
|
||||||
{ value: "custom", label: "Custom only" },
|
{ value: "custom", label: "Custom only" },
|
||||||
]
|
]
|
||||||
|
|
||||||
const SYSTEM_SCOPE_FETCH_LIMIT = 100
|
|
||||||
|
|
||||||
export function QuestionTypeLibraryPage() {
|
export function QuestionTypeLibraryPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [searchParams] = useSearchParams()
|
const [searchParams] = useSearchParams()
|
||||||
|
|
@ -62,7 +60,6 @@ export function QuestionTypeLibraryPage() {
|
||||||
|
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [definitions, setDefinitions] = useState<QuestionTypeDefinition[]>([])
|
const [definitions, setDefinitions] = useState<QuestionTypeDefinition[]>([])
|
||||||
const [totalCount, setTotalCount] = useState<number | undefined>(undefined)
|
|
||||||
const [query, setQuery] = useState("")
|
const [query, setQuery] = useState("")
|
||||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
|
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
|
||||||
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("all")
|
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("all")
|
||||||
|
|
@ -83,38 +80,30 @@ export function QuestionTypeLibraryPage() {
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
try {
|
try {
|
||||||
const isSystemScope = scopeFilter === "system"
|
const { definitions: rows } = await getQuestionTypeDefinitions({
|
||||||
const { definitions: rows, total_count } = await getQuestionTypeDefinitions({
|
|
||||||
include_system: scopeFilter !== "custom",
|
include_system: scopeFilter !== "custom",
|
||||||
...(statusFilter !== "All" ? { status: statusFilter } : {}),
|
...(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)
|
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) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
toast.error("Failed to load question type definitions")
|
toast.error("Failed to load question type definitions")
|
||||||
setDefinitions([])
|
setDefinitions([])
|
||||||
setTotalCount(0)
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [offset, pageSize, scopeFilter, statusFilter])
|
}, [scopeFilter, statusFilter])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load()
|
void load()
|
||||||
}, [load])
|
}, [load])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setOffset(0)
|
||||||
|
}, [query, pageSize, scopeFilter, statusFilter])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (createdId) {
|
if (createdId) {
|
||||||
toast.success("Definition created", { description: `Id ${createdId}` })
|
toast.success("Definition created", { description: `Id ${createdId}` })
|
||||||
|
|
@ -127,6 +116,8 @@ export function QuestionTypeLibraryPage() {
|
||||||
}
|
}
|
||||||
}, [updatedId])
|
}, [updatedId])
|
||||||
|
|
||||||
|
const isSystemScope = scopeFilter === "system"
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
const q = query.trim().toLowerCase()
|
const q = query.trim().toLowerCase()
|
||||||
if (!q) return definitions
|
if (!q) return definitions
|
||||||
|
|
@ -137,19 +128,17 @@ export function QuestionTypeLibraryPage() {
|
||||||
})
|
})
|
||||||
}, [definitions, query])
|
}, [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 canPrev = !isSystemScope && offset > 0
|
||||||
const canNext =
|
const canNext = !isSystemScope && offset + pageSize < totalCount
|
||||||
!isSystemScope &&
|
|
||||||
(totalCount != null ? offset + pageSize < totalCount : definitions.length === pageSize)
|
|
||||||
|
|
||||||
const pageStart = totalCount === 0 ? 0 : isSystemScope ? 1 : offset + 1
|
const pageStart = totalCount === 0 ? 0 : isSystemScope ? 1 : offset + 1
|
||||||
const pageEnd =
|
const pageEnd = isSystemScope ? filtered.length : Math.min(offset + paginated.length, totalCount)
|
||||||
isSystemScope
|
|
||||||
? filtered.length
|
|
||||||
: totalCount != null
|
|
||||||
? Math.min(offset + definitions.length, totalCount)
|
|
||||||
: offset + definitions.length
|
|
||||||
|
|
||||||
const resetPagination = () => setOffset(0)
|
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" />
|
<Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||||
<Input
|
<Input
|
||||||
className="h-11 pl-11 pr-10 rounded-[10px] border-grayScale-200 bg-white placeholder:text-grayScale-400 text-sm shadow-sm"
|
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}
|
value={query}
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -353,7 +342,7 @@ export function QuestionTypeLibraryPage() {
|
||||||
</div>
|
</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">
|
<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
|
<QuestionTypeCard
|
||||||
key={d.id}
|
key={d.id}
|
||||||
id={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 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">
|
<div className="flex flex-wrap items-center gap-3 text-xs text-grayScale-500">
|
||||||
<span>
|
<span>
|
||||||
{totalCount != null
|
{totalCount === 0
|
||||||
? `Showing ${pageStart}–${pageEnd} of ${totalCount}`
|
? "No results"
|
||||||
: `Showing ${pageStart}–${pageEnd}`}
|
: `Showing ${pageStart}–${pageEnd} of ${totalCount}`}
|
||||||
</span>
|
</span>
|
||||||
{query.trim() && filtered.length !== definitions.length ? (
|
{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">
|
<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>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
{!isSystemScope ? (
|
{!isSystemScope ? (
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,7 @@ import {
|
||||||
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
|
||||||
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
||||||
|
|
@ -250,15 +251,18 @@ export function SpeakingPage() {
|
||||||
let total = 0
|
let total = 0
|
||||||
|
|
||||||
if (selectedPracticeId) {
|
if (selectedPracticeId) {
|
||||||
const offset = (safePage - 1) * audioPageSize
|
const selectedPractice = practiceOptions.find((p) => p.id === Number(selectedPracticeId))
|
||||||
const practiceRes = await getPracticeQuestionsByPractice(Number(selectedPracticeId), {
|
const practiceId = Number(selectedPracticeId)
|
||||||
limit: audioPageSize,
|
const allRows = await fetchAllOffsetPages(async (batchOffset, limit) => {
|
||||||
offset,
|
const practiceRes = await getPracticeQuestionsByPractice(practiceId, {
|
||||||
|
limit,
|
||||||
|
offset: batchOffset,
|
||||||
question_type: "AUDIO",
|
question_type: "AUDIO",
|
||||||
})
|
})
|
||||||
const practiceData = practiceRes.data?.data
|
const practiceData = practiceRes.data?.data
|
||||||
const selectedPractice = practiceOptions.find((p) => p.id === Number(selectedPracticeId))
|
const questions = practiceData?.questions ?? []
|
||||||
rows = (practiceData?.questions ?? []).map((q) => ({
|
return {
|
||||||
|
items: questions.map((q) => ({
|
||||||
id: q.question_id || q.id,
|
id: q.question_id || q.id,
|
||||||
question_text: q.question_text,
|
question_text: q.question_text,
|
||||||
question_type: q.question_type,
|
question_type: q.question_type,
|
||||||
|
|
@ -272,9 +276,13 @@ export function SpeakingPage() {
|
||||||
status: q.question_status ?? "DRAFT",
|
status: q.question_status ?? "DRAFT",
|
||||||
created_at: "",
|
created_at: "",
|
||||||
audio_correct_answer_text: q.audio_correct_answer_text ?? undefined,
|
audio_correct_answer_text: q.audio_correct_answer_text ?? undefined,
|
||||||
practice_id: Number(selectedPracticeId),
|
practice_id: practiceId,
|
||||||
practice_title: selectedPractice?.title ?? `Practice #${selectedPracticeId}`,
|
practice_title: selectedPractice?.title ?? `Practice #${selectedPracticeId}`,
|
||||||
}))
|
})),
|
||||||
|
total_count: practiceData?.total_count,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
rows = allRows
|
||||||
const q = searchQuery.trim().toLowerCase()
|
const q = searchQuery.trim().toLowerCase()
|
||||||
if (q) {
|
if (q) {
|
||||||
rows = rows.filter((question) => {
|
rows = rows.filter((question) => {
|
||||||
|
|
@ -283,17 +291,25 @@ export function SpeakingPage() {
|
||||||
return haystack.includes(q)
|
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 {
|
} else {
|
||||||
const groupedRows = await Promise.all(
|
const groupedRows = await Promise.all(
|
||||||
practiceOptions.map(async (practice) => {
|
practiceOptions.map(async (practice) => {
|
||||||
try {
|
try {
|
||||||
|
const questions = await fetchAllOffsetPages(async (batchOffset, limit) => {
|
||||||
const res = await getPracticeQuestionsByPractice(practice.id, {
|
const res = await getPracticeQuestionsByPractice(practice.id, {
|
||||||
limit: 100,
|
limit,
|
||||||
offset: 0,
|
offset: batchOffset,
|
||||||
question_type: "AUDIO",
|
question_type: "AUDIO",
|
||||||
})
|
})
|
||||||
const questions = res.data?.data?.questions ?? []
|
const data = res.data?.data
|
||||||
|
return {
|
||||||
|
items: data?.questions ?? [],
|
||||||
|
total_count: data?.total_count,
|
||||||
|
}
|
||||||
|
})
|
||||||
return questions.map((q) => ({
|
return questions.map((q) => ({
|
||||||
id: q.question_id || q.id,
|
id: q.question_id || q.id,
|
||||||
question_text: q.question_text,
|
question_text: q.question_text,
|
||||||
|
|
|
||||||
|
|
@ -17,8 +17,9 @@ export function DefinitionRuntimeHint({
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">May not be publishable</p>
|
<p className="font-semibold">May not be publishable</p>
|
||||||
<p className="mt-0.5 text-amber-800/90">
|
<p className="mt-0.5 text-amber-800/90">
|
||||||
The server requires a mappable runtime question type. Add at least one non-timer response
|
The server requires a mappable runtime question type. Add at least one non-timer
|
||||||
kind (e.g. OPTION, TEXT_INPUT). Timer-only definitions are rejected.
|
response kind (e.g. OPTION, TEXT_INPUT), or use No input only when the definition is
|
||||||
|
intentionally display-only.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,10 @@ import {
|
||||||
getResponseKindPresentation,
|
getResponseKindPresentation,
|
||||||
getStimulusKindPresentation,
|
getStimulusKindPresentation,
|
||||||
} from "./componentKindUi"
|
} from "./componentKindUi"
|
||||||
|
import {
|
||||||
|
isNoInputComponentKind,
|
||||||
|
noInputSchemaRow,
|
||||||
|
} from "../../../../lib/questionComponentKinds"
|
||||||
|
|
||||||
interface QuestionTypeConfigStepProps {
|
interface QuestionTypeConfigStepProps {
|
||||||
draft: QuestionTypeDefinitionCreatePayload
|
draft: QuestionTypeDefinitionCreatePayload
|
||||||
|
|
@ -29,10 +33,6 @@ interface QuestionTypeConfigStepProps {
|
||||||
onBack: () => void
|
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 {
|
function slugFragmentFromKind(kind: string): string {
|
||||||
const s = (kind || "field").toLowerCase().replace(/[^a-z0-9]+/g, "_")
|
const s = (kind || "field").toLowerCase().replace(/[^a-z0-9]+/g, "_")
|
||||||
return s.replace(/^_|_$/g, "") || "field"
|
return s.replace(/^_|_$/g, "") || "field"
|
||||||
|
|
@ -93,10 +93,26 @@ export function QuestionTypeConfigStep({
|
||||||
|
|
||||||
const handleStimulusKindClick = (kind: string) => {
|
const handleStimulusKindClick = (kind: string) => {
|
||||||
setDraft((d) => {
|
setDraft((d) => {
|
||||||
|
if (isNoInputComponentKind(kind)) {
|
||||||
const wasSelected = d.stimulus_component_kinds.includes(kind)
|
const wasSelected = d.stimulus_component_kinds.includes(kind)
|
||||||
const stimulus_component_kinds = toggleKind(d.stimulus_component_kinds, 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 baseKinds = d.stimulus_component_kinds.filter((k) => !isNoInputComponentKind(k))
|
||||||
|
const stimulus_component_kinds = wasSelected
|
||||||
|
? baseKinds.filter((k) => k !== kind)
|
||||||
|
: [...baseKinds, kind]
|
||||||
|
|
||||||
if (!wasSelected) {
|
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)) {
|
if (!stimulus_schema.some((r) => r.kind === kind)) {
|
||||||
stimulus_schema.push({
|
stimulus_schema.push({
|
||||||
id: nextUniqueSchemaElementId(stimulus_schema, kind),
|
id: nextUniqueSchemaElementId(stimulus_schema, kind),
|
||||||
|
|
@ -117,10 +133,26 @@ export function QuestionTypeConfigStep({
|
||||||
|
|
||||||
const handleResponseKindClick = (kind: string) => {
|
const handleResponseKindClick = (kind: string) => {
|
||||||
setDraft((d) => {
|
setDraft((d) => {
|
||||||
|
if (isNoInputComponentKind(kind)) {
|
||||||
const wasSelected = d.response_component_kinds.includes(kind)
|
const wasSelected = d.response_component_kinds.includes(kind)
|
||||||
const response_component_kinds = toggleKind(d.response_component_kinds, 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 baseKinds = d.response_component_kinds.filter((k) => !isNoInputComponentKind(k))
|
||||||
|
const response_component_kinds = wasSelected
|
||||||
|
? baseKinds.filter((k) => k !== kind)
|
||||||
|
: [...baseKinds, kind]
|
||||||
|
|
||||||
if (!wasSelected) {
|
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)) {
|
if (!response_schema.some((r) => r.kind === kind)) {
|
||||||
response_schema.push({
|
response_schema.push({
|
||||||
id: nextUniqueSchemaElementId(response_schema, kind),
|
id: nextUniqueSchemaElementId(response_schema, kind),
|
||||||
|
|
@ -246,7 +278,7 @@ export function QuestionTypeConfigStep({
|
||||||
selected={selected}
|
selected={selected}
|
||||||
onClick={() => handleStimulusKindClick(kind)}
|
onClick={() => handleStimulusKindClick(kind)}
|
||||||
/>
|
/>
|
||||||
{selected ? (
|
{selected && !isNoInputComponentKind(kind) ? (
|
||||||
<div className="flex items-center justify-between gap-2 px-0.5 min-h-[32px]">
|
<div className="flex items-center justify-between gap-2 px-0.5 min-h-[32px]">
|
||||||
<span className="text-[12px] text-grayScale-500 font-medium">
|
<span className="text-[12px] text-grayScale-500 font-medium">
|
||||||
{slotCount} slot{slotCount === 1 ? "" : "s"}
|
{slotCount} slot{slotCount === 1 ? "" : "s"}
|
||||||
|
|
@ -310,7 +342,7 @@ export function QuestionTypeConfigStep({
|
||||||
selected={selected}
|
selected={selected}
|
||||||
onClick={() => handleResponseKindClick(kind)}
|
onClick={() => handleResponseKindClick(kind)}
|
||||||
/>
|
/>
|
||||||
{selected ? (
|
{selected && !isNoInputComponentKind(kind) ? (
|
||||||
<div className="flex items-center justify-between gap-2 px-0.5 min-h-[32px]">
|
<div className="flex items-center justify-between gap-2 px-0.5 min-h-[32px]">
|
||||||
<span className="text-[12px] text-grayScale-500 font-medium">
|
<span className="text-[12px] text-grayScale-500 font-medium">
|
||||||
{slotCount} slot{slotCount === 1 ? "" : "s"}
|
{slotCount} slot{slotCount === 1 ? "" : "s"}
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ import {
|
||||||
buildValidateKindsPayload,
|
buildValidateKindsPayload,
|
||||||
inferRuntimeQuestionType,
|
inferRuntimeQuestionType,
|
||||||
} from "../../lib/questionTypeDefinitionValidation"
|
} from "../../lib/questionTypeDefinitionValidation"
|
||||||
import { DefinitionRuntimeHint } from "./DefinitionRuntimeHint"
|
|
||||||
import { slotLabel } from "./componentKindUi"
|
import { slotLabel } from "./componentKindUi"
|
||||||
|
|
||||||
interface QuestionTypeReviewPublishStepProps {
|
interface QuestionTypeReviewPublishStepProps {
|
||||||
|
|
@ -41,13 +40,6 @@ export function QuestionTypeReviewPublishStep({
|
||||||
const runtime = inferRuntimeQuestionType(payload.key, payload.response_component_kinds)
|
const runtime = inferRuntimeQuestionType(payload.key, payload.response_component_kinds)
|
||||||
|
|
||||||
const submit = async (status: "ACTIVE" | "INACTIVE") => {
|
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 }
|
const body = { ...payload, status }
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -112,11 +104,6 @@ export function QuestionTypeReviewPublishStep({
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<DefinitionRuntimeHint
|
|
||||||
definitionKey={payload.key}
|
|
||||||
responseKinds={payload.response_component_kinds}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
|
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Key</dt>
|
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Key</dt>
|
||||||
|
|
@ -136,7 +123,7 @@ export function QuestionTypeReviewPublishStep({
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Runtime type</dt>
|
<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>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Stimulus kinds</dt>
|
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Stimulus kinds</dt>
|
||||||
|
|
@ -158,7 +145,7 @@ export function QuestionTypeReviewPublishStep({
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="h-11"
|
className="h-11"
|
||||||
disabled={submitting || runtime == null}
|
disabled={submitting}
|
||||||
onClick={() => void submit("INACTIVE")}
|
onClick={() => void submit("INACTIVE")}
|
||||||
>
|
>
|
||||||
{submitting ? (
|
{submitting ? (
|
||||||
|
|
@ -172,7 +159,7 @@ export function QuestionTypeReviewPublishStep({
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
className="h-11 bg-[#9E2891] hover:bg-[#8A237E] text-white"
|
className="h-11 bg-[#9E2891] hover:bg-[#8A237E] text-white"
|
||||||
disabled={submitting || runtime == null}
|
disabled={submitting}
|
||||||
onClick={() => void submit("ACTIVE")}
|
onClick={() => void submit("ACTIVE")}
|
||||||
>
|
>
|
||||||
{submitting ? (
|
{submitting ? (
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import {
|
||||||
getResponseKindPresentation,
|
getResponseKindPresentation,
|
||||||
getStimulusKindPresentation,
|
getStimulusKindPresentation,
|
||||||
} from "./componentKindUi"
|
} from "./componentKindUi"
|
||||||
|
import { isNoInputComponentKind } from "../../../../lib/questionComponentKinds"
|
||||||
|
|
||||||
type Side = "stimulus" | "response"
|
type Side = "stimulus" | "response"
|
||||||
|
|
||||||
|
|
@ -119,7 +120,9 @@ export function SchemaBuilderSection({
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{rows.map((row, index) => (
|
{rows.map((row, index) => {
|
||||||
|
const noInput = isNoInputComponentKind(row.kind)
|
||||||
|
return (
|
||||||
<div
|
<div
|
||||||
key={`${side}-${index}`}
|
key={`${side}-${index}`}
|
||||||
className="rounded-xl border border-grayScale-200 bg-[#F8FAFC] p-4 space-y-3"
|
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"
|
className="h-8 w-8 p-0 text-grayScale-500 hover:text-red-600"
|
||||||
onClick={() => removeRow(index)}
|
onClick={() => removeRow(index)}
|
||||||
aria-label="Remove row"
|
aria-label="Remove row"
|
||||||
|
disabled={noInput}
|
||||||
>
|
>
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -170,6 +174,13 @@ export function SchemaBuilderSection({
|
||||||
</div>
|
</div>
|
||||||
</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="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-[12px] font-semibold text-grayScale-600">
|
<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>
|
<p className="text-[11px] text-grayScale-400">Tab out of the field to apply JSON config.</p>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{rowErrors?.[index] ? <p className="text-sm text-red-600">{rowErrors[index]}</p> : null}
|
{rowErrors?.[index] ? <p className="text-sm text-red-600">{rowErrors[index]}</p> : null}
|
||||||
</div>
|
</div>
|
||||||
))}
|
)})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import {
|
||||||
getResponseKindPresentation,
|
getResponseKindPresentation,
|
||||||
getStimulusKindPresentation,
|
getStimulusKindPresentation,
|
||||||
} from "./componentKindUi"
|
} from "./componentKindUi"
|
||||||
|
import { isNoInputComponentKind } from "../../../../lib/questionComponentKinds"
|
||||||
|
|
||||||
interface SchemaSlotLabelsPanelProps {
|
interface SchemaSlotLabelsPanelProps {
|
||||||
stimulusRows: DynamicElementDefinition[]
|
stimulusRows: DynamicElementDefinition[]
|
||||||
|
|
@ -71,11 +72,18 @@ function SlotLabelGroup({
|
||||||
className="h-8 w-8 shrink-0 p-0 text-grayScale-500 hover:text-red-600"
|
className="h-8 w-8 shrink-0 p-0 text-grayScale-500 hover:text-red-600"
|
||||||
onClick={() => onChange(removeRow(rows, index))}
|
onClick={() => onChange(removeRow(rows, index))}
|
||||||
aria-label={`Remove ${presentation.label} slot`}
|
aria-label={`Remove ${presentation.label} slot`}
|
||||||
|
disabled={isNoInputComponentKind(row.kind)}
|
||||||
>
|
>
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
|
{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">
|
<label className="text-[12px] font-semibold text-grayScale-600">
|
||||||
Field label <span className="text-red-500">*</span>
|
Field label <span className="text-red-500">*</span>
|
||||||
</label>
|
</label>
|
||||||
|
|
@ -88,6 +96,8 @@ function SlotLabelGroup({
|
||||||
<p className="text-[11px] text-grayScale-400">
|
<p className="text-[11px] text-grayScale-400">
|
||||||
Shown to authors when they create questions from this type.
|
Shown to authors when they create questions from this type.
|
||||||
</p>
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{rowError ? <p className="text-sm text-red-600">{rowError}</p> : null}
|
{rowError ? <p className="text-sm text-red-600">{rowError}</p> : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import {
|
||||||
ListOrdered,
|
ListOrdered,
|
||||||
ListTodo,
|
ListTodo,
|
||||||
Mic2,
|
Mic2,
|
||||||
|
Minus,
|
||||||
MousePointer2,
|
MousePointer2,
|
||||||
Table as TableIcon,
|
Table as TableIcon,
|
||||||
Type,
|
Type,
|
||||||
|
|
@ -35,6 +36,7 @@ const STIMULUS_LABELS: Record<string, string> = {
|
||||||
SELECT_MISSING_WORDS: defaultLabelForKind("SELECT_MISSING_WORDS"),
|
SELECT_MISSING_WORDS: defaultLabelForKind("SELECT_MISSING_WORDS"),
|
||||||
TABLE: defaultLabelForKind("TABLE"),
|
TABLE: defaultLabelForKind("TABLE"),
|
||||||
PDF_ATTACHMENT: defaultLabelForKind("PDF_ATTACHMENT"),
|
PDF_ATTACHMENT: defaultLabelForKind("PDF_ATTACHMENT"),
|
||||||
|
NO_INPUT: defaultLabelForKind("NO_INPUT"),
|
||||||
}
|
}
|
||||||
|
|
||||||
const RESPONSE_LABELS: Record<string, string> = {
|
const RESPONSE_LABELS: Record<string, string> = {
|
||||||
|
|
@ -49,6 +51,7 @@ const RESPONSE_LABELS: Record<string, string> = {
|
||||||
MATCHING_ANSWER: defaultLabelForKind("MATCHING_ANSWER"),
|
MATCHING_ANSWER: defaultLabelForKind("MATCHING_ANSWER"),
|
||||||
LABEL_SELECTION: defaultLabelForKind("LABEL_SELECTION"),
|
LABEL_SELECTION: defaultLabelForKind("LABEL_SELECTION"),
|
||||||
SEQUENCE_ORDER: defaultLabelForKind("SEQUENCE_ORDER"),
|
SEQUENCE_ORDER: defaultLabelForKind("SEQUENCE_ORDER"),
|
||||||
|
NO_INPUT: defaultLabelForKind("NO_INPUT"),
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Legacy screenshot labels → map to closest API kind for display only (same code path). */
|
/** 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,
|
SELECT_MISSING_WORDS: ListTodo,
|
||||||
TABLE: TableIcon,
|
TABLE: TableIcon,
|
||||||
PDF_ATTACHMENT: FileUp,
|
PDF_ATTACHMENT: FileUp,
|
||||||
|
NO_INPUT: Minus,
|
||||||
}
|
}
|
||||||
|
|
||||||
const RESPONSE_ICONS: Record<string, LucideIcon> = {
|
const RESPONSE_ICONS: Record<string, LucideIcon> = {
|
||||||
|
|
@ -78,6 +82,7 @@ const RESPONSE_ICONS: Record<string, LucideIcon> = {
|
||||||
MATCHING_ANSWER: GitCompare,
|
MATCHING_ANSWER: GitCompare,
|
||||||
LABEL_SELECTION: MousePointer2,
|
LABEL_SELECTION: MousePointer2,
|
||||||
SEQUENCE_ORDER: ListOrdered,
|
SEQUENCE_ORDER: ListOrdered,
|
||||||
|
NO_INPUT: Minus,
|
||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_ICON = FileText
|
const DEFAULT_ICON = FileText
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,12 @@ import type {
|
||||||
QuestionTypeDefinitionCreatePayload,
|
QuestionTypeDefinitionCreatePayload,
|
||||||
} from "../../../types/questionTypeDefinition.types"
|
} from "../../../types/questionTypeDefinition.types"
|
||||||
import { defaultLabelForKind } from "../../../lib/schemaSlotLabel"
|
import { defaultLabelForKind } from "../../../lib/schemaSlotLabel"
|
||||||
|
import {
|
||||||
|
effectiveComponentKinds,
|
||||||
|
isNoInputComponentKind,
|
||||||
|
sideIsNoInputOnly,
|
||||||
|
noInputSchemaRow,
|
||||||
|
} from "../../../lib/questionComponentKinds"
|
||||||
|
|
||||||
export type FieldErrorMap = Record<string, string>
|
export type FieldErrorMap = Record<string, string>
|
||||||
|
|
||||||
|
|
@ -32,13 +38,24 @@ export function validateDefinitionKinds(
|
||||||
const errors: FieldErrorMap = {}
|
const errors: FieldErrorMap = {}
|
||||||
const { stimulus_component_kinds: sk, response_component_kinds: rk } = payload
|
const { stimulus_component_kinds: sk, response_component_kinds: rk } = payload
|
||||||
|
|
||||||
if (!sk.length) errors.stimulus_kinds = "Select at least one stimulus component kind."
|
if (sk.length === 0 && rk.length === 0) {
|
||||||
if (!rk.length) errors.response_kinds = "Select at least one response component kind."
|
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 (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 && !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."
|
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 sCat = new Set(catalog.stimulus_component_kinds)
|
||||||
const rCat = new Set(catalog.response_component_kinds)
|
const rCat = new Set(catalog.response_component_kinds)
|
||||||
if (sCat.size > 0 && sk.length) {
|
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) {
|
if (invalid.length) {
|
||||||
const msg = `Not in stimulus catalog: ${invalid.join(", ")}.`
|
const msg = `Not in stimulus catalog: ${invalid.join(", ")}.`
|
||||||
errors.stimulus_kinds = errors.stimulus_kinds ? `${errors.stimulus_kinds} ${msg}` : msg
|
errors.stimulus_kinds = errors.stimulus_kinds ? `${errors.stimulus_kinds} ${msg}` : msg
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (rCat.size > 0 && rk.length) {
|
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) {
|
if (invalid.length) {
|
||||||
const msg = `Not in response catalog: ${invalid.join(", ")}.`
|
const msg = `Not in response catalog: ${invalid.join(", ")}.`
|
||||||
errors.response_kinds = errors.response_kinds ? `${errors.response_kinds} ${msg}` : msg
|
errors.response_kinds = errors.response_kinds ? `${errors.response_kinds} ${msg}` : msg
|
||||||
|
|
@ -91,8 +108,28 @@ export function validateDefinitionSchemas(
|
||||||
side: "stimulus" | "response",
|
side: "stimulus" | "response",
|
||||||
) => {
|
) => {
|
||||||
const prefix = side
|
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) {
|
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
|
return
|
||||||
}
|
}
|
||||||
idsUniqueAndNonEmpty(rows, prefix, errors)
|
idsUniqueAndNonEmpty(rows, prefix, errors)
|
||||||
|
|
@ -101,14 +138,17 @@ export function validateDefinitionSchemas(
|
||||||
const catalogSet = side === "stimulus" ? catalog.stimulus : catalog.response
|
const catalogSet = side === "stimulus" ? catalog.stimulus : catalog.response
|
||||||
rows.forEach((row, i) => {
|
rows.forEach((row, i) => {
|
||||||
const rowMessages: string[] = []
|
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.")
|
if (!row.kind) rowMessages.push("Kind is required.")
|
||||||
else if (allowedSet.size && !allowedSet.has(row.kind)) {
|
else if (allowedSet.size && !allowedSet.has(row.kind)) {
|
||||||
rowMessages.push(`Kind "${row.kind}" is not in selected ${side} kinds.`)
|
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.`)
|
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.")
|
rowMessages.push("Label is required — this is the field title authors see when creating questions.")
|
||||||
}
|
}
|
||||||
if (rowMessages.length) errors[`${prefix}_${i}`] = rowMessages.join(" ")
|
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))
|
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([
|
const SHORT_ANSWER_RESPONSE_KINDS = new Set([
|
||||||
"SHORT_ANSWER",
|
"SHORT_ANSWER",
|
||||||
"TEXT_INPUT",
|
"TEXT_INPUT",
|
||||||
|
|
@ -183,24 +223,43 @@ export function buildValidateKindsPayload(
|
||||||
export function buildCreatePayload(
|
export function buildCreatePayload(
|
||||||
draft: QuestionTypeDefinitionCreatePayload,
|
draft: QuestionTypeDefinitionCreatePayload,
|
||||||
): 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,
|
...r,
|
||||||
id: r.id.trim(),
|
id: r.id.trim(),
|
||||||
kind: r.kind.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,
|
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,
|
...r,
|
||||||
id: r.id.trim(),
|
id: r.id.trim(),
|
||||||
kind: r.kind.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,
|
config: r.config && Object.keys(r.config).length ? r.config : undefined,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const stimulusKindsFromSchema = uniqueKindsFromSchemaRows(stimulus_schema)
|
const stimulusKindsFromSchema = uniqueKindsFromSchemaRows(stimulus_schema)
|
||||||
const responseKindsFromSchema = uniqueKindsFromSchemaRows(response_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 {
|
return {
|
||||||
...draft,
|
...draft,
|
||||||
key: draft.key.trim(),
|
key: draft.key.trim(),
|
||||||
|
|
@ -210,7 +269,7 @@ export function buildCreatePayload(
|
||||||
stimulusKindsFromSchema.length > 0 ? stimulusKindsFromSchema : [...draft.stimulus_component_kinds],
|
stimulusKindsFromSchema.length > 0 ? stimulusKindsFromSchema : [...draft.stimulus_component_kinds],
|
||||||
response_component_kinds:
|
response_component_kinds:
|
||||||
responseKindsFromSchema.length > 0 ? responseKindsFromSchema : [...draft.response_component_kinds],
|
responseKindsFromSchema.length > 0 ? responseKindsFromSchema : [...draft.response_component_kinds],
|
||||||
stimulus_schema,
|
stimulus_schema: finalStimulusSchema,
|
||||||
response_schema,
|
response_schema: finalResponseSchema,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ import {
|
||||||
} from "../../lib/faqDisplay"
|
} from "../../lib/faqDisplay"
|
||||||
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
|
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import type { FAQ, FAQStatus } from "../../types/faq.types"
|
import type { FAQ, FAQStatus } from "../../types/faq.types"
|
||||||
|
|
@ -57,7 +58,6 @@ export function FaqsPage() {
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const [permissionDenied, setPermissionDenied] = useState(false)
|
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||||
const [faqs, setFaqs] = useState<FAQ[]>([])
|
const [faqs, setFaqs] = useState<FAQ[]>([])
|
||||||
const [totalCount, setTotalCount] = useState(0)
|
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
const [query, setQuery] = useState("")
|
const [query, setQuery] = useState("")
|
||||||
|
|
@ -70,8 +70,6 @@ export function FaqsPage() {
|
||||||
const [createOpen, setCreateOpen] = useState(false)
|
const [createOpen, setCreateOpen] = useState(false)
|
||||||
const [suggestedDisplayOrder, setSuggestedDisplayOrder] = useState(1)
|
const [suggestedDisplayOrder, setSuggestedDisplayOrder] = useState(1)
|
||||||
|
|
||||||
const offset = (page - 1) * pageSize
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
if (!canList) {
|
if (!canList) {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|
@ -82,14 +80,19 @@ export function FaqsPage() {
|
||||||
setError(false)
|
setError(false)
|
||||||
setPermissionDenied(false)
|
setPermissionDenied(false)
|
||||||
try {
|
try {
|
||||||
|
const allFaqs = await fetchAllOffsetPages(async (batchOffset, limit) => {
|
||||||
const res = await getFAQs({
|
const res = await getFAQs({
|
||||||
status: statusFilter === "all" ? undefined : statusFilter,
|
status: statusFilter === "all" ? undefined : statusFilter,
|
||||||
category: categoryFilter || undefined,
|
category: categoryFilter || undefined,
|
||||||
limit: pageSize,
|
limit,
|
||||||
offset,
|
offset: batchOffset,
|
||||||
})
|
})
|
||||||
setFaqs(res.data.faqs)
|
return {
|
||||||
setTotalCount(res.data.total_count)
|
items: res.data.faqs,
|
||||||
|
total_count: res.data.total_count,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
setFaqs(allFaqs)
|
||||||
|
|
||||||
const categoryRes = await getFAQs({ limit: 200, offset: 0 })
|
const categoryRes = await getFAQs({ limit: 200, offset: 0 })
|
||||||
setAllCategories(deriveFaqCategories(categoryRes.data.faqs))
|
setAllCategories(deriveFaqCategories(categoryRes.data.faqs))
|
||||||
|
|
@ -98,7 +101,6 @@ export function FaqsPage() {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
setError(true)
|
setError(true)
|
||||||
setFaqs([])
|
setFaqs([])
|
||||||
setTotalCount(0)
|
|
||||||
if (isFaqForbiddenError(e)) {
|
if (isFaqForbiddenError(e)) {
|
||||||
setPermissionDenied(true)
|
setPermissionDenied(true)
|
||||||
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view FAQs"))
|
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view FAQs"))
|
||||||
|
|
@ -108,7 +110,7 @@ export function FaqsPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [canList, statusFilter, categoryFilter, pageSize, offset])
|
}, [canList, statusFilter, categoryFilter])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load()
|
void load()
|
||||||
|
|
@ -116,7 +118,7 @@ export function FaqsPage() {
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}, [statusFilter, categoryFilter, pageSize])
|
}, [statusFilter, categoryFilter, pageSize, query])
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
const q = query.trim().toLowerCase()
|
const q = query.trim().toLowerCase()
|
||||||
|
|
@ -129,9 +131,12 @@ export function FaqsPage() {
|
||||||
})
|
})
|
||||||
}, [faqs, query])
|
}, [faqs, query])
|
||||||
|
|
||||||
|
const totalCount = filtered.length
|
||||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||||
const pageStart = totalCount === 0 ? 0 : offset + 1
|
const safePage = Math.min(page, totalPages)
|
||||||
const pageEnd = Math.min(offset + faqs.length, totalCount)
|
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 canPrev = page > 1
|
||||||
const canNext = page < totalPages
|
const canNext = page < totalPages
|
||||||
|
|
||||||
|
|
@ -222,7 +227,7 @@ export function FaqsPage() {
|
||||||
summary={
|
summary={
|
||||||
loading
|
loading
|
||||||
? "Loading…"
|
? "Loading…"
|
||||||
: `${filtered.length} shown on page · ${totalCount} total`
|
: `${totalCount} shown · ${faqs.length} loaded`
|
||||||
}
|
}
|
||||||
search={
|
search={
|
||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
|
|
@ -323,7 +328,7 @@ export function FaqsPage() {
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{filtered.map((faq) => (
|
{paginated.map((faq) => (
|
||||||
<TableRow key={faq.id}>
|
<TableRow key={faq.id}>
|
||||||
<TableCell className="max-w-xs">
|
<TableCell className="max-w-xs">
|
||||||
<p className="line-clamp-2 font-medium text-grayScale-900">
|
<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 { Button } from "../../components/ui/button";
|
||||||
import { Input } from "../../components/ui/input";
|
import { Input } from "../../components/ui/input";
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages";
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
|
|
@ -51,7 +52,7 @@ import {
|
||||||
deleteIssue,
|
deleteIssue,
|
||||||
createIssue,
|
createIssue,
|
||||||
} from "../../api/issues.api";
|
} from "../../api/issues.api";
|
||||||
import type { Issue, IssueFilters } from "../../types/issue.types";
|
import type { Issue } from "../../types/issue.types";
|
||||||
|
|
||||||
// ── Status configuration ───────────────────────────────────────────
|
// ── Status configuration ───────────────────────────────────────────
|
||||||
const STATUSES = ["pending", "in_progress", "resolved", "closed"] as const;
|
const STATUSES = ["pending", "in_progress", "resolved", "closed"] as const;
|
||||||
|
|
@ -188,7 +189,6 @@ function formatRoleLabel(role: string | null | undefined): string {
|
||||||
// ── Main Component ─────────────────────────────────────────────────
|
// ── Main Component ─────────────────────────────────────────────────
|
||||||
export function IssuesPage() {
|
export function IssuesPage() {
|
||||||
const [issues, setIssues] = useState<Issue[]>([]);
|
const [issues, setIssues] = useState<Issue[]>([]);
|
||||||
const [totalCount, setTotalCount] = useState(0);
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
|
@ -221,27 +221,31 @@ export function IssuesPage() {
|
||||||
const fetchIssues = useCallback(async () => {
|
const fetchIssues = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const filters: IssueFilters = {
|
const allIssues = await fetchAllOffsetPages(async (offset, limit) => {
|
||||||
limit: pageSize,
|
const res = await getIssues({ limit, offset });
|
||||||
offset: (page - 1) * pageSize,
|
|
||||||
};
|
|
||||||
const res = await getIssues(filters);
|
|
||||||
const payload = res.data?.data;
|
const payload = res.data?.data;
|
||||||
setIssues(Array.isArray(payload?.issues) ? payload.issues : []);
|
return {
|
||||||
setTotalCount(typeof payload?.total_count === "number" ? payload.total_count : 0);
|
items: Array.isArray(payload?.issues) ? payload.issues : [],
|
||||||
|
total_count: typeof payload?.total_count === "number" ? payload.total_count : undefined,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
setIssues(allIssues);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch issues:", error);
|
console.error("Failed to fetch issues:", error);
|
||||||
setIssues([]);
|
setIssues([]);
|
||||||
setTotalCount(0);
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [page, pageSize]);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchIssues();
|
fetchIssues();
|
||||||
}, [fetchIssues]);
|
}, [fetchIssues]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1);
|
||||||
|
}, [searchQuery, statusFilter, typeFilter, pageSize]);
|
||||||
|
|
||||||
const handleViewDetail = async (issueId: number) => {
|
const handleViewDetail = async (issueId: number) => {
|
||||||
setDialogOpen(true);
|
setDialogOpen(true);
|
||||||
setDetailLoading(true);
|
setDetailLoading(true);
|
||||||
|
|
@ -326,9 +330,12 @@ export function IssuesPage() {
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const totalCount = filteredIssues.length;
|
||||||
|
|
||||||
// Pagination
|
// Pagination
|
||||||
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
||||||
const safePage = Math.min(page, pageCount);
|
const safePage = Math.min(page, pageCount);
|
||||||
|
const paginatedIssues = filteredIssues.slice((safePage - 1) * pageSize, safePage * pageSize);
|
||||||
const handlePrev = () => safePage > 1 && setPage(safePage - 1);
|
const handlePrev = () => safePage > 1 && setPage(safePage - 1);
|
||||||
const handleNext = () => safePage < pageCount && setPage(safePage + 1);
|
const handleNext = () => safePage < pageCount && setPage(safePage + 1);
|
||||||
|
|
||||||
|
|
@ -528,7 +535,7 @@ export function IssuesPage() {
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : (
|
) : (
|
||||||
filteredIssues.map((issue) => {
|
paginatedIssues.map((issue) => {
|
||||||
const typeConfig = getIssueTypeConfig(issue.issue_type);
|
const typeConfig = getIssueTypeConfig(issue.issue_type);
|
||||||
const statusConfig = getStatusConfig(issue.status);
|
const statusConfig = getStatusConfig(issue.status);
|
||||||
const TypeIcon = typeConfig.icon;
|
const TypeIcon = typeConfig.icon;
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import {
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "../../components/ui/dropdown-menu"
|
} from "../../components/ui/dropdown-menu"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
|
|
@ -174,7 +175,7 @@ function NotificationItem({
|
||||||
export function NotificationsPage() {
|
export function NotificationsPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [notifications, setNotifications] = useState<Notification[]>([])
|
const [notifications, setNotifications] = useState<Notification[]>([])
|
||||||
const [totalCount, setTotalCount] = useState(0)
|
const [allCount, setAllCount] = useState(0)
|
||||||
const [globalUnread, setGlobalUnread] = useState(0)
|
const [globalUnread, setGlobalUnread] = useState(0)
|
||||||
const [offset, setOffset] = useState(0)
|
const [offset, setOffset] = useState(0)
|
||||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
|
|
@ -195,27 +196,37 @@ export function NotificationsPage() {
|
||||||
const [typeFilter, setTypeFilter] = useState<"all" | string>("all")
|
const [typeFilter, setTypeFilter] = useState<"all" | string>("all")
|
||||||
const [levelFilter, setLevelFilter] = useState<"all" | string>("all")
|
const [levelFilter, setLevelFilter] = useState<"all" | string>("all")
|
||||||
|
|
||||||
const fetchData = useCallback(async (currentOffset: number) => {
|
const fetchData = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError(false)
|
setError(false)
|
||||||
try {
|
try {
|
||||||
const [notifRes, unreadRes] = await Promise.all([
|
const [allNotifications, unreadRes] = await Promise.all([
|
||||||
getNotifications(pageSize, currentOffset),
|
fetchAllOffsetPages(async (batchOffset, limit) => {
|
||||||
|
const notifRes = await getNotifications(limit, batchOffset)
|
||||||
|
return {
|
||||||
|
items: notifRes.data.notifications ?? [],
|
||||||
|
total_count: notifRes.data.total_count,
|
||||||
|
}
|
||||||
|
}),
|
||||||
getUnreadCount(),
|
getUnreadCount(),
|
||||||
])
|
])
|
||||||
setNotifications(notifRes.data.notifications ?? [])
|
setNotifications(allNotifications)
|
||||||
setTotalCount(notifRes.data.total_count)
|
setAllCount(allNotifications.length)
|
||||||
setGlobalUnread(unreadRes.data.unread)
|
setGlobalUnread(unreadRes.data.unread)
|
||||||
} catch {
|
} catch {
|
||||||
setError(true)
|
setError(true)
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [pageSize])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData(offset)
|
void fetchData()
|
||||||
}, [offset, pageSize, fetchData])
|
}, [fetchData])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setOffset(0)
|
||||||
|
}, [searchTerm, channelFilter, activeStatusTab, typeFilter, levelFilter, pageSize])
|
||||||
|
|
||||||
const handleToggleRead = useCallback(async (id: string, currentlyRead: boolean) => {
|
const handleToggleRead = useCallback(async (id: string, currentlyRead: boolean) => {
|
||||||
setTogglingIds((prev) => new Set(prev).add(id))
|
setTogglingIds((prev) => new Set(prev).add(id))
|
||||||
|
|
@ -258,32 +269,13 @@ export function NotificationsPage() {
|
||||||
try {
|
try {
|
||||||
await markAllUnread()
|
await markAllUnread()
|
||||||
setNotifications((prev) => prev.map((n) => ({ ...n, is_read: false })))
|
setNotifications((prev) => prev.map((n) => ({ ...n, is_read: false })))
|
||||||
setGlobalUnread(totalCount)
|
setGlobalUnread(allCount)
|
||||||
} catch {
|
} catch {
|
||||||
// silently fail
|
// silently fail
|
||||||
} finally {
|
} finally {
|
||||||
setBulkLoading(false)
|
setBulkLoading(false)
|
||||||
}
|
}
|
||||||
}, [totalCount])
|
}, [allCount])
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
const filteredNotifications = notifications.filter((n) => {
|
const filteredNotifications = notifications.filter((n) => {
|
||||||
if (channelFilter !== "all" && n.delivery_channel !== channelFilter) return false
|
if (channelFilter !== "all" && n.delivery_channel !== channelFilter) return false
|
||||||
|
|
@ -308,6 +300,27 @@ export function NotificationsPage() {
|
||||||
return true
|
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([
|
const activeFilterCount = countActiveFilters([
|
||||||
{ value: activeStatusTab, defaultValue: "all" },
|
{ value: activeStatusTab, defaultValue: "all" },
|
||||||
{ value: channelFilter, defaultValue: "all" },
|
{ value: channelFilter, defaultValue: "all" },
|
||||||
|
|
@ -524,7 +537,7 @@ export function NotificationsPage() {
|
||||||
className="mb-3"
|
className="mb-3"
|
||||||
activeFilterCount={activeFilterCount}
|
activeFilterCount={activeFilterCount}
|
||||||
onClearFilters={clearFilters}
|
onClearFilters={clearFilters}
|
||||||
summary={`${filteredNotifications.length} shown · ${totalCount} total`}
|
summary={`${totalCount} shown · ${allCount} total`}
|
||||||
search={
|
search={
|
||||||
<div className="relative w-full">
|
<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" />
|
<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>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : (
|
) : (
|
||||||
filteredNotifications.map((n) => {
|
paginatedNotifications.map((n) => {
|
||||||
const config = NOTIFICATION_TYPE_CONFIG[n.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
const config = NOTIFICATION_TYPE_CONFIG[n.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
||||||
const Icon = config.icon
|
const Icon = config.icon
|
||||||
const isToggling = togglingIds.has(n.id)
|
const isToggling = togglingIds.has(n.id)
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import {
|
||||||
} from "../../components/ui/table"
|
} from "../../components/ui/table"
|
||||||
import { usePersonaPermissions } from "../../hooks/usePersonaPermissions"
|
import { usePersonaPermissions } from "../../hooks/usePersonaPermissions"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||||
import {
|
import {
|
||||||
formatPersonaDate,
|
formatPersonaDate,
|
||||||
personaAvatarUrl,
|
personaAvatarUrl,
|
||||||
|
|
@ -61,7 +62,6 @@ export function PersonasPage() {
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const [permissionDenied, setPermissionDenied] = useState(false)
|
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||||
const [personas, setPersonas] = useState<LmsPersona[]>([])
|
const [personas, setPersonas] = useState<LmsPersona[]>([])
|
||||||
const [totalCount, setTotalCount] = useState(0)
|
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
const [query, setQuery] = useState("")
|
const [query, setQuery] = useState("")
|
||||||
|
|
@ -71,8 +71,6 @@ export function PersonasPage() {
|
||||||
const [personaPendingDelete, setPersonaPendingDelete] = useState<LmsPersona | null>(null)
|
const [personaPendingDelete, setPersonaPendingDelete] = useState<LmsPersona | null>(null)
|
||||||
const [togglingId, setTogglingId] = useState<number | null>(null)
|
const [togglingId, setTogglingId] = useState<number | null>(null)
|
||||||
|
|
||||||
const offset = (page - 1) * pageSize
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
if (!canList) {
|
if (!canList) {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|
@ -84,18 +82,22 @@ export function PersonasPage() {
|
||||||
setPermissionDenied(false)
|
setPermissionDenied(false)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const allPersonas = await fetchAllOffsetPages(async (batchOffset, limit) => {
|
||||||
const res = await listPersonas({
|
const res = await listPersonas({
|
||||||
active_only: statusFilter === "active",
|
active_only: statusFilter === "active",
|
||||||
limit: pageSize,
|
limit,
|
||||||
offset,
|
offset: batchOffset,
|
||||||
})
|
})
|
||||||
setPersonas(res.data.personas)
|
return {
|
||||||
setTotalCount(res.data.total_count)
|
items: res.data.personas,
|
||||||
|
total_count: res.data.total_count,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
setPersonas(allPersonas)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
setError(true)
|
setError(true)
|
||||||
setPersonas([])
|
setPersonas([])
|
||||||
setTotalCount(0)
|
|
||||||
if (isPersonaForbiddenError(e)) {
|
if (isPersonaForbiddenError(e)) {
|
||||||
setPermissionDenied(true)
|
setPermissionDenied(true)
|
||||||
toast.error(getPersonaApiErrorMessage(e, "You do not have permission to view personas"))
|
toast.error(getPersonaApiErrorMessage(e, "You do not have permission to view personas"))
|
||||||
|
|
@ -105,7 +107,7 @@ export function PersonasPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [canList, statusFilter, pageSize, offset])
|
}, [canList, statusFilter])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load()
|
void load()
|
||||||
|
|
@ -113,7 +115,7 @@ export function PersonasPage() {
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}, [statusFilter, pageSize])
|
}, [statusFilter, pageSize, query])
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
let rows = personas
|
let rows = personas
|
||||||
|
|
@ -142,13 +144,16 @@ export function PersonasPage() {
|
||||||
|
|
||||||
const clearFilters = () => {
|
const clearFilters = () => {
|
||||||
setStatusFilter("all")
|
setStatusFilter("all")
|
||||||
|
setQuery("")
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const totalCount = filtered.length
|
||||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||||
const safePage = Math.min(page, totalPages)
|
const safePage = Math.min(page, totalPages)
|
||||||
const startEntry = totalCount === 0 ? 0 : offset + 1
|
const paginated = filtered.slice((safePage - 1) * pageSize, safePage * pageSize)
|
||||||
const endEntry = Math.min(offset + personas.length, totalCount)
|
const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
|
||||||
|
const endEntry = Math.min(safePage * pageSize, totalCount)
|
||||||
|
|
||||||
const handleToggleActive = async (persona: LmsPersona) => {
|
const handleToggleActive = async (persona: LmsPersona) => {
|
||||||
if (!canUpdate) {
|
if (!canUpdate) {
|
||||||
|
|
@ -291,7 +296,7 @@ export function PersonasPage() {
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : (
|
) : (
|
||||||
filtered.map((persona) => (
|
paginated.map((persona) => (
|
||||||
<TableRow key={persona.id}>
|
<TableRow key={persona.id}>
|
||||||
<TableCell className="py-3.5">
|
<TableCell className="py-3.5">
|
||||||
<img
|
<img
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import {
|
||||||
Star,
|
Star,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { loadRatingsPage } from "../../api/ratings.api"
|
import { fetchAllRatingsByTarget } from "../../api/ratings.api"
|
||||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
|
@ -77,7 +77,7 @@ export function AppReviewsPage() {
|
||||||
setPermissionDenied(false)
|
setPermissionDenied(false)
|
||||||
|
|
||||||
try {
|
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)
|
setSummary(data.summary)
|
||||||
setReviews(data.reviews)
|
setReviews(data.reviews)
|
||||||
|
|
||||||
|
|
@ -98,7 +98,7 @@ export function AppReviewsPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [canList, page, pageSize])
|
}, [canList])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load()
|
void load()
|
||||||
|
|
@ -106,7 +106,7 @@ export function AppReviewsPage() {
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}, [pageSize, starsFilter])
|
}, [pageSize, starsFilter, query])
|
||||||
|
|
||||||
const filteredReviews = useMemo(() => {
|
const filteredReviews = useMemo(() => {
|
||||||
const q = query.trim().toLowerCase()
|
const q = query.trim().toLowerCase()
|
||||||
|
|
@ -134,13 +134,14 @@ export function AppReviewsPage() {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
const totalCount = summary.total_count
|
const totalCount = filteredReviews.length
|
||||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||||
const safePage = Math.min(page, totalPages)
|
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 startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
|
||||||
const endEntry = Math.min(safePage * pageSize, totalCount)
|
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) {
|
if (!permissionsLoading && !canList) {
|
||||||
return <RatingsAccessDenied />
|
return <RatingsAccessDenied />
|
||||||
|
|
@ -211,7 +212,7 @@ export function AppReviewsPage() {
|
||||||
className="border-0 shadow-none"
|
className="border-0 shadow-none"
|
||||||
activeFilterCount={activeFilterCount}
|
activeFilterCount={activeFilterCount}
|
||||||
onClearFilters={clearFilters}
|
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={
|
summary={
|
||||||
totalCount > 0
|
totalCount > 0
|
||||||
? `Showing ${startEntry}–${endEntry} of ${totalCount}`
|
? `Showing ${startEntry}–${endEntry} of ${totalCount}`
|
||||||
|
|
@ -279,18 +280,18 @@ export function AppReviewsPage() {
|
||||||
<p className="text-sm font-medium text-grayScale-500">
|
<p className="text-sm font-medium text-grayScale-500">
|
||||||
{totalCount === 0
|
{totalCount === 0
|
||||||
? "No reviews yet"
|
? "No reviews yet"
|
||||||
: "No reviews match your filters on this page"}
|
: "No reviews match your filters"}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-grayScale-400">
|
<p className="text-xs text-grayScale-400">
|
||||||
{totalCount === 0
|
{summary.total_count === 0
|
||||||
? "Learners can submit ratings from the mobile or web app."
|
? "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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : (
|
) : (
|
||||||
filteredReviews.map((rating) => {
|
paginatedReviews.map((rating) => {
|
||||||
const profile = reviewerProfiles.get(rating.user_id)
|
const profile = reviewerProfiles.get(rating.user_id)
|
||||||
return (
|
return (
|
||||||
<TableRow key={rating.id}>
|
<TableRow key={rating.id}>
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import {
|
import {
|
||||||
|
|
@ -64,7 +65,6 @@ export function AppVersionsTab() {
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const [versions, setVersions] = useState<AppVersion[]>([])
|
const [versions, setVersions] = useState<AppVersion[]>([])
|
||||||
const [totalCount, setTotalCount] = useState(0)
|
|
||||||
const [offset, setOffset] = useState(0)
|
const [offset, setOffset] = useState(0)
|
||||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
const [query, setQuery] = useState("")
|
const [query, setQuery] = useState("")
|
||||||
|
|
@ -78,24 +78,32 @@ export function AppVersionsTab() {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError(false)
|
setError(false)
|
||||||
try {
|
try {
|
||||||
const res = await getAppVersions({ limit: pageSize, offset })
|
const allVersions = await fetchAllOffsetPages(async (batchOffset, limit) => {
|
||||||
setVersions(res.data.versions)
|
const res = await getAppVersions({ limit, offset: batchOffset })
|
||||||
setTotalCount(res.data.total_count)
|
return {
|
||||||
|
items: res.data.versions,
|
||||||
|
total_count: res.data.total_count,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
setVersions(allVersions)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
setError(true)
|
setError(true)
|
||||||
setVersions([])
|
setVersions([])
|
||||||
setTotalCount(0)
|
|
||||||
toast.error("Failed to load app versions")
|
toast.error("Failed to load app versions")
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [offset, pageSize])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load()
|
void load()
|
||||||
}, [load])
|
}, [load])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setOffset(0)
|
||||||
|
}, [query, platformFilter, statusFilter, pageSize])
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
const q = query.trim().toLowerCase()
|
const q = query.trim().toLowerCase()
|
||||||
return [...versions]
|
return [...versions]
|
||||||
|
|
@ -123,8 +131,10 @@ export function AppVersionsTab() {
|
||||||
const activeCount = versions.filter((v) => v.status.toUpperCase() === "ACTIVE").length
|
const activeCount = versions.filter((v) => v.status.toUpperCase() === "ACTIVE").length
|
||||||
const forceCount = versions.filter((v) => v.update_type.toUpperCase() === "FORCE").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 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 canPrev = offset > 0
|
||||||
const canNext = offset + pageSize < totalCount
|
const canNext = offset + pageSize < totalCount
|
||||||
|
|
||||||
|
|
@ -364,7 +374,7 @@ export function AppVersionsTab() {
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-grayScale-50">
|
<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">
|
<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">
|
<td className="whitespace-nowrap px-3 py-3 sm:px-4 sm:py-4">
|
||||||
<p className="font-semibold text-grayScale-900">
|
<p className="font-semibold text-grayScale-900">
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,7 @@ import {
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
} from "../../components/ui/dialog";
|
} from "../../components/ui/dialog";
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages";
|
||||||
import { cn } from "../../lib/utils";
|
import { cn } from "../../lib/utils";
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
||||||
import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api";
|
import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api";
|
||||||
|
|
@ -133,7 +134,6 @@ function formatRoleLabel(role: string): string {
|
||||||
// ── Main Component ─────────────────────────────────────────────────
|
// ── Main Component ─────────────────────────────────────────────────
|
||||||
export function UserLogPage() {
|
export function UserLogPage() {
|
||||||
const [logs, setLogs] = useState<ActivityLog[]>([]);
|
const [logs, setLogs] = useState<ActivityLog[]>([]);
|
||||||
const [totalCount, setTotalCount] = useState(0);
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
|
@ -150,30 +150,35 @@ export function UserLogPage() {
|
||||||
const fetchLogs = useCallback(async () => {
|
const fetchLogs = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const filters: ActivityLogFilters = {
|
const allLogs = await fetchAllOffsetPages(async (offset, limit) => {
|
||||||
limit: pageSize,
|
const filters: ActivityLogFilters = { limit, offset };
|
||||||
offset: (page - 1) * pageSize,
|
|
||||||
};
|
|
||||||
if (actionFilter) filters.action = actionFilter;
|
if (actionFilter) filters.action = actionFilter;
|
||||||
if (dateAfter) filters.after = new Date(dateAfter).toISOString();
|
if (dateAfter) filters.after = new Date(dateAfter).toISOString();
|
||||||
if (dateBefore) filters.before = new Date(dateBefore).toISOString();
|
if (dateBefore) filters.before = new Date(dateBefore).toISOString();
|
||||||
|
|
||||||
const res = await getActivityLogs(filters);
|
const res = await getActivityLogs(filters);
|
||||||
setLogs(res.data.data.logs);
|
return {
|
||||||
setTotalCount(res.data.data.total_count);
|
items: res.data.data.logs,
|
||||||
|
total_count: res.data.data.total_count,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
setLogs(allLogs);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch activity logs:", error);
|
console.error("Failed to fetch activity logs:", error);
|
||||||
setLogs([]);
|
setLogs([]);
|
||||||
setTotalCount(0);
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [page, pageSize, actionFilter, dateAfter, dateBefore]);
|
}, [actionFilter, dateAfter, dateBefore]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchLogs();
|
fetchLogs();
|
||||||
}, [fetchLogs]);
|
}, [fetchLogs]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1);
|
||||||
|
}, [searchQuery, pageSize]);
|
||||||
|
|
||||||
const handleViewDetail = async (logId: number) => {
|
const handleViewDetail = async (logId: number) => {
|
||||||
setDialogOpen(true);
|
setDialogOpen(true);
|
||||||
setDetailLoading(true);
|
setDetailLoading(true);
|
||||||
|
|
@ -207,9 +212,24 @@ export function UserLogPage() {
|
||||||
|
|
||||||
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim());
|
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
|
// Pagination
|
||||||
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
||||||
const safePage = Math.min(page, pageCount);
|
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 handlePrev = () => safePage > 1 && setPage(safePage - 1);
|
||||||
const handleNext = () => safePage < pageCount && setPage(safePage + 1);
|
const handleNext = () => safePage < pageCount && setPage(safePage + 1);
|
||||||
|
|
@ -228,19 +248,6 @@ export function UserLogPage() {
|
||||||
return pages;
|
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 (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
|
|
@ -399,7 +406,7 @@ export function UserLogPage() {
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
) : (
|
) : (
|
||||||
filteredLogs.map((log) => {
|
paginatedLogs.map((log) => {
|
||||||
const ActionIcon = getActionIcon(log.action);
|
const ActionIcon = getActionIcon(log.action);
|
||||||
return (
|
return (
|
||||||
<TableRow key={log.id} className="group">
|
<TableRow key={log.id} className="group">
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user