Add question type definition groups and streamline definition editing.
Support many-to-many group_ids in the API client and admin UI, and let admins save definition edits from the header with unsaved-change detection and redirect back to the library. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
c587ea90d8
commit
f833275b75
185
src/api/questionTypeDefinitionGroups.api.ts
Normal file
185
src/api/questionTypeDefinitionGroups.api.ts
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
import http from "./http"
|
||||
import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages"
|
||||
import {
|
||||
parseDefinitionsList,
|
||||
unwrapApiPayload,
|
||||
} from "./questionTypeDefinitions.api"
|
||||
import type {
|
||||
QuestionTypeDefinitionGroup,
|
||||
QuestionTypeDefinitionGroupCreatePayload,
|
||||
QuestionTypeDefinitionGroupDetail,
|
||||
QuestionTypeDefinitionGroupsListParams,
|
||||
QuestionTypeDefinitionGroupsListResult,
|
||||
QuestionTypeDefinitionGroupUpdatePayload,
|
||||
} from "../types/questionTypeDefinition.types"
|
||||
|
||||
interface ApiEnvelope<T> {
|
||||
message?: string
|
||||
data?: T
|
||||
Data?: T
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
function asStr(v: unknown): string {
|
||||
if (v == null) return ""
|
||||
return String(v)
|
||||
}
|
||||
|
||||
function parseGroupStatus(raw: unknown): QuestionTypeDefinitionGroup["status"] {
|
||||
const s = asStr(raw).toUpperCase()
|
||||
return s === "INACTIVE" ? "INACTIVE" : "ACTIVE"
|
||||
}
|
||||
|
||||
export function normalizeQuestionTypeDefinitionGroup(
|
||||
raw: unknown,
|
||||
): QuestionTypeDefinitionGroup | null {
|
||||
if (!raw || typeof raw !== "object") return null
|
||||
const o = raw as Record<string, unknown>
|
||||
const id = Number(o.id ?? o.ID)
|
||||
if (!Number.isFinite(id) || id <= 0) return null
|
||||
const descriptionRaw = o.description ?? o.Description
|
||||
return {
|
||||
id,
|
||||
name: asStr(o.name ?? o.Name).trim(),
|
||||
description:
|
||||
descriptionRaw == null || asStr(descriptionRaw).trim() === ""
|
||||
? null
|
||||
: asStr(descriptionRaw).trim(),
|
||||
display_order: Number(o.display_order ?? o.DisplayOrder ?? 0) || 0,
|
||||
status: parseGroupStatus(o.status ?? o.Status),
|
||||
created_at: asStr(o.created_at ?? o.CreatedAt),
|
||||
updated_at:
|
||||
o.updated_at != null || o.UpdatedAt != null
|
||||
? asStr(o.updated_at ?? o.UpdatedAt)
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function parseGroupsList(payload: unknown): QuestionTypeDefinitionGroup[] {
|
||||
if (!payload) return []
|
||||
if (Array.isArray(payload)) {
|
||||
return payload
|
||||
.map((row) => normalizeQuestionTypeDefinitionGroup(row))
|
||||
.filter((g): g is QuestionTypeDefinitionGroup => g != null)
|
||||
}
|
||||
if (typeof payload === "object") {
|
||||
const o = payload as Record<string, unknown>
|
||||
const inner =
|
||||
o.groups ??
|
||||
o.Groups ??
|
||||
o.question_type_definition_groups ??
|
||||
o.QuestionTypeDefinitionGroups
|
||||
if (Array.isArray(inner)) {
|
||||
return inner
|
||||
.map((row) => normalizeQuestionTypeDefinitionGroup(row))
|
||||
.filter((g): g is QuestionTypeDefinitionGroup => g != null)
|
||||
}
|
||||
const single = normalizeQuestionTypeDefinitionGroup(payload)
|
||||
return single ? [single] : []
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function parseGroupsListResult(payload: unknown): QuestionTypeDefinitionGroupsListResult {
|
||||
const empty: QuestionTypeDefinitionGroupsListResult = {
|
||||
groups: [],
|
||||
total_count: 0,
|
||||
limit: 20,
|
||||
offset: 0,
|
||||
}
|
||||
if (!payload || typeof payload !== "object") return empty
|
||||
const o = payload as Record<string, unknown>
|
||||
const groups = parseGroupsList(o.groups ?? o.Groups ?? payload)
|
||||
const total_count = Number(o.total_count ?? o.TotalCount ?? groups.length)
|
||||
const limit = Number(o.limit ?? o.Limit ?? 20)
|
||||
const offset = Number(o.offset ?? o.Offset ?? 0)
|
||||
return {
|
||||
groups,
|
||||
total_count: Number.isFinite(total_count) ? total_count : groups.length,
|
||||
limit: Number.isFinite(limit) ? limit : 20,
|
||||
offset: Number.isFinite(offset) ? offset : 0,
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchGroupsPage(
|
||||
params?: QuestionTypeDefinitionGroupsListParams,
|
||||
): Promise<QuestionTypeDefinitionGroupsListResult> {
|
||||
const res = await http.get<ApiEnvelope<unknown>>("/questions/type-definition-groups", {
|
||||
params,
|
||||
})
|
||||
const raw = unwrapApiPayload(res) ?? res.data
|
||||
return parseGroupsListResult(raw)
|
||||
}
|
||||
|
||||
const GROUPS_FETCH_ALL_PAGE_SIZE = 100
|
||||
|
||||
/** Lists all groups (paginates through the API). */
|
||||
export async function getQuestionTypeDefinitionGroups(
|
||||
params?: QuestionTypeDefinitionGroupsListParams,
|
||||
): Promise<QuestionTypeDefinitionGroupsListResult> {
|
||||
const hasExplicitPagination = params?.limit !== undefined || params?.offset !== undefined
|
||||
if (hasExplicitPagination) {
|
||||
return fetchGroupsPage(params)
|
||||
}
|
||||
|
||||
const groups = await fetchAllOffsetPages(async (offset, limit) => {
|
||||
const page = await fetchGroupsPage({ ...params, limit, offset })
|
||||
return { items: page.groups, total_count: page.total_count }
|
||||
})
|
||||
|
||||
return {
|
||||
groups: groups.sort(
|
||||
(a, b) => a.display_order - b.display_order || a.name.localeCompare(b.name),
|
||||
),
|
||||
total_count: groups.length,
|
||||
limit: GROUPS_FETCH_ALL_PAGE_SIZE,
|
||||
offset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getQuestionTypeDefinitionGroupById(
|
||||
id: number,
|
||||
): Promise<QuestionTypeDefinitionGroupDetail | undefined> {
|
||||
const res = await http.get<ApiEnvelope<unknown>>(`/questions/type-definition-groups/${id}`)
|
||||
const raw = unwrapApiPayload(res) ?? res.data
|
||||
if (!raw || typeof raw !== "object") return undefined
|
||||
const group = normalizeQuestionTypeDefinitionGroup(raw)
|
||||
if (!group) return undefined
|
||||
const o = raw as Record<string, unknown>
|
||||
const definitions = parseDefinitionsList(o.definitions ?? o.Definitions)
|
||||
return { ...group, definitions }
|
||||
}
|
||||
|
||||
export async function createQuestionTypeDefinitionGroup(
|
||||
body: QuestionTypeDefinitionGroupCreatePayload,
|
||||
) {
|
||||
return http.post<ApiEnvelope<unknown>>("/questions/type-definition-groups", body)
|
||||
}
|
||||
|
||||
export async function updateQuestionTypeDefinitionGroup(
|
||||
id: number,
|
||||
body: QuestionTypeDefinitionGroupUpdatePayload,
|
||||
) {
|
||||
return http.put<ApiEnvelope<unknown>>(`/questions/type-definition-groups/${id}`, body)
|
||||
}
|
||||
|
||||
export async function deleteQuestionTypeDefinitionGroup(id: number) {
|
||||
return http.delete<ApiEnvelope<unknown>>(`/questions/type-definition-groups/${id}`)
|
||||
}
|
||||
|
||||
export function extractGroupMutationId(res: { data?: unknown }): number | undefined {
|
||||
const data = unwrapApiPayload(res)
|
||||
if (!data || typeof data !== "object" || Array.isArray(data)) return undefined
|
||||
const o = data as Record<string, unknown>
|
||||
const id = Number(o.id ?? o.ID)
|
||||
return Number.isFinite(id) && id > 0 ? id : undefined
|
||||
}
|
||||
|
||||
export function groupApiErrorMessage(e: unknown, fallback: string): string {
|
||||
const err = e as { response?: { data?: { message?: string; error?: string } } }
|
||||
return String(
|
||||
err.response?.data?.message || err.response?.data?.error || fallback,
|
||||
)
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import type {
|
|||
QuestionTypeDefinitionValidatePayload,
|
||||
ValidateQuestionTypeDefinitionResult,
|
||||
} from "../types/questionTypeDefinition.types"
|
||||
import { normalizeGroupIds } from "../lib/questionTypeGroupIds"
|
||||
import { normalizePracticeParents, parentsFromPractice } from "../lib/practiceParents"
|
||||
|
||||
interface ApiEnvelope<T> {
|
||||
|
|
@ -230,6 +231,9 @@ export function normalizeTypeDefinitionFromApi(raw: unknown): QuestionTypeDefini
|
|||
const s = asStr(d)
|
||||
return s === "" ? null : s
|
||||
})(),
|
||||
group_ids: normalizeGroupIds(
|
||||
o.group_ids ?? o.GroupIds ?? o.group_id ?? o.GroupId ?? o.groupId,
|
||||
),
|
||||
stimulus_component_kinds: asStringArray(o.StimulusComponentKinds ?? o.stimulus_component_kinds),
|
||||
response_component_kinds: asStringArray(o.ResponseComponentKinds ?? o.response_component_kinds),
|
||||
stimulus_schema: normalizeSchemaRows(o.StimulusSchema ?? o.stimulus_schema),
|
||||
|
|
@ -268,6 +272,7 @@ export const extractCreatedDefinitionId = extractDefinitionMutationId
|
|||
export interface QuestionTypeDefinitionsListParams {
|
||||
include_system?: boolean
|
||||
status?: string
|
||||
group_id?: number
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
|
@ -409,6 +414,24 @@ export async function updateQuestionTypeDefinition(
|
|||
return http.put<ApiEnvelope<unknown>>(`/questions/type-definitions/${id}`, body)
|
||||
}
|
||||
|
||||
/** Assign or replace group memberships (`null` or `[]` clears all). */
|
||||
export async function assignQuestionTypeDefinitionGroups(
|
||||
definitionId: number,
|
||||
groupIds: number[] | null,
|
||||
) {
|
||||
return updateQuestionTypeDefinition(definitionId, {
|
||||
group_ids: normalizeGroupIds(groupIds),
|
||||
})
|
||||
}
|
||||
|
||||
/** @deprecated Use assignQuestionTypeDefinitionGroups */
|
||||
export async function assignQuestionTypeDefinitionGroup(
|
||||
definitionId: number,
|
||||
groupId: number | null,
|
||||
) {
|
||||
return assignQuestionTypeDefinitionGroups(definitionId, groupId == null ? null : [groupId])
|
||||
}
|
||||
|
||||
export async function deleteQuestionTypeDefinition(id: number) {
|
||||
return http.delete<ApiEnvelope<unknown>>(`/questions/type-definitions/${id}`)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ import { ProgramDetailPage } from "../pages/content-management/ProgramDetailPage
|
|||
import { CourseManagementPage } from "../pages/content-management/CourseManagementPage";
|
||||
import { UnitManagementPage } from "../pages/content-management/UnitManagementPage";
|
||||
import { QuestionTypeLibraryPage } from "../pages/content-management/QuestionTypeLibraryPage";
|
||||
import { QuestionTypeGroupDetailPage } from "../pages/content-management/QuestionTypeGroupDetailPage";
|
||||
import { CreateQuestionTypeFlow } from "../pages/content-management/CreateQuestionTypeFlow";
|
||||
import { NotFoundPage } from "../pages/NotFoundPage";
|
||||
import { NotificationsPage } from "../pages/notifications/NotificationsPage";
|
||||
|
|
@ -183,6 +184,10 @@ export function AppRoutes() {
|
|||
path="/new-content/question-types"
|
||||
element={<QuestionTypeLibraryPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/question-types/groups/:groupId"
|
||||
element={<QuestionTypeGroupDetailPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/question-types/:definitionId/create-practice"
|
||||
element={<AddPracticeFlow />}
|
||||
|
|
|
|||
45
src/lib/questionTypeGroupIds.ts
Normal file
45
src/lib/questionTypeGroupIds.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import type { QuestionTypeDefinitionGroup } from "../types/questionTypeDefinition.types"
|
||||
|
||||
/** Normalize API / draft `group_ids` to sorted unique positive ids, or null when empty. */
|
||||
export function normalizeGroupIds(value: unknown): number[] | null {
|
||||
if (value == null) return null
|
||||
if (Array.isArray(value)) {
|
||||
const ids = value
|
||||
.map((v) => Number(v))
|
||||
.filter((n) => Number.isFinite(n) && n > 0)
|
||||
if (!ids.length) return null
|
||||
return [...new Set(ids)].sort((a, b) => a - b)
|
||||
}
|
||||
const single = Number(value)
|
||||
if (Number.isFinite(single) && single > 0) return [single]
|
||||
return null
|
||||
}
|
||||
|
||||
export function isDefinitionUngrouped(groupIds: number[] | null | undefined): boolean {
|
||||
return groupIds == null || groupIds.length === 0
|
||||
}
|
||||
|
||||
export function definitionBelongsToGroup(
|
||||
groupIds: number[] | null | undefined,
|
||||
groupId: number,
|
||||
): boolean {
|
||||
return groupIds?.includes(groupId) ?? false
|
||||
}
|
||||
|
||||
export function removeGroupFromMembership(
|
||||
groupIds: number[] | null | undefined,
|
||||
groupId: number,
|
||||
): number[] | null {
|
||||
const next = (groupIds ?? []).filter((id) => id !== groupId)
|
||||
return next.length ? next : null
|
||||
}
|
||||
|
||||
export function questionTypeGroupLabels(
|
||||
groupIds: number[] | null | undefined,
|
||||
groups: QuestionTypeDefinitionGroup[],
|
||||
): string {
|
||||
if (isDefinitionUngrouped(groupIds)) return "Ungrouped"
|
||||
return (groupIds ?? [])
|
||||
.map((id) => groups.find((g) => g.id === id)?.name ?? `Group #${id}`)
|
||||
.join(", ")
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { useEffect, useMemo, useState } from "react"
|
||||
import { Link, useNavigate, useParams } from "react-router-dom"
|
||||
import { ArrowLeft } from "lucide-react"
|
||||
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card } from "../../components/ui/card"
|
||||
|
|
@ -21,9 +21,12 @@ import type {
|
|||
import {
|
||||
buildCreatePayload,
|
||||
buildValidateKindsPayload,
|
||||
seedSchemasFromKindsIfEmpty,
|
||||
validateDefinitionBasic,
|
||||
validateDefinitionKinds,
|
||||
validateDefinitionSchemas,
|
||||
validateDefinitionThroughStep,
|
||||
areDefinitionDraftsEqual,
|
||||
type FieldErrorMap,
|
||||
} from "./lib/questionTypeDefinitionValidation"
|
||||
import { defaultLabelForKind } from "../../lib/schemaSlotLabel"
|
||||
|
|
@ -32,16 +35,14 @@ import { QuestionTypeConfigStep } from "./components/question-type-steps/Questio
|
|||
import { QuestionTypeValidatePreviewStep } from "./components/question-type-steps/QuestionTypeValidatePreviewStep"
|
||||
import { QuestionTypeReviewPublishStep } from "./components/question-type-steps/QuestionTypeReviewPublishStep"
|
||||
import {
|
||||
isNoInputComponentKind,
|
||||
mergeCatalogWithNoInput,
|
||||
noInputSchemaRow,
|
||||
sideIsNoInputOnly,
|
||||
} from "../../lib/questionComponentKinds"
|
||||
|
||||
const initialDraft = (): QuestionTypeDefinitionCreatePayload => ({
|
||||
const initialDraft = (presetGroupId?: number | null): QuestionTypeDefinitionCreatePayload => ({
|
||||
key: "",
|
||||
display_name: "",
|
||||
description: "",
|
||||
group_ids: presetGroupId ? [presetGroupId] : null,
|
||||
status: "ACTIVE",
|
||||
stimulus_component_kinds: [],
|
||||
response_component_kinds: [],
|
||||
|
|
@ -49,20 +50,12 @@ const initialDraft = (): QuestionTypeDefinitionCreatePayload => ({
|
|||
response_schema: [],
|
||||
})
|
||||
|
||||
function seedSchemaFromKinds(kinds: string[]) {
|
||||
return kinds.map((k, i) => ({
|
||||
id: `${(k || "field").toLowerCase().replace(/[^a-z0-9]+/g, "_") || "field"}_${i + 1}`,
|
||||
kind: k,
|
||||
label: defaultLabelForKind(k),
|
||||
required: true as boolean,
|
||||
}))
|
||||
}
|
||||
|
||||
function definitionToDraft(def: QuestionTypeDefinition): QuestionTypeDefinitionCreatePayload {
|
||||
return {
|
||||
key: def.key,
|
||||
display_name: def.display_name,
|
||||
description: def.description ?? "",
|
||||
group_ids: def.group_ids ?? null,
|
||||
status: def.status === "INACTIVE" ? "INACTIVE" : "ACTIVE",
|
||||
stimulus_component_kinds: [...(def.stimulus_component_kinds ?? [])],
|
||||
response_component_kinds: [...(def.response_component_kinds ?? [])],
|
||||
|
|
@ -79,6 +72,13 @@ function definitionToDraft(def: QuestionTypeDefinition): QuestionTypeDefinitionC
|
|||
|
||||
export function CreateQuestionTypeFlow() {
|
||||
const navigate = useNavigate()
|
||||
const [searchParams] = useSearchParams()
|
||||
const presetGroupId = useMemo(() => {
|
||||
const raw = searchParams.get("groupId")
|
||||
if (!raw || !/^\d+$/.test(raw)) return null
|
||||
const n = Number(raw)
|
||||
return Number.isFinite(n) && n > 0 ? n : null
|
||||
}, [searchParams])
|
||||
const { definitionId: definitionIdParam } = useParams<{ definitionId?: string }>()
|
||||
const editDefinitionId = useMemo(() => {
|
||||
if (!definitionIdParam || !/^\d+$/.test(definitionIdParam)) return null
|
||||
|
|
@ -88,7 +88,9 @@ export function CreateQuestionTypeFlow() {
|
|||
const isEdit = editDefinitionId != null
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(1)
|
||||
const [draft, setDraft] = useState<QuestionTypeDefinitionCreatePayload>(initialDraft)
|
||||
const [draft, setDraft] = useState<QuestionTypeDefinitionCreatePayload>(() =>
|
||||
initialDraft(presetGroupId),
|
||||
)
|
||||
const [stepErrors, setStepErrors] = useState<FieldErrorMap>({})
|
||||
const [definitionReady, setDefinitionReady] = useState(!isEdit)
|
||||
const [isSystemDefinition, setIsSystemDefinition] = useState(false)
|
||||
|
|
@ -99,6 +101,13 @@ export function CreateQuestionTypeFlow() {
|
|||
})
|
||||
const [catalogLoading, setCatalogLoading] = useState(true)
|
||||
const [catalogError, setCatalogError] = useState<string | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savedDraft, setSavedDraft] = useState<QuestionTypeDefinitionCreatePayload | null>(null)
|
||||
|
||||
const hasUnsavedChanges = useMemo(() => {
|
||||
if (!isEdit || savedDraft == null) return false
|
||||
return !areDefinitionDraftsEqual(draft, savedDraft)
|
||||
}, [isEdit, draft, savedDraft])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
|
@ -147,7 +156,9 @@ export function CreateQuestionTypeFlow() {
|
|||
navigate("/new-content/question-types")
|
||||
return
|
||||
}
|
||||
setDraft(definitionToDraft(def))
|
||||
const loaded = definitionToDraft(def)
|
||||
setDraft(loaded)
|
||||
setSavedDraft(loaded)
|
||||
setIsSystemDefinition(Boolean(def.is_system))
|
||||
setCurrentStep(1)
|
||||
setStepErrors({})
|
||||
|
|
@ -168,12 +179,13 @@ export function CreateQuestionTypeFlow() {
|
|||
|
||||
useEffect(() => {
|
||||
if (!isEdit) {
|
||||
setDraft(initialDraft())
|
||||
setDraft(initialDraft(presetGroupId))
|
||||
setSavedDraft(null)
|
||||
setCurrentStep(1)
|
||||
setStepErrors({})
|
||||
setDefinitionReady(true)
|
||||
}
|
||||
}, [isEdit])
|
||||
}, [isEdit, presetGroupId])
|
||||
|
||||
const catalogForSchemaValidation = {
|
||||
stimulus: new Set(mergeCatalogWithNoInput(componentCatalog.stimulus_component_kinds)),
|
||||
|
|
@ -208,29 +220,7 @@ export function CreateQuestionTypeFlow() {
|
|||
return
|
||||
}
|
||||
|
||||
const nextDraft: QuestionTypeDefinitionCreatePayload = { ...draft }
|
||||
if (
|
||||
!nextDraft.stimulus_schema.length &&
|
||||
sideIsNoInputOnly(nextDraft.stimulus_component_kinds)
|
||||
) {
|
||||
nextDraft.stimulus_schema = [noInputSchemaRow()]
|
||||
} else if (
|
||||
!nextDraft.stimulus_schema.length &&
|
||||
nextDraft.stimulus_component_kinds.length
|
||||
) {
|
||||
nextDraft.stimulus_schema = seedSchemaFromKinds(nextDraft.stimulus_component_kinds)
|
||||
}
|
||||
if (
|
||||
!nextDraft.response_schema.length &&
|
||||
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)
|
||||
}
|
||||
const nextDraft = seedSchemasFromKindsIfEmpty(draft)
|
||||
setDraft(nextDraft)
|
||||
|
||||
const mergedSchema = validateDefinitionSchemas(nextDraft, catalogForSchemaValidation)
|
||||
|
|
@ -247,7 +237,58 @@ export function CreateQuestionTypeFlow() {
|
|||
|
||||
const handleBack = () => setCurrentStep((prev) => Math.max(prev - 1, 1))
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
if (!isEdit || editDefinitionId == null || !hasUnsavedChanges) return
|
||||
|
||||
const prepared = currentStep >= 2 ? seedSchemasFromKindsIfEmpty(draft) : draft
|
||||
|
||||
const errors = validateDefinitionThroughStep(
|
||||
currentStep,
|
||||
prepared,
|
||||
componentCatalog,
|
||||
catalogForSchemaValidation,
|
||||
)
|
||||
setStepErrors(errors)
|
||||
if (Object.keys(errors).length) {
|
||||
toast.error("Fix the highlighted fields before saving.")
|
||||
return
|
||||
}
|
||||
setStepErrors({})
|
||||
|
||||
const body = buildCreatePayload(prepared)
|
||||
setSaving(true)
|
||||
try {
|
||||
if (currentStep >= 2) {
|
||||
const validation = await validateQuestionTypeDefinition(buildValidateKindsPayload(prepared))
|
||||
if (!validation.valid) {
|
||||
toast.error(validation.message || "Invalid question type definition", {
|
||||
description: validation.error ? String(validation.error) : undefined,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const res = await updateQuestionTypeDefinition(editDefinitionId, body)
|
||||
const id = extractDefinitionMutationId(res) ?? editDefinitionId
|
||||
toast.success(res.data?.message || "Question type definition updated", {
|
||||
description: `Definition id: ${id}`,
|
||||
})
|
||||
navigate(`/new-content/question-types?updated=${id}`)
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { message?: string; error?: string } } }
|
||||
toast.error(String(err.response?.data?.message || "Save failed"), {
|
||||
description: err.response?.data?.error ? String(err.response.data.error) : undefined,
|
||||
})
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleHeaderSaveDraft = async () => {
|
||||
if (isEdit) {
|
||||
await handleSaveEdit()
|
||||
return
|
||||
}
|
||||
setDraft((d) => ({ ...d, status: "INACTIVE" }))
|
||||
if (currentStep < 4) {
|
||||
toast.message("Status set to Inactive", {
|
||||
|
|
@ -338,9 +379,19 @@ export function CreateQuestionTypeFlow() {
|
|||
</Button>
|
||||
<Button
|
||||
className="h-10 px-8 rounded-[6px] bg-[#9E2891] font-medium text-white shadow-lg shadow-brand-500/10 hover:bg-[#8A237E] transition-all"
|
||||
onClick={handleHeaderSaveDraft}
|
||||
onClick={() => void handleHeaderSaveDraft()}
|
||||
disabled={saving || (isEdit && !hasUnsavedChanges)}
|
||||
>
|
||||
Save as Draft
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Saving…
|
||||
</>
|
||||
) : isEdit ? (
|
||||
"Save changes"
|
||||
) : (
|
||||
"Save as Draft"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -359,6 +410,7 @@ export function CreateQuestionTypeFlow() {
|
|||
errors={stepErrors}
|
||||
keyReadOnly={isEdit}
|
||||
onNext={handleNextFromStep1}
|
||||
saving={saving}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 2 && (
|
||||
|
|
@ -372,10 +424,16 @@ export function CreateQuestionTypeFlow() {
|
|||
errors={stepErrors}
|
||||
onNext={handleNextFromStep2}
|
||||
onBack={handleBack}
|
||||
saving={saving}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 3 && (
|
||||
<QuestionTypeValidatePreviewStep draft={draft} onNext={() => setCurrentStep(4)} onBack={handleBack} />
|
||||
<QuestionTypeValidatePreviewStep
|
||||
draft={draft}
|
||||
onNext={() => setCurrentStep(4)}
|
||||
onBack={handleBack}
|
||||
saving={saving}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 4 && (
|
||||
<QuestionTypeReviewPublishStep
|
||||
|
|
@ -383,6 +441,7 @@ export function CreateQuestionTypeFlow() {
|
|||
onBack={handleBack}
|
||||
editDefinitionId={editDefinitionId}
|
||||
isSystem={isSystemDefinition}
|
||||
saveDisabled={isEdit && !hasUnsavedChanges}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
306
src/pages/content-management/QuestionTypeGroupDetailPage.tsx
Normal file
306
src/pages/content-management/QuestionTypeGroupDetailPage.tsx
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { Link, useNavigate, useParams } from "react-router-dom"
|
||||
import {
|
||||
ArrowLeft,
|
||||
FolderOpen,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
Unlink,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../components/ui/dialog"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { cn } from "../../lib/utils"
|
||||
import {
|
||||
deleteQuestionTypeDefinitionGroup,
|
||||
getQuestionTypeDefinitionGroupById,
|
||||
groupApiErrorMessage,
|
||||
} from "../../api/questionTypeDefinitionGroups.api"
|
||||
import { assignQuestionTypeDefinitionGroups } from "../../api/questionTypeDefinitions.api"
|
||||
import { removeGroupFromMembership } from "../../lib/questionTypeGroupIds"
|
||||
import type { QuestionTypeDefinitionGroupDetail } from "../../types/questionTypeDefinition.types"
|
||||
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
||||
import { QuestionTypeGroupFormDialog } from "./components/QuestionTypeGroupFormDialog"
|
||||
import { QuestionTypeDefinitionPracticesDialog } from "./components/QuestionTypeDefinitionPracticesDialog"
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||
|
||||
export function QuestionTypeGroupDetailPage() {
|
||||
const navigate = useNavigate()
|
||||
const { groupId: groupIdParam } = useParams<{ groupId: string }>()
|
||||
const groupId = Number(groupIdParam)
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [group, setGroup] = useState<QuestionTypeDefinitionGroupDetail | null>(null)
|
||||
const [editOpen, setEditOpen] = useState(false)
|
||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
||||
const [deleteSubmitting, setDeleteSubmitting] = useState(false)
|
||||
const [definitionForPractices, setDefinitionForPractices] = useState<QuestionTypeDefinition | null>(
|
||||
null,
|
||||
)
|
||||
const [detachingId, setDetachingId] = useState<number | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!Number.isFinite(groupId) || groupId <= 0) {
|
||||
setGroup(null)
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
try {
|
||||
const detail = await getQuestionTypeDefinitionGroupById(groupId)
|
||||
if (!detail) {
|
||||
toast.error("Group not found")
|
||||
navigate("/new-content/question-types")
|
||||
return
|
||||
}
|
||||
setGroup(detail)
|
||||
} catch (e) {
|
||||
toast.error(groupApiErrorMessage(e, "Failed to load group"))
|
||||
setGroup(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [groupId, navigate])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const handleDetach = async (definitionId: number) => {
|
||||
if (!group) return
|
||||
const def = group.definitions.find((d) => d.id === definitionId)
|
||||
const next = removeGroupFromMembership(def?.group_ids, groupId)
|
||||
setDetachingId(definitionId)
|
||||
try {
|
||||
await assignQuestionTypeDefinitionGroups(definitionId, next)
|
||||
toast.success("Removed from this group")
|
||||
await load()
|
||||
} catch (e) {
|
||||
toast.error(groupApiErrorMessage(e, "Could not remove from group"))
|
||||
} finally {
|
||||
setDetachingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteGroup = async () => {
|
||||
if (!group) return
|
||||
setDeleteSubmitting(true)
|
||||
try {
|
||||
await deleteQuestionTypeDefinitionGroup(group.id)
|
||||
toast.success("Group deleted. Membership links for this group were removed.")
|
||||
navigate("/new-content/question-types")
|
||||
} catch (e) {
|
||||
toast.error(groupApiErrorMessage(e, "Delete failed"))
|
||||
} finally {
|
||||
setDeleteSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!Number.isFinite(groupId) || groupId <= 0) {
|
||||
return (
|
||||
<div className="px-6 py-20 text-center text-sm text-grayScale-500">Invalid group id.</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-in fade-in duration-500 pb-20">
|
||||
<Link
|
||||
to="/new-content/question-types"
|
||||
className="flex items-center gap-2 text-[15px] font-bold text-grayScale-600 transition-colors hover:text-brand-500 group w-fit"
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5 transition-transform group-hover:-translate-x-1" />
|
||||
Back to question types
|
||||
</Link>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-24">
|
||||
<SpinnerIcon className="h-8 w-8 text-brand-500" />
|
||||
<p className="text-sm text-grayScale-500">Loading group…</p>
|
||||
</div>
|
||||
) : !group ? (
|
||||
<p className="text-sm text-grayScale-500">Group not found.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
|
||||
<FolderOpen className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-[28px] font-medium text-grayScale-900 tracking-tight">
|
||||
{group.name}
|
||||
</h1>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||
<Badge
|
||||
className={cn(
|
||||
"border-none shadow-none",
|
||||
group.status === "ACTIVE"
|
||||
? "bg-[#F0FDF4] text-[#16A34A]"
|
||||
: "bg-grayScale-100 text-grayScale-600",
|
||||
)}
|
||||
>
|
||||
{group.status}
|
||||
</Badge>
|
||||
<span className="text-xs text-grayScale-500">
|
||||
Order {group.display_order} · {group.definitions.length} definition
|
||||
{group.definitions.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{group.description ? (
|
||||
<p className="max-w-2xl text-sm text-grayScale-600">{group.description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit group
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete group
|
||||
</Button>
|
||||
<Link to={`/new-content/question-types/create?groupId=${group.id}`}>
|
||||
<Button size="sm" className="bg-[#9E2891] hover:bg-[#8A237E] text-white">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add definition
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
|
||||
<CardHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<CardTitle className="text-base font-bold text-grayScale-900">
|
||||
Definitions in this group
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6">
|
||||
{group.definitions.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
|
||||
<p className="text-sm font-semibold text-grayScale-700">No definitions yet</p>
|
||||
<p className="max-w-sm text-xs text-grayScale-500">
|
||||
Create a definition in this group or move an existing one here from the library.
|
||||
</p>
|
||||
<Link to={`/new-content/question-types/create?groupId=${group.id}`}>
|
||||
<Button size="sm" className="rounded-[8px] bg-brand-600 hover:bg-brand-500">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create definition
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{group.definitions.map((d) => (
|
||||
<div key={d.id} className="space-y-2">
|
||||
<QuestionTypeCard
|
||||
id={d.id}
|
||||
definitionKey={d.key}
|
||||
display_name={d.display_name}
|
||||
status={d.status}
|
||||
is_system={d.is_system}
|
||||
stimulusKindsCount={d.stimulus_component_kinds?.length ?? 0}
|
||||
responseKindsCount={d.response_component_kinds?.length ?? 0}
|
||||
deleteDisabled={!!d.is_system}
|
||||
onEdit={() => navigate(`/new-content/question-types/${d.id}/edit`)}
|
||||
onCreatePractice={() =>
|
||||
navigate(`/new-content/question-types/${d.id}/create-practice`)
|
||||
}
|
||||
onViewPractices={() => setDefinitionForPractices(d)}
|
||||
onDelete={undefined}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-full text-xs text-grayScale-600 hover:text-red-600"
|
||||
disabled={detachingId === d.id}
|
||||
onClick={() => void handleDetach(d.id)}
|
||||
>
|
||||
{detachingId === d.id ? (
|
||||
<SpinnerIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||
) : (
|
||||
<Unlink className="mr-1.5 h-3.5 w-3.5" />
|
||||
)}
|
||||
Remove from group
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
|
||||
<QuestionTypeGroupFormDialog
|
||||
open={editOpen}
|
||||
onOpenChange={setEditOpen}
|
||||
group={group}
|
||||
onSaved={() => void load()}
|
||||
/>
|
||||
|
||||
<QuestionTypeDefinitionPracticesDialog
|
||||
definition={definitionForPractices}
|
||||
open={definitionForPractices !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDefinitionForPractices(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
<Dialog open={deleteOpen} onOpenChange={(open) => !deleteSubmitting && setDeleteOpen(open)}>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete group?</DialogTitle>
|
||||
<DialogDescription className="text-left">
|
||||
Deleting this group will not delete any question types. Definitions will be removed from this
|
||||
group only; other group memberships are unchanged.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={deleteSubmitting}
|
||||
onClick={() => setDeleteOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={deleteSubmitting}
|
||||
onClick={() => void handleDeleteGroup()}
|
||||
>
|
||||
{deleteSubmitting ? <SpinnerIcon className="h-4 w-4" /> : "Delete group"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -5,7 +5,10 @@ import {
|
|||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronUp,
|
||||
FolderOpen,
|
||||
Layers,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
|
|
@ -14,6 +17,7 @@ import {
|
|||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
|
|
@ -35,10 +39,25 @@ import {
|
|||
deleteQuestionTypeDefinition,
|
||||
getQuestionTypeDefinitions,
|
||||
} from "../../api/questionTypeDefinitions.api"
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||
import {
|
||||
deleteQuestionTypeDefinitionGroup,
|
||||
getQuestionTypeDefinitionGroups,
|
||||
groupApiErrorMessage,
|
||||
} from "../../api/questionTypeDefinitionGroups.api"
|
||||
import type {
|
||||
QuestionTypeDefinition,
|
||||
QuestionTypeDefinitionGroup,
|
||||
} from "../../types/questionTypeDefinition.types"
|
||||
import { QuestionTypeGroupFormDialog } from "./components/QuestionTypeGroupFormDialog"
|
||||
import {
|
||||
definitionBelongsToGroup,
|
||||
isDefinitionUngrouped,
|
||||
questionTypeGroupLabels,
|
||||
} from "../../lib/questionTypeGroupIds"
|
||||
|
||||
type StatusFilter = "All" | "ACTIVE" | "INACTIVE"
|
||||
type ScopeFilter = "all" | "system" | "custom"
|
||||
type GroupFilter = "all" | "ungrouped" | number
|
||||
|
||||
const STATUS_OPTIONS: { value: StatusFilter; label: string }[] = [
|
||||
{ value: "All", label: "All statuses" },
|
||||
|
|
@ -60,23 +79,49 @@ export function QuestionTypeLibraryPage() {
|
|||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [definitions, setDefinitions] = useState<QuestionTypeDefinition[]>([])
|
||||
const [groups, setGroups] = useState<QuestionTypeDefinitionGroup[]>([])
|
||||
const [groupsLoading, setGroupsLoading] = useState(true)
|
||||
const [query, setQuery] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
|
||||
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("all")
|
||||
const [groupFilter, setGroupFilter] = useState<GroupFilter>("all")
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [definitionPendingDelete, setDefinitionPendingDelete] = useState<QuestionTypeDefinition | null>(null)
|
||||
const [deleteSubmitting, setDeleteSubmitting] = useState(false)
|
||||
const [definitionForPractices, setDefinitionForPractices] = useState<QuestionTypeDefinition | null>(null)
|
||||
const [groupFormOpen, setGroupFormOpen] = useState(false)
|
||||
const [groupPendingEdit, setGroupPendingEdit] = useState<QuestionTypeDefinitionGroup | null>(null)
|
||||
const [groupPendingDelete, setGroupPendingDelete] = useState<QuestionTypeDefinitionGroup | null>(null)
|
||||
const [groupDeleteSubmitting, setGroupDeleteSubmitting] = useState(false)
|
||||
const [groupsSectionOpen, setGroupsSectionOpen] = useState(false)
|
||||
|
||||
const hasActiveFilters =
|
||||
query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all"
|
||||
query.trim().length > 0 ||
|
||||
statusFilter !== "All" ||
|
||||
scopeFilter !== "all" ||
|
||||
groupFilter !== "all"
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter, defaultValue: "All" },
|
||||
{ value: scopeFilter, defaultValue: "all" },
|
||||
{ value: groupFilter === "all" ? "" : "filtered", defaultValue: "" },
|
||||
])
|
||||
|
||||
const loadGroups = useCallback(async () => {
|
||||
setGroupsLoading(true)
|
||||
try {
|
||||
const { groups: rows } = await getQuestionTypeDefinitionGroups()
|
||||
setGroups(rows)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.error("Failed to load question type groups")
|
||||
setGroups([])
|
||||
} finally {
|
||||
setGroupsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
|
|
@ -98,11 +143,12 @@ export function QuestionTypeLibraryPage() {
|
|||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
void loadGroups()
|
||||
}, [load, loadGroups])
|
||||
|
||||
useEffect(() => {
|
||||
setOffset(0)
|
||||
}, [query, pageSize, scopeFilter, statusFilter])
|
||||
}, [query, pageSize, scopeFilter, statusFilter, groupFilter])
|
||||
|
||||
useEffect(() => {
|
||||
if (createdId) {
|
||||
|
|
@ -119,14 +165,23 @@ export function QuestionTypeLibraryPage() {
|
|||
const isSystemScope = scopeFilter === "system"
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let rows = definitions
|
||||
if (groupFilter === "ungrouped") {
|
||||
rows = rows.filter((d) => isDefinitionUngrouped(d.group_ids))
|
||||
} else if (typeof groupFilter === "number") {
|
||||
rows = rows.filter((d) => definitionBelongsToGroup(d.group_ids, groupFilter))
|
||||
}
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return definitions
|
||||
return definitions.filter((d) => {
|
||||
if (!q) return rows
|
||||
return rows.filter((d) => {
|
||||
const name = (d.display_name || "").toLowerCase()
|
||||
const key = (d.key || "").toLowerCase()
|
||||
return name.includes(q) || key.includes(q) || String(d.id).includes(q)
|
||||
const groupName = questionTypeGroupLabels(d.group_ids, groups).toLowerCase()
|
||||
return (
|
||||
name.includes(q) || key.includes(q) || String(d.id).includes(q) || groupName.includes(q)
|
||||
)
|
||||
})
|
||||
}, [definitions, query])
|
||||
}, [definitions, query, groupFilter, groups])
|
||||
|
||||
const paginated = useMemo(() => {
|
||||
if (isSystemScope) return filtered
|
||||
|
|
@ -146,9 +201,42 @@ export function QuestionTypeLibraryPage() {
|
|||
setQuery("")
|
||||
setStatusFilter("All")
|
||||
setScopeFilter("all")
|
||||
setGroupFilter("all")
|
||||
setOffset(0)
|
||||
}
|
||||
|
||||
const definitionCountByGroup = useMemo(() => {
|
||||
const counts = new Map<number, number>()
|
||||
for (const d of definitions) {
|
||||
for (const id of d.group_ids ?? []) {
|
||||
counts.set(id, (counts.get(id) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
return counts
|
||||
}, [definitions])
|
||||
|
||||
const ungroupedCount = useMemo(
|
||||
() => definitions.filter((d) => isDefinitionUngrouped(d.group_ids)).length,
|
||||
[definitions],
|
||||
)
|
||||
|
||||
const handleConfirmDeleteGroup = async () => {
|
||||
const row = groupPendingDelete
|
||||
if (!row) return
|
||||
setGroupDeleteSubmitting(true)
|
||||
try {
|
||||
await deleteQuestionTypeDefinitionGroup(row.id)
|
||||
toast.success("Group deleted. Membership links for this group were removed.")
|
||||
setGroupPendingDelete(null)
|
||||
if (groupFilter === row.id) setGroupFilter("all")
|
||||
await Promise.all([load(), loadGroups()])
|
||||
} catch (e) {
|
||||
toast.error(groupApiErrorMessage(e, "Delete failed"))
|
||||
} finally {
|
||||
setGroupDeleteSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openDeleteConfirm = (row: QuestionTypeDefinition) => {
|
||||
if (row.is_system) {
|
||||
toast.error("System definitions cannot be deleted.")
|
||||
|
|
@ -205,6 +293,144 @@ export function QuestionTypeLibraryPage() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
|
||||
<CardHeader
|
||||
className={cn(
|
||||
"px-6 py-5",
|
||||
groupsSectionOpen ? "border-b border-grayScale-100" : "",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-3 text-left"
|
||||
onClick={() => setGroupsSectionOpen((open) => !open)}
|
||||
aria-expanded={groupsSectionOpen}
|
||||
>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600">
|
||||
<FolderOpen className="h-5 w-5" aria-hidden />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<CardTitle className="text-base font-bold text-grayScale-900">Groups</CardTitle>
|
||||
{!groupsSectionOpen && !groupsLoading ? (
|
||||
<span className="rounded-full bg-grayScale-100 px-2 py-0.5 text-[11px] font-semibold text-grayScale-600">
|
||||
{groups.length} group{groups.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-xs text-grayScale-500 mt-0.5">
|
||||
{groupsSectionOpen
|
||||
? "Organize definitions by subject, skill, or workflow"
|
||||
: "Click to expand and manage groups"}
|
||||
</p>
|
||||
</div>
|
||||
{groupsSectionOpen ? (
|
||||
<ChevronUp className="h-5 w-5 shrink-0 text-grayScale-400" aria-hidden />
|
||||
) : (
|
||||
<ChevronDown className="h-5 w-5 shrink-0 text-grayScale-400" aria-hidden />
|
||||
)}
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 rounded-[8px] border-grayScale-200"
|
||||
onClick={() => {
|
||||
setGroupPendingEdit(null)
|
||||
setGroupFormOpen(true)
|
||||
}}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create group
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{groupsSectionOpen ? (
|
||||
<CardContent className="p-0">
|
||||
{groupsLoading ? (
|
||||
<div className="flex items-center justify-center gap-2 px-6 py-10 text-sm text-grayScale-500">
|
||||
<SpinnerIcon className="h-5 w-5 text-brand-500" />
|
||||
Loading groups…
|
||||
</div>
|
||||
) : groups.length === 0 ? (
|
||||
<div className="px-6 py-10 text-center text-sm text-grayScale-500">
|
||||
No groups yet. Create one to organize your question type catalog.
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-grayScale-100">
|
||||
{groups.map((g) => (
|
||||
<li
|
||||
key={g.id}
|
||||
className="flex flex-wrap items-center justify-between gap-3 px-6 py-4 hover:bg-grayScale-50/80"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-0 flex-1 text-left"
|
||||
onClick={() => navigate(`/new-content/question-types/groups/${g.id}`)}
|
||||
>
|
||||
<p className="font-semibold text-grayScale-900">{g.name}</p>
|
||||
<p className="mt-0.5 text-xs text-grayScale-500">
|
||||
{definitionCountByGroup.get(g.id) ?? 0} definition
|
||||
{(definitionCountByGroup.get(g.id) ?? 0) === 1 ? "" : "s"}
|
||||
{g.description ? ` · ${g.description}` : ""}
|
||||
</p>
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
className={cn(
|
||||
"border-none shadow-none text-[11px]",
|
||||
g.status === "ACTIVE"
|
||||
? "bg-[#F0FDF4] text-[#16A34A]"
|
||||
: "bg-grayScale-100 text-grayScale-600",
|
||||
)}
|
||||
>
|
||||
{g.status}
|
||||
</Badge>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => {
|
||||
setGroupFilter(g.id)
|
||||
resetPagination()
|
||||
}}
|
||||
>
|
||||
Filter
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={() => {
|
||||
setGroupPendingEdit(g)
|
||||
setGroupFormOpen(true)
|
||||
}}
|
||||
aria-label={`Edit ${g.name}`}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-grayScale-500 hover:text-red-600"
|
||||
onClick={() => setGroupPendingDelete(g)}
|
||||
aria-label={`Delete ${g.name}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
) : null}
|
||||
</Card>
|
||||
|
||||
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
|
||||
<CardHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
|
|
@ -225,7 +451,10 @@ export function QuestionTypeLibraryPage() {
|
|||
size="sm"
|
||||
className="rounded-[8px] border-grayScale-200"
|
||||
disabled={loading}
|
||||
onClick={() => void load()}
|
||||
onClick={() => {
|
||||
void load()
|
||||
void loadGroups()
|
||||
}}
|
||||
>
|
||||
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||
Refresh
|
||||
|
|
@ -299,6 +528,39 @@ export function QuestionTypeLibraryPage() {
|
|||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
Group
|
||||
</span>
|
||||
<FilterChip
|
||||
label="All groups"
|
||||
active={groupFilter === "all"}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setGroupFilter("all")
|
||||
resetPagination()
|
||||
}}
|
||||
/>
|
||||
<FilterChip
|
||||
label={`Ungrouped (${ungroupedCount})`}
|
||||
active={groupFilter === "ungrouped"}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setGroupFilter("ungrouped")
|
||||
resetPagination()
|
||||
}}
|
||||
/>
|
||||
{typeof groupFilter === "number" ? (
|
||||
<FilterChip
|
||||
label={questionTypeGroupLabel(groupFilter, groups)}
|
||||
active
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
navigate(`/new-content/question-types/groups/${groupFilter}`)
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
</div>
|
||||
|
|
@ -436,6 +698,49 @@ export function QuestionTypeLibraryPage() {
|
|||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<QuestionTypeGroupFormDialog
|
||||
open={groupFormOpen}
|
||||
onOpenChange={setGroupFormOpen}
|
||||
group={groupPendingEdit}
|
||||
onSaved={() => {
|
||||
void loadGroups()
|
||||
void load()
|
||||
}}
|
||||
/>
|
||||
|
||||
<Dialog
|
||||
open={groupPendingDelete !== null}
|
||||
onOpenChange={(open) => !groupDeleteSubmitting && !open && setGroupPendingDelete(null)}
|
||||
>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete group?</DialogTitle>
|
||||
<DialogDescription className="text-left">
|
||||
Deleting "{groupPendingDelete?.name}" will not delete any question types.
|
||||
Definitions will be removed from this group only; other group memberships are unchanged.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={groupDeleteSubmitting}
|
||||
onClick={() => setGroupPendingDelete(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={groupDeleteSubmitting}
|
||||
onClick={() => void handleConfirmDeleteGroup()}
|
||||
>
|
||||
{groupDeleteSubmitting ? <SpinnerIcon className="h-4 w-4" /> : "Delete group"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<QuestionTypeDefinitionPracticesDialog
|
||||
definition={definitionForPractices}
|
||||
open={definitionForPractices !== null}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,185 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
import { Textarea } from "../../../components/ui/textarea"
|
||||
import { Select } from "../../../components/ui/select"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import {
|
||||
createQuestionTypeDefinitionGroup,
|
||||
extractGroupMutationId,
|
||||
groupApiErrorMessage,
|
||||
updateQuestionTypeDefinitionGroup,
|
||||
} from "../../../api/questionTypeDefinitionGroups.api"
|
||||
import type {
|
||||
QuestionTypeDefinitionGroup,
|
||||
QuestionTypeDefinitionGroupStatus,
|
||||
} from "../../../types/questionTypeDefinition.types"
|
||||
|
||||
interface QuestionTypeGroupFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** When set, dialog edits this group; otherwise creates a new one */
|
||||
group?: QuestionTypeDefinitionGroup | null
|
||||
onSaved?: (group: QuestionTypeDefinitionGroup) => void
|
||||
}
|
||||
|
||||
export function QuestionTypeGroupFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
group,
|
||||
onSaved,
|
||||
}: QuestionTypeGroupFormDialogProps) {
|
||||
const isEdit = group != null
|
||||
const [name, setName] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [displayOrder, setDisplayOrder] = useState("0")
|
||||
const [status, setStatus] = useState<QuestionTypeDefinitionGroupStatus>("ACTIVE")
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (group) {
|
||||
setName(group.name)
|
||||
setDescription(group.description ?? "")
|
||||
setDisplayOrder(String(group.display_order))
|
||||
setStatus(group.status)
|
||||
} else {
|
||||
setName("")
|
||||
setDescription("")
|
||||
setDisplayOrder("0")
|
||||
setStatus("ACTIVE")
|
||||
}
|
||||
}, [open, group])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const trimmedName = name.trim()
|
||||
if (!trimmedName) {
|
||||
toast.error("Group name is required")
|
||||
return
|
||||
}
|
||||
const order = Number(displayOrder)
|
||||
const body = {
|
||||
name: trimmedName,
|
||||
description: description.trim() || null,
|
||||
display_order: Number.isFinite(order) ? order : 0,
|
||||
status,
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
if (isEdit && group) {
|
||||
const res = await updateQuestionTypeDefinitionGroup(group.id, body)
|
||||
toast.success(res.data?.message || "Group updated")
|
||||
onSaved?.({ ...group, ...body })
|
||||
} else {
|
||||
const res = await createQuestionTypeDefinitionGroup(body)
|
||||
const id = extractGroupMutationId(res)
|
||||
toast.success(res.data?.message || "Group created")
|
||||
if (id != null) {
|
||||
onSaved?.({
|
||||
id,
|
||||
name: body.name,
|
||||
description: body.description ?? null,
|
||||
display_order: body.display_order ?? 0,
|
||||
status: body.status ?? "ACTIVE",
|
||||
created_at: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
}
|
||||
onOpenChange(false)
|
||||
} catch (e) {
|
||||
toast.error(groupApiErrorMessage(e, isEdit ? "Update failed" : "Create failed"))
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? "Edit group" : "Create group"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Groups organize question type definitions in the catalog. Deleting a group does not delete
|
||||
definitions.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">
|
||||
Name <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Speaking & Listening"
|
||||
className="h-10"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">Description</label>
|
||||
<Textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Optional description for admins"
|
||||
className="min-h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">Display order</label>
|
||||
<Input
|
||||
type="number"
|
||||
value={displayOrder}
|
||||
onChange={(e) => setDisplayOrder(e.target.value)}
|
||||
className="h-10"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">Status</label>
|
||||
<Select
|
||||
className="h-10"
|
||||
value={status}
|
||||
onChange={(e) =>
|
||||
setStatus(e.target.value === "INACTIVE" ? "INACTIVE" : "ACTIVE")
|
||||
}
|
||||
>
|
||||
<option value="ACTIVE">Active</option>
|
||||
<option value="INACTIVE">Inactive</option>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={submitting}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="bg-[#9E2891] hover:bg-[#8A237E] text-white"
|
||||
disabled={submitting}
|
||||
onClick={() => void handleSubmit()}
|
||||
>
|
||||
{submitting ? <SpinnerIcon className="h-4 w-4" /> : isEdit ? "Save changes" : "Create group"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { getQuestionTypeDefinitionGroups } from "../../../api/questionTypeDefinitionGroups.api"
|
||||
import type { QuestionTypeDefinitionGroup } from "../../../types/questionTypeDefinition.types"
|
||||
import { normalizeGroupIds, questionTypeGroupLabels } from "../../../lib/questionTypeGroupIds"
|
||||
import { cn } from "../../../lib/utils"
|
||||
|
||||
interface QuestionTypeGroupsMultiSelectProps {
|
||||
value: number[] | null
|
||||
onChange: (groupIds: number[] | null) => void
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
/** When true, only ACTIVE groups are listed */
|
||||
activeOnly?: boolean
|
||||
}
|
||||
|
||||
export function QuestionTypeGroupsMultiSelect({
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
className,
|
||||
activeOnly = true,
|
||||
}: QuestionTypeGroupsMultiSelectProps) {
|
||||
const [groups, setGroups] = useState<QuestionTypeDefinitionGroup[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const selected = new Set(value ?? [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
getQuestionTypeDefinitionGroups(activeOnly ? { status: "ACTIVE" } : undefined)
|
||||
.then((res) => {
|
||||
if (!cancelled) setGroups(res.groups)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setGroups([])
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [activeOnly])
|
||||
|
||||
const toggle = (groupId: number) => {
|
||||
const current = value ?? []
|
||||
const next = current.includes(groupId)
|
||||
? current.filter((id) => id !== groupId)
|
||||
: [...current, groupId]
|
||||
onChange(normalizeGroupIds(next))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
<div
|
||||
className={cn(
|
||||
"max-h-48 space-y-1 overflow-y-auto rounded-[12px] border border-grayScale-300 bg-[#F8FAFC] p-3",
|
||||
disabled && "opacity-70",
|
||||
)}
|
||||
>
|
||||
{loading ? (
|
||||
<p className="text-sm text-grayScale-500">Loading groups…</p>
|
||||
) : groups.length === 0 ? (
|
||||
<p className="text-sm text-grayScale-500">No groups yet. Create one from the library page.</p>
|
||||
) : (
|
||||
groups.map((g) => (
|
||||
<label
|
||||
key={g.id}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-grayScale-800 hover:bg-white",
|
||||
disabled && "cursor-not-allowed",
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-grayScale-300 text-brand-600 focus:ring-brand-500"
|
||||
checked={selected.has(g.id)}
|
||||
disabled={disabled || loading}
|
||||
onChange={() => toggle(g.id)}
|
||||
/>
|
||||
<span className="font-medium">{g.name}</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{loading ? (
|
||||
<SpinnerIcon className="pointer-events-none absolute right-3 top-3 h-4 w-4 text-grayScale-400" />
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** @deprecated Use QuestionTypeGroupsMultiSelect */
|
||||
export const QuestionTypeGroupSelect = QuestionTypeGroupsMultiSelect
|
||||
|
||||
export function questionTypeGroupLabel(
|
||||
groupId: number | null | undefined,
|
||||
groups: QuestionTypeDefinitionGroup[],
|
||||
): string {
|
||||
if (groupId == null) return "Ungrouped"
|
||||
return questionTypeGroupLabels([groupId], groups)
|
||||
}
|
||||
|
|
@ -1,17 +1,18 @@
|
|||
import { ArrowRight } from "lucide-react"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
import { Card } from "../../../../components/ui/card"
|
||||
import { Input } from "../../../../components/ui/input"
|
||||
import { Textarea } from "../../../../components/ui/textarea"
|
||||
import { Select } from "../../../../components/ui/select"
|
||||
import type { QuestionTypeDefinitionCreatePayload } from "../../../../types/questionTypeDefinition.types"
|
||||
import type { FieldErrorMap } from "../../lib/questionTypeDefinitionValidation"
|
||||
import { QuestionTypeGroupsMultiSelect } from "../QuestionTypeGroupSelect"
|
||||
import { QuestionTypeStepFooter } from "./QuestionTypeStepFooter"
|
||||
|
||||
interface QuestionTypeBasicInfoStepProps {
|
||||
draft: QuestionTypeDefinitionCreatePayload
|
||||
setDraft: React.Dispatch<React.SetStateAction<QuestionTypeDefinitionCreatePayload>>
|
||||
errors: FieldErrorMap
|
||||
onNext: () => void
|
||||
saving?: boolean
|
||||
/** When editing an existing definition, the key is immutable on the server */
|
||||
keyReadOnly?: boolean
|
||||
}
|
||||
|
|
@ -21,6 +22,7 @@ export function QuestionTypeBasicInfoStep({
|
|||
setDraft,
|
||||
errors,
|
||||
onNext,
|
||||
saving,
|
||||
keyReadOnly,
|
||||
}: QuestionTypeBasicInfoStepProps) {
|
||||
return (
|
||||
|
|
@ -80,6 +82,17 @@ export function QuestionTypeBasicInfoStep({
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-w-md">
|
||||
<label className="text-[14px] font-medium text-grayScale-700">Groups</label>
|
||||
<QuestionTypeGroupsMultiSelect
|
||||
value={draft.group_ids ?? null}
|
||||
onChange={(groupIds) => setDraft((d) => ({ ...d, group_ids: groupIds }))}
|
||||
/>
|
||||
<p className="text-grayScale-400 text-[13px] font-medium">
|
||||
Optional catalog groups for organizing this definition in the library.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-w-xs">
|
||||
<label className="text-[14px] font-medium text-grayScale-700 flex items-center gap-1">
|
||||
Status <span className="text-red-500">*</span>
|
||||
|
|
@ -100,16 +113,11 @@ export function QuestionTypeBasicInfoStep({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-4 border border-grayScale-200 flex items-center justify-end bg-[#F8FAFC]">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onNext}
|
||||
className="h-10 px-10 rounded-[6px] bg-[#9E2891] font-medium text-white shadow-lg shadow-brand-500/10 hover:bg-[#8A237E] transition-all flex items-center gap-3"
|
||||
>
|
||||
Next: Input and answer types
|
||||
<ArrowRight className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
<QuestionTypeStepFooter
|
||||
onNext={onNext}
|
||||
nextLabel="Next: Input and answer types"
|
||||
saving={saving}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useState } from "react"
|
||||
import { ArrowLeft, ArrowRight, ChevronDown, ChevronUp, Minus, Plus } from "lucide-react"
|
||||
import { ChevronDown, ChevronUp, Minus, Plus } from "lucide-react"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
import { Card } from "../../../../components/ui/card"
|
||||
import { Input } from "../../../../components/ui/input"
|
||||
|
|
@ -20,6 +20,7 @@ import {
|
|||
isNoInputComponentKind,
|
||||
noInputSchemaRow,
|
||||
} from "../../../../lib/questionComponentKinds"
|
||||
import { QuestionTypeStepFooter } from "./QuestionTypeStepFooter"
|
||||
|
||||
interface QuestionTypeConfigStepProps {
|
||||
draft: QuestionTypeDefinitionCreatePayload
|
||||
|
|
@ -31,6 +32,7 @@ interface QuestionTypeConfigStepProps {
|
|||
errors: FieldErrorMap
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
saving?: boolean
|
||||
}
|
||||
|
||||
function slugFragmentFromKind(kind: string): string {
|
||||
|
|
@ -88,6 +90,7 @@ export function QuestionTypeConfigStep({
|
|||
errors,
|
||||
onNext,
|
||||
onBack,
|
||||
saving,
|
||||
}: QuestionTypeConfigStepProps) {
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false)
|
||||
|
||||
|
|
@ -433,25 +436,12 @@ export function QuestionTypeConfigStep({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-4 border-t border-grayScale-200 flex items-center justify-between bg-[#F8FAFC]">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-10 px-6 rounded-[6px] border-none shadow-none text-grayScale-600 font-bold hover:bg-grayScale-100"
|
||||
onClick={onBack}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2 inline" />
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onNext}
|
||||
className="h-10 px-10 rounded-[6px] bg-[#9E2891] font-medium text-white shadow-lg shadow-brand-500/10 hover:bg-[#8A237E] transition-all flex items-center gap-3"
|
||||
>
|
||||
Next: Validate
|
||||
<ArrowRight className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
<QuestionTypeStepFooter
|
||||
onBack={onBack}
|
||||
onNext={onNext}
|
||||
nextLabel="Next: Validate"
|
||||
saving={saving}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useState } from "react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { ArrowLeft, Loader2 } from "lucide-react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
|
@ -10,6 +10,7 @@ import {
|
|||
updateQuestionTypeDefinition,
|
||||
validateQuestionTypeDefinition,
|
||||
} from "../../../../api/questionTypeDefinitions.api"
|
||||
import { getQuestionTypeDefinitionGroups } from "../../../../api/questionTypeDefinitionGroups.api"
|
||||
import type { QuestionTypeDefinitionCreatePayload } from "../../../../types/questionTypeDefinition.types"
|
||||
import {
|
||||
buildCreatePayload,
|
||||
|
|
@ -17,6 +18,7 @@ import {
|
|||
inferRuntimeQuestionType,
|
||||
} from "../../lib/questionTypeDefinitionValidation"
|
||||
import { slotLabel } from "./componentKindUi"
|
||||
import { questionTypeGroupLabels } from "../../../../lib/questionTypeGroupIds"
|
||||
|
||||
interface QuestionTypeReviewPublishStepProps {
|
||||
draft: QuestionTypeDefinitionCreatePayload
|
||||
|
|
@ -24,6 +26,7 @@ interface QuestionTypeReviewPublishStepProps {
|
|||
/** When set, saves via PUT /questions/type-definitions/:id */
|
||||
editDefinitionId?: number | null
|
||||
isSystem?: boolean
|
||||
saveDisabled?: boolean
|
||||
}
|
||||
|
||||
export function QuestionTypeReviewPublishStep({
|
||||
|
|
@ -31,15 +34,32 @@ export function QuestionTypeReviewPublishStep({
|
|||
onBack,
|
||||
editDefinitionId,
|
||||
isSystem,
|
||||
saveDisabled = false,
|
||||
}: QuestionTypeReviewPublishStepProps) {
|
||||
const navigate = useNavigate()
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [groupName, setGroupName] = useState<string>("")
|
||||
const isEdit = editDefinitionId != null && editDefinitionId > 0
|
||||
|
||||
const payload = buildCreatePayload(draft)
|
||||
const runtime = inferRuntimeQuestionType(payload.key, payload.response_component_kinds)
|
||||
|
||||
useEffect(() => {
|
||||
if (!payload.group_ids?.length) {
|
||||
setGroupName("Ungrouped")
|
||||
return
|
||||
}
|
||||
getQuestionTypeDefinitionGroups()
|
||||
.then((res) => {
|
||||
setGroupName(questionTypeGroupLabels(payload.group_ids, res.groups))
|
||||
})
|
||||
.catch(() => {
|
||||
setGroupName(payload.group_ids!.map((id) => `Group #${id}`).join(", "))
|
||||
})
|
||||
}, [payload.group_ids])
|
||||
|
||||
const submit = async (status: "ACTIVE" | "INACTIVE") => {
|
||||
if (isEdit && saveDisabled) return
|
||||
const body = { ...payload, status }
|
||||
setSubmitting(true)
|
||||
try {
|
||||
|
|
@ -117,6 +137,10 @@ export function QuestionTypeReviewPublishStep({
|
|||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Description</dt>
|
||||
<dd className="font-medium text-grayScale-800 mt-1">{payload.description || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Groups</dt>
|
||||
<dd className="font-medium text-grayScale-900 mt-1">{groupName || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-grayScale-400 font-semibold uppercase text-[11px] tracking-wide">Status</dt>
|
||||
<dd className="font-medium text-grayScale-900 mt-1">{draft.status}</dd>
|
||||
|
|
@ -145,7 +169,7 @@ export function QuestionTypeReviewPublishStep({
|
|||
type="button"
|
||||
variant="outline"
|
||||
className="h-11"
|
||||
disabled={submitting}
|
||||
disabled={submitting || (isEdit && saveDisabled)}
|
||||
onClick={() => void submit("INACTIVE")}
|
||||
>
|
||||
{submitting ? (
|
||||
|
|
@ -159,7 +183,7 @@ export function QuestionTypeReviewPublishStep({
|
|||
<Button
|
||||
type="button"
|
||||
className="h-11 bg-[#9E2891] hover:bg-[#8A237E] text-white"
|
||||
disabled={submitting}
|
||||
disabled={submitting || (isEdit && saveDisabled)}
|
||||
onClick={() => void submit("ACTIVE")}
|
||||
>
|
||||
{submitting ? (
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
|
||||
interface QuestionTypeStepFooterProps {
|
||||
onNext: () => void
|
||||
nextLabel: string
|
||||
onBack?: () => void
|
||||
saving?: boolean
|
||||
nextDisabled?: boolean
|
||||
}
|
||||
|
||||
export function QuestionTypeStepFooter({
|
||||
onNext,
|
||||
nextLabel,
|
||||
onBack,
|
||||
saving = false,
|
||||
nextDisabled = false,
|
||||
}: QuestionTypeStepFooterProps) {
|
||||
return (
|
||||
<div className="px-4 py-4 border border-grayScale-200 flex flex-wrap items-center justify-between gap-3 bg-[#F8FAFC]">
|
||||
<div className="flex items-center gap-2">
|
||||
{onBack ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-10 px-6 rounded-[6px] border-none shadow-none text-grayScale-600 font-bold hover:bg-grayScale-100"
|
||||
onClick={onBack}
|
||||
disabled={saving}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2 inline" />
|
||||
Back
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onNext}
|
||||
disabled={saving || nextDisabled}
|
||||
className="h-10 px-10 rounded-[6px] bg-[#9E2891] font-medium text-white shadow-lg shadow-brand-500/10 hover:bg-[#8A237E] disabled:opacity-50 transition-all flex items-center gap-3"
|
||||
>
|
||||
{nextLabel}
|
||||
<ArrowRight className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { ArrowLeft, ArrowRight, CheckCircle2, Loader2 } from "lucide-react"
|
||||
import { CheckCircle2, Loader2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
import { Card } from "../../../../components/ui/card"
|
||||
|
|
@ -10,17 +10,20 @@ import {
|
|||
buildValidateKindsPayload,
|
||||
} from "../../lib/questionTypeDefinitionValidation"
|
||||
import { DefinitionRuntimeHint } from "./DefinitionRuntimeHint"
|
||||
import { QuestionTypeStepFooter } from "./QuestionTypeStepFooter"
|
||||
|
||||
interface QuestionTypeValidatePreviewStepProps {
|
||||
draft: QuestionTypeDefinitionCreatePayload
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
saving?: boolean
|
||||
}
|
||||
|
||||
export function QuestionTypeValidatePreviewStep({
|
||||
draft,
|
||||
onNext,
|
||||
onBack,
|
||||
saving,
|
||||
}: QuestionTypeValidatePreviewStepProps) {
|
||||
const [validating, setValidating] = useState(false)
|
||||
const [serverOk, setServerOk] = useState<boolean | null>(null)
|
||||
|
|
@ -152,26 +155,13 @@ export function QuestionTypeValidatePreviewStep({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-4 border border-grayScale-200 flex items-center justify-between bg-[#F8FAFC]">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-10 px-6 rounded-[6px] border-none shadow-none text-grayScale-600 font-bold hover:bg-grayScale-100"
|
||||
onClick={onBack}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2 inline" />
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleNext}
|
||||
disabled={validating || serverOk !== true}
|
||||
className="h-10 px-10 rounded-[6px] bg-[#9E2891] font-medium text-white shadow-lg shadow-brand-500/10 hover:bg-[#8A237E] disabled:opacity-50 transition-all flex items-center gap-3"
|
||||
>
|
||||
Next: Review & publish
|
||||
<ArrowRight className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
<QuestionTypeStepFooter
|
||||
onBack={onBack}
|
||||
onNext={handleNext}
|
||||
nextLabel="Next: Review & publish"
|
||||
saving={saving}
|
||||
nextDisabled={validating || serverOk !== true}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
sideIsNoInputOnly,
|
||||
noInputSchemaRow,
|
||||
} from "../../../lib/questionComponentKinds"
|
||||
import { normalizeGroupIds } from "../../../lib/questionTypeGroupIds"
|
||||
|
||||
export type FieldErrorMap = Record<string, string>
|
||||
|
||||
|
|
@ -265,6 +266,7 @@ export function buildCreatePayload(
|
|||
key: draft.key.trim(),
|
||||
display_name: draft.display_name.trim(),
|
||||
description: draft.description?.trim() || null,
|
||||
group_ids: normalizeGroupIds(draft.group_ids),
|
||||
stimulus_component_kinds:
|
||||
stimulusKindsFromSchema.length > 0 ? stimulusKindsFromSchema : [...draft.stimulus_component_kinds],
|
||||
response_component_kinds:
|
||||
|
|
@ -273,3 +275,56 @@ export function buildCreatePayload(
|
|||
response_schema: finalResponseSchema,
|
||||
}
|
||||
}
|
||||
|
||||
function seedSchemaFromKinds(kinds: string[]): DynamicElementDefinition[] {
|
||||
return kinds.map((k, i) => ({
|
||||
id: `${(k || "field").toLowerCase().replace(/[^a-z0-9]+/g, "_") || "field"}_${i + 1}`,
|
||||
kind: k,
|
||||
label: defaultLabelForKind(k),
|
||||
required: true,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Fills empty schema arrays from selected kinds before validation or save. */
|
||||
export function seedSchemasFromKindsIfEmpty(
|
||||
draft: QuestionTypeDefinitionCreatePayload,
|
||||
): QuestionTypeDefinitionCreatePayload {
|
||||
const next = { ...draft }
|
||||
if (!next.stimulus_schema.length && sideIsNoInputOnly(next.stimulus_component_kinds)) {
|
||||
next.stimulus_schema = [noInputSchemaRow()]
|
||||
} else if (!next.stimulus_schema.length && next.stimulus_component_kinds.length) {
|
||||
next.stimulus_schema = seedSchemaFromKinds(next.stimulus_component_kinds)
|
||||
}
|
||||
if (!next.response_schema.length && sideIsNoInputOnly(next.response_component_kinds)) {
|
||||
next.response_schema = [noInputSchemaRow()]
|
||||
} else if (!next.response_schema.length && next.response_component_kinds.length) {
|
||||
next.response_schema = seedSchemaFromKinds(next.response_component_kinds)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/** Validates fields required through the given wizard step (1 = basics only). */
|
||||
export function validateDefinitionThroughStep(
|
||||
step: number,
|
||||
draft: QuestionTypeDefinitionCreatePayload,
|
||||
catalog: QuestionComponentCatalog,
|
||||
catalogForSchema: { stimulus: Set<string>; response: Set<string> },
|
||||
): FieldErrorMap {
|
||||
const errors = validateDefinitionBasic(draft)
|
||||
if (step < 2) return errors
|
||||
|
||||
Object.assign(errors, validateDefinitionKinds(draft, catalog))
|
||||
const prepared = seedSchemasFromKindsIfEmpty(draft)
|
||||
Object.assign(errors, validateDefinitionSchemas(prepared, catalogForSchema))
|
||||
return errors
|
||||
}
|
||||
|
||||
/** Compares drafts by normalized API payload (ignores inconsequential ordering). */
|
||||
export function areDefinitionDraftsEqual(
|
||||
a: QuestionTypeDefinitionCreatePayload,
|
||||
b: QuestionTypeDefinitionCreatePayload,
|
||||
): boolean {
|
||||
const fingerprint = (draft: QuestionTypeDefinitionCreatePayload) =>
|
||||
JSON.stringify(buildCreatePayload(seedSchemasFromKindsIfEmpty(draft)))
|
||||
return fingerprint(a) === fingerprint(b)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export interface QuestionTypeDefinitionCreatePayload {
|
|||
key: string
|
||||
display_name: string
|
||||
description?: string | null
|
||||
group_ids?: number[] | null
|
||||
stimulus_component_kinds: string[]
|
||||
response_component_kinds: string[]
|
||||
stimulus_schema: DynamicElementDefinition[]
|
||||
|
|
@ -42,6 +43,7 @@ export type ValidateQuestionTypeDefinitionResult =
|
|||
|
||||
export interface QuestionTypeDefinition extends QuestionTypeDefinitionCreatePayload {
|
||||
id: number
|
||||
group_ids: number[] | null
|
||||
is_system?: boolean
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
|
|
@ -96,3 +98,42 @@ export interface QuestionTypeDefinitionPracticesResult {
|
|||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export type QuestionTypeDefinitionGroupStatus = "ACTIVE" | "INACTIVE"
|
||||
|
||||
export interface QuestionTypeDefinitionGroup {
|
||||
id: number
|
||||
name: string
|
||||
description: string | null
|
||||
display_order: number
|
||||
status: QuestionTypeDefinitionGroupStatus
|
||||
created_at: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface QuestionTypeDefinitionGroupDetail extends QuestionTypeDefinitionGroup {
|
||||
definitions: QuestionTypeDefinition[]
|
||||
}
|
||||
|
||||
export interface QuestionTypeDefinitionGroupCreatePayload {
|
||||
name: string
|
||||
description?: string | null
|
||||
display_order?: number
|
||||
status?: QuestionTypeDefinitionGroupStatus
|
||||
}
|
||||
|
||||
export type QuestionTypeDefinitionGroupUpdatePayload =
|
||||
Partial<QuestionTypeDefinitionGroupCreatePayload>
|
||||
|
||||
export interface QuestionTypeDefinitionGroupsListParams {
|
||||
status?: QuestionTypeDefinitionGroupStatus
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export interface QuestionTypeDefinitionGroupsListResult {
|
||||
groups: QuestionTypeDefinitionGroup[]
|
||||
total_count: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user