Add attach-practice flow, nullable parents, and practice UX improvements.
Support linking existing practices from course/module/lesson pages with client-side search, a full-page attach wizard, and titled parent summaries on review. Extend practice creation for question-type shells, multi-parent APIs, and layout fixes across admin flows. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
1915d89bc3
commit
ad75a06284
|
|
@ -105,6 +105,8 @@ import type {
|
|||
GetExamPrepModuleLessonsResponse,
|
||||
GetTopLevelModuleLessonsResponse,
|
||||
GetPracticesByParentContextResponse,
|
||||
GetPracticesListParams,
|
||||
GetPracticesListResponse,
|
||||
CreateParentLinkedPracticeRequest,
|
||||
CreateParentLinkedPracticeResponse,
|
||||
UpdateParentLinkedPracticeRequest,
|
||||
|
|
@ -112,6 +114,8 @@ import type {
|
|||
UpdatePracticeFullRequest,
|
||||
UpdatePracticeFullResponse,
|
||||
UpdateParentLinkedPracticeResponse,
|
||||
UpdatePracticeParentsRequest,
|
||||
UpdatePracticeParentsResponse,
|
||||
PublishParentLinkedPracticeRequest,
|
||||
PublishStatusOnlyRequest,
|
||||
AccessTierOnlyRequest,
|
||||
|
|
@ -839,10 +843,20 @@ export const getPracticesByParentLesson = (
|
|||
) =>
|
||||
http.get<GetPracticesByParentContextResponse>(`/lessons/${lessonId}/practices`, { params })
|
||||
|
||||
/** GET /practices — list all practices (for attach-existing flow). */
|
||||
export const getPractices = (params?: GetPracticesListParams) =>
|
||||
http.get<GetPracticesListResponse>("/practices", { params })
|
||||
|
||||
/** POST /practices — create a practice (story + question set) for course / module / lesson. */
|
||||
export const createParentLinkedPractice = (data: CreateParentLinkedPracticeRequest) =>
|
||||
http.post<CreateParentLinkedPracticeResponse>("/practices", data)
|
||||
|
||||
/** PUT /practices/:id/parents — replace all parent links on a practice. */
|
||||
export const updatePracticeParents = (
|
||||
practiceId: number,
|
||||
data: UpdatePracticeParentsRequest,
|
||||
) => http.put<UpdatePracticeParentsResponse>(`/practices/${practiceId}/parents`, data)
|
||||
|
||||
/** PUT /practices/:id */
|
||||
export const updateParentLinkedPractice = (
|
||||
practiceId: number,
|
||||
|
|
|
|||
|
|
@ -4,10 +4,14 @@ import type {
|
|||
QuestionComponentCatalog,
|
||||
QuestionTypeDefinition,
|
||||
QuestionTypeDefinitionCreatePayload,
|
||||
QuestionTypeDefinitionPractice,
|
||||
QuestionTypeDefinitionPracticesParams,
|
||||
QuestionTypeDefinitionPracticesResult,
|
||||
QuestionTypeDefinitionUpdatePayload,
|
||||
QuestionTypeDefinitionValidatePayload,
|
||||
ValidateQuestionTypeDefinitionResult,
|
||||
} from "../types/questionTypeDefinition.types"
|
||||
import { normalizePracticeParents, parentsFromPractice } from "../lib/practiceParents"
|
||||
|
||||
interface ApiEnvelope<T> {
|
||||
message?: string
|
||||
|
|
@ -408,3 +412,172 @@ export async function updateQuestionTypeDefinition(
|
|||
export async function deleteQuestionTypeDefinition(id: number) {
|
||||
return http.delete<ApiEnvelope<unknown>>(`/questions/type-definitions/${id}`)
|
||||
}
|
||||
|
||||
function normalizePracticeFromApi(row: unknown): QuestionTypeDefinitionPractice | null {
|
||||
if (!row || typeof row !== "object") return null
|
||||
const o = row as Record<string, unknown>
|
||||
const practice_id = Number(o.practice_id ?? o.PracticeId ?? o.practiceId ?? o.id ?? o.ID)
|
||||
const question_set_id = Number(o.question_set_id ?? o.QuestionSetId ?? o.questionSetId)
|
||||
if (!Number.isFinite(practice_id) || practice_id <= 0) return null
|
||||
if (!Number.isFinite(question_set_id) || question_set_id <= 0) return null
|
||||
|
||||
const matching_question_count = Number(
|
||||
o.matching_question_count ?? o.MatchingQuestionCount ?? o.matchingQuestionCount ?? 0,
|
||||
)
|
||||
const parentObj =
|
||||
o.parent != null && typeof o.parent === "object" && !Array.isArray(o.parent)
|
||||
? (o.parent as Record<string, unknown>)
|
||||
: o.Parent != null && typeof o.Parent === "object" && !Array.isArray(o.Parent)
|
||||
? (o.Parent as Record<string, unknown>)
|
||||
: null
|
||||
|
||||
const parent_idRaw =
|
||||
o.parent_id ??
|
||||
o.ParentId ??
|
||||
o.parentId ??
|
||||
parentObj?.id ??
|
||||
parentObj?.Id ??
|
||||
parentObj?.ID
|
||||
const parent_id =
|
||||
parent_idRaw != null && Number.isFinite(Number(parent_idRaw)) ? Number(parent_idRaw) : undefined
|
||||
|
||||
const parent_kind =
|
||||
asStr(o.parent_kind ?? o.ParentKind ?? o.parentKind) ||
|
||||
(parentObj ? asStr(parentObj.kind ?? parentObj.Kind) : "") ||
|
||||
undefined
|
||||
|
||||
const program_id = Number(o.program_id ?? o.ProgramId ?? o.programId)
|
||||
const course_id = Number(o.course_id ?? o.CourseId ?? o.courseId)
|
||||
const module_id = Number(o.module_id ?? o.ModuleId ?? o.moduleId)
|
||||
const lesson_id = Number(o.lesson_id ?? o.LessonId ?? o.lessonId)
|
||||
const parents = parentsFromPractice({
|
||||
parents: normalizePracticeParents(row),
|
||||
parent_kind,
|
||||
parent_id,
|
||||
})
|
||||
|
||||
return {
|
||||
practice_kind: asStr(o.practice_kind ?? o.PracticeKind ?? o.practiceKind ?? "LMS"),
|
||||
practice_id,
|
||||
question_set_id,
|
||||
title: asStr(o.title ?? o.Title) || `Practice #${practice_id}`,
|
||||
story_description:
|
||||
o.story_description != null
|
||||
? asStr(o.story_description)
|
||||
: o.StoryDescription != null
|
||||
? asStr(o.StoryDescription)
|
||||
: undefined,
|
||||
story_image:
|
||||
o.story_image != null
|
||||
? asStr(o.story_image)
|
||||
: o.StoryImage != null
|
||||
? asStr(o.StoryImage)
|
||||
: undefined,
|
||||
quick_tips:
|
||||
o.quick_tips != null
|
||||
? asStr(o.quick_tips)
|
||||
: o.QuickTips != null
|
||||
? asStr(o.QuickTips)
|
||||
: undefined,
|
||||
publish_status: asStr(o.publish_status ?? o.PublishStatus ?? o.publishStatus) || undefined,
|
||||
parents,
|
||||
parent_kind: parents[0]?.parent_kind,
|
||||
parent_id: parents[0]?.parent_id,
|
||||
program_id: Number.isFinite(program_id) && program_id > 0 ? program_id : undefined,
|
||||
course_id: Number.isFinite(course_id) && course_id > 0 ? course_id : undefined,
|
||||
module_id: Number.isFinite(module_id) && module_id > 0 ? module_id : undefined,
|
||||
lesson_id: Number.isFinite(lesson_id) && lesson_id > 0 ? lesson_id : undefined,
|
||||
matching_question_count: Number.isFinite(matching_question_count) ? matching_question_count : 0,
|
||||
created_at:
|
||||
o.created_at != null
|
||||
? asStr(o.created_at)
|
||||
: o.CreatedAt != null
|
||||
? asStr(o.CreatedAt)
|
||||
: undefined,
|
||||
updated_at:
|
||||
o.updated_at != null
|
||||
? asStr(o.updated_at)
|
||||
: o.UpdatedAt != null
|
||||
? asStr(o.UpdatedAt)
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function parsePracticesList(payload: unknown): QuestionTypeDefinitionPractice[] {
|
||||
if (!payload) return []
|
||||
if (Array.isArray(payload)) {
|
||||
return payload
|
||||
.map((item) => normalizePracticeFromApi(item))
|
||||
.filter((x): x is QuestionTypeDefinitionPractice => x != null)
|
||||
}
|
||||
if (typeof payload === "object" && payload !== null) {
|
||||
const o = payload as Record<string, unknown>
|
||||
const inner = o.practices ?? o.Practices
|
||||
if (Array.isArray(inner)) return parsePracticesList(inner)
|
||||
const data = o.data ?? o.Data
|
||||
if (data && typeof data === "object") return parsePracticesList(data)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function parsePracticesPage(
|
||||
payload: unknown,
|
||||
definitionId: number,
|
||||
params?: QuestionTypeDefinitionPracticesParams,
|
||||
): QuestionTypeDefinitionPracticesResult {
|
||||
const practices = parsePracticesList(payload)
|
||||
const limit = params?.limit ?? 20
|
||||
const offset = params?.offset ?? 0
|
||||
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
||||
return {
|
||||
question_type_definition_id: definitionId,
|
||||
practices,
|
||||
total_count: practices.length,
|
||||
limit,
|
||||
offset,
|
||||
}
|
||||
}
|
||||
|
||||
const o = payload as Record<string, unknown>
|
||||
const data =
|
||||
o.data != null && typeof o.data === "object" && !Array.isArray(o.data)
|
||||
? (o.data as Record<string, unknown>)
|
||||
: o
|
||||
|
||||
const question_type_definition_id = Number(
|
||||
data.question_type_definition_id ??
|
||||
data.QuestionTypeDefinitionId ??
|
||||
data.questionTypeDefinitionId ??
|
||||
definitionId,
|
||||
)
|
||||
const total_count = parseListTotalCount(data) ?? parseListTotalCount(payload) ?? practices.length
|
||||
const parsedLimit = Number(data.limit ?? data.Limit ?? limit)
|
||||
const parsedOffset = Number(data.offset ?? data.Offset ?? offset)
|
||||
|
||||
return {
|
||||
question_type_definition_id:
|
||||
Number.isFinite(question_type_definition_id) && question_type_definition_id > 0
|
||||
? question_type_definition_id
|
||||
: definitionId,
|
||||
practices,
|
||||
total_count,
|
||||
limit: Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : limit,
|
||||
offset: Number.isFinite(parsedOffset) && parsedOffset >= 0 ? parsedOffset : offset,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /questions/type-definitions/:id/practices
|
||||
* Lists LMS practices that contain questions using this definition.
|
||||
*/
|
||||
export async function getQuestionTypeDefinitionPractices(
|
||||
definitionId: number,
|
||||
params?: QuestionTypeDefinitionPracticesParams,
|
||||
): Promise<QuestionTypeDefinitionPracticesResult> {
|
||||
const res = await http.get<ApiEnvelope<unknown>>(`/questions/type-definitions/${definitionId}/practices`, {
|
||||
params,
|
||||
})
|
||||
const raw = unwrapApiPayload(res) ?? res.data
|
||||
return parsePracticesPage(raw, definitionId, params)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import { LessonPracticesPage } from "../pages/content-management/LessonPractices
|
|||
import { ModuleDetailPage } from "../pages/content-management/ModuleDetailPage";
|
||||
import { AddVideoFlow } from "../pages/content-management/AddVideoFlow";
|
||||
import { AddPracticeFlow } from "../pages/content-management/AddPracticeFlow";
|
||||
import { LinkExistingPracticeFlow } from "../pages/content-management/LinkExistingPracticeFlow";
|
||||
import { EditPracticeFlow } from "../pages/content-management/EditPracticeFlow";
|
||||
import { CourseModuleDetailPage } from "../pages/content-management/CourseModuleDetailPage";
|
||||
import { ProgramTypeSelectionPage } from "../pages/content-management/ProgramTypeSelectionPage";
|
||||
|
|
@ -182,6 +183,10 @@ export function AppRoutes() {
|
|||
path="/new-content/question-types"
|
||||
element={<QuestionTypeLibraryPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/question-types/:definitionId/create-practice"
|
||||
element={<AddPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/question-types/:definitionId/edit"
|
||||
element={<CreateQuestionTypeFlow />}
|
||||
|
|
@ -198,14 +203,26 @@ export function AppRoutes() {
|
|||
path="/new-content/courses/:programType/add-practice"
|
||||
element={<AddPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/courses/:programType/attach-practice"
|
||||
element={<LinkExistingPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/courses/:programType/:courseId/add-practice"
|
||||
element={<AddPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/courses/:programType/:courseId/attach-practice"
|
||||
element={<LinkExistingPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/courses/:programType/:courseId/:unitId/:moduleId/add-practice"
|
||||
element={<AddPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/courses/:programType/:courseId/:unitId/:moduleId/attach-practice"
|
||||
element={<LinkExistingPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/courses/:programType/:courseId"
|
||||
element={<CourseManagementPage />}
|
||||
|
|
@ -266,6 +283,10 @@ export function AppRoutes() {
|
|||
path="/new-content/learn-english/:level/courses/add-practice"
|
||||
element={<AddPracticeFlow />}
|
||||
/>
|
||||
<Route
|
||||
path="/new-content/learn-english/:level/courses/attach-practice"
|
||||
element={<LinkExistingPracticeFlow />}
|
||||
/>
|
||||
|
||||
<Route path="/notifications" element={<NotificationsPage />} />
|
||||
<Route
|
||||
|
|
|
|||
67
src/components/SearchHighlight.tsx
Normal file
67
src/components/SearchHighlight.tsx
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { Fragment, useMemo } from "react"
|
||||
import { cn } from "../lib/utils"
|
||||
|
||||
export function getSearchTokens(query: string): string[] {
|
||||
return query.trim().split(/\s+/).filter(Boolean)
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
}
|
||||
|
||||
type Segment = { text: string; match: boolean }
|
||||
|
||||
function segmentByTokens(text: string, tokens: string[]): Segment[] {
|
||||
if (tokens.length === 0) return [{ text, match: false }]
|
||||
|
||||
const pattern = [...tokens]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map(escapeRegExp)
|
||||
.join("|")
|
||||
const regex = new RegExp(`(${pattern})`, "gi")
|
||||
const parts = text.split(regex).filter((part) => part.length > 0)
|
||||
if (parts.length <= 1) return [{ text, match: false }]
|
||||
|
||||
const lowerTokens = new Set(tokens.map((token) => token.toLowerCase()))
|
||||
return parts.map((part) => ({
|
||||
text: part,
|
||||
match: lowerTokens.has(part.toLowerCase()),
|
||||
}))
|
||||
}
|
||||
|
||||
interface SearchHighlightProps {
|
||||
text: string
|
||||
query: string
|
||||
className?: string
|
||||
highlightClassName?: string
|
||||
}
|
||||
|
||||
export function SearchHighlight({
|
||||
text,
|
||||
query,
|
||||
className,
|
||||
highlightClassName = "rounded-sm bg-amber-200/90 px-0.5 font-inherit text-inherit",
|
||||
}: SearchHighlightProps) {
|
||||
const segments = useMemo(
|
||||
() => segmentByTokens(text, getSearchTokens(query)),
|
||||
[text, query],
|
||||
)
|
||||
|
||||
if (!query.trim()) {
|
||||
return <span className={className}>{text}</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={className}>
|
||||
{segments.map((segment, index) =>
|
||||
segment.match ? (
|
||||
<mark key={index} className={cn(highlightClassName)}>
|
||||
{segment.text}
|
||||
</mark>
|
||||
) : (
|
||||
<Fragment key={index}>{segment.text}</Fragment>
|
||||
),
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
|
@ -45,7 +45,7 @@ export function Topbar({ onSidebarToggle }: TopbarProps) {
|
|||
}
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-40 flex h-16 items-center justify-between gap-3 border-b bg-grayScale-50/85 px-4 backdrop-blur lg:justify-end lg:px-6">
|
||||
<header className="z-40 flex h-16 shrink-0 items-center justify-between gap-3 border-b bg-grayScale-50/85 px-4 backdrop-blur lg:justify-end lg:px-6">
|
||||
{/* Sidebar toggle */}
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
51
src/hooks/usePracticeParentTitles.ts
Normal file
51
src/hooks/usePracticeParentTitles.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { useEffect, useMemo, useState } from "react"
|
||||
import type { PracticeParent } from "../types/course.types"
|
||||
import { dedupeParents } from "../lib/practiceParents"
|
||||
import {
|
||||
resolvePracticeParentTitles,
|
||||
type PracticeParentTitleHints,
|
||||
type PracticeParentTitleMap,
|
||||
} from "../lib/practiceParentTitles"
|
||||
|
||||
export function usePracticeParentTitles(
|
||||
parents: PracticeParent[],
|
||||
hints?: PracticeParentTitleHints,
|
||||
) {
|
||||
const [titles, setTitles] = useState<PracticeParentTitleMap>(() => new Map())
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const parentsKey = useMemo(
|
||||
() =>
|
||||
dedupeParents(parents)
|
||||
.map((parent) => `${parent.parent_kind}:${parent.parent_id}`)
|
||||
.sort()
|
||||
.join("|"),
|
||||
[parents],
|
||||
)
|
||||
|
||||
const hintsKey = useMemo(
|
||||
() =>
|
||||
JSON.stringify({
|
||||
courses: hints?.courses ?? {},
|
||||
modules: hints?.modules ?? {},
|
||||
lessons: hints?.lessons ?? {},
|
||||
}),
|
||||
[hints?.courses, hints?.modules, hints?.lessons],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
void resolvePracticeParentTitles(parents, hints).then((resolved) => {
|
||||
if (!cancelled) {
|
||||
setTitles(resolved)
|
||||
setLoading(false)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [parentsKey, hintsKey])
|
||||
|
||||
return { titles, loading }
|
||||
}
|
||||
|
|
@ -96,6 +96,7 @@
|
|||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ export function AppLayout() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-dvh min-h-screen overflow-hidden bg-grayScale-100">
|
||||
<div className="flex h-dvh overflow-hidden bg-grayScale-100">
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
isCollapsed={sidebarCollapsed}
|
||||
|
|
|
|||
32
src/lib/attachPracticeToParent.ts
Normal file
32
src/lib/attachPracticeToParent.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { updatePracticeParents } from "../api/courses.api"
|
||||
import type { ParentContextPractice, PracticeParent } from "../types/course.types"
|
||||
import { dedupeParents, parentsFromPractice } from "./practiceParents"
|
||||
|
||||
export function practiceAlreadyLinkedToParent(
|
||||
practice: Pick<ParentContextPractice, "parents" | "parent_kind" | "parent_id">,
|
||||
target: PracticeParent,
|
||||
): boolean {
|
||||
const key = `${target.parent_kind}:${target.parent_id}`
|
||||
return parentsFromPractice(practice).some(
|
||||
(p) => `${p.parent_kind}:${p.parent_id}` === key,
|
||||
)
|
||||
}
|
||||
|
||||
export function mergedParentsForAttach(
|
||||
practice: Pick<ParentContextPractice, "parents" | "parent_kind" | "parent_id">,
|
||||
newParent: PracticeParent,
|
||||
): PracticeParent[] {
|
||||
return dedupeParents([...parentsFromPractice(practice), newParent])
|
||||
}
|
||||
|
||||
export async function attachPracticeToParent(
|
||||
practice: ParentContextPractice,
|
||||
newParent: PracticeParent,
|
||||
): Promise<void> {
|
||||
if (practiceAlreadyLinkedToParent(practice, newParent)) {
|
||||
throw new Error("This practice is already linked to the selected location.")
|
||||
}
|
||||
await updatePracticeParents(practice.id, {
|
||||
parents: mergedParentsForAttach(practice, newParent),
|
||||
})
|
||||
}
|
||||
34
src/lib/fetchAllPractices.ts
Normal file
34
src/lib/fetchAllPractices.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { getPractices } from "../api/courses.api"
|
||||
import type { ParentContextPractice } from "../types/course.types"
|
||||
|
||||
const FETCH_PAGE_SIZE = 100
|
||||
|
||||
export async function fetchAllPractices(
|
||||
unlinkedOnly: boolean,
|
||||
): Promise<ParentContextPractice[]> {
|
||||
const all: ParentContextPractice[] = []
|
||||
let offset = 0
|
||||
let totalCount = Number.POSITIVE_INFINITY
|
||||
|
||||
while (offset < totalCount) {
|
||||
const res = await getPractices({
|
||||
limit: FETCH_PAGE_SIZE,
|
||||
offset,
|
||||
unlinked_only: unlinkedOnly,
|
||||
})
|
||||
const envelope = res.data?.data
|
||||
const batch = Array.isArray(envelope?.practices) ? envelope.practices : []
|
||||
if (typeof envelope?.total_count === "number") {
|
||||
totalCount = envelope.total_count
|
||||
} else if (batch.length === 0) {
|
||||
break
|
||||
} else {
|
||||
totalCount = offset + batch.length
|
||||
}
|
||||
all.push(...batch)
|
||||
if (batch.length === 0) break
|
||||
offset += FETCH_PAGE_SIZE
|
||||
}
|
||||
|
||||
return all
|
||||
}
|
||||
|
|
@ -163,11 +163,15 @@ export function legacyQuestionTypeFromDefinition(
|
|||
export type QuestionDifficultyLevel = "EASY" | "MEDIUM" | "HARD"
|
||||
|
||||
export interface LearnEnglishDefinitionQuestionInput {
|
||||
clientRowId?: string
|
||||
questionText: string
|
||||
questionTypeDefinitionId: number
|
||||
dynamicFieldValues: Record<string, string>
|
||||
difficultyLevel?: QuestionDifficultyLevel
|
||||
points?: number
|
||||
associatedQuestionId?: number | null
|
||||
associatedAnchorRowId?: string | null
|
||||
prerequisiteQuestionIds?: number[]
|
||||
displayOrder?: number
|
||||
mcqOptions?: { option_text: string; is_correct: boolean }[]
|
||||
trueFalseAnswerIsTrue?: boolean
|
||||
|
|
|
|||
350
src/lib/learnEnglishPracticeEditPath.ts
Normal file
350
src/lib/learnEnglishPracticeEditPath.ts
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
import {
|
||||
getLearnEnglishPracticeFull,
|
||||
getLearningPrograms,
|
||||
getModuleLessons,
|
||||
getPracticesByParentCourse,
|
||||
getPracticesByParentLesson,
|
||||
getPracticesByParentModule,
|
||||
getProgramCourses,
|
||||
getTopLevelCourseModules,
|
||||
} from "../api/courses.api"
|
||||
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
||||
import { parentsFromPractice } from "./practiceParents"
|
||||
import type {
|
||||
LearningProgramListItem,
|
||||
ProgramCourseListItem,
|
||||
TopLevelCourseModuleItem,
|
||||
TopLevelModuleLessonItem,
|
||||
} from "../types/course.types"
|
||||
import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types"
|
||||
|
||||
const PAGE_SIZE = 100
|
||||
|
||||
type ParentTab = "course" | "module" | "lesson"
|
||||
|
||||
const sortBySortOrder = <T extends { sort_order?: number }>(items: T[]): T[] =>
|
||||
[...items].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
|
||||
|
||||
function parentTabFromKind(kind?: string): ParentTab | null {
|
||||
const k = (kind || "").toUpperCase()
|
||||
if (k === "COURSE") return "course"
|
||||
if (k === "MODULE") return "module"
|
||||
if (k === "LESSON") return "lesson"
|
||||
return null
|
||||
}
|
||||
|
||||
function pickNum(...values: unknown[]): number | undefined {
|
||||
for (const value of values) {
|
||||
const n = Number(value)
|
||||
if (Number.isFinite(n) && n > 0) return n
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function listFromEnvelope<T>(
|
||||
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
|
||||
key: string,
|
||||
): T[] {
|
||||
const body = res.data?.data ?? res.data?.Data
|
||||
if (!body || typeof body !== "object") return []
|
||||
const record = body as Record<string, unknown>
|
||||
const pascalKey = key.charAt(0).toUpperCase() + key.slice(1)
|
||||
const raw = record[key] ?? record[pascalKey]
|
||||
return Array.isArray(raw) ? (raw as T[]) : []
|
||||
}
|
||||
|
||||
function totalFromEnvelope(
|
||||
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
|
||||
): number | undefined {
|
||||
const body = res.data?.data ?? res.data?.Data
|
||||
if (!body || typeof body !== "object") return undefined
|
||||
const record = body as Record<string, unknown>
|
||||
const total = Number(record.total_count ?? record.TotalCount ?? record.totalCount)
|
||||
return Number.isFinite(total) && total >= 0 ? total : undefined
|
||||
}
|
||||
|
||||
async function fetchAllLearningPrograms(): Promise<LearningProgramListItem[]> {
|
||||
const all: LearningProgramListItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getLearningPrograms({ limit: PAGE_SIZE, offset })
|
||||
const page = listFromEnvelope<LearningProgramListItem>(res, "programs")
|
||||
all.push(...page)
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && all.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
offset += page.length
|
||||
}
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function fetchAllProgramCourses(programId: number): Promise<ProgramCourseListItem[]> {
|
||||
const all: ProgramCourseListItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getProgramCourses(programId, { limit: PAGE_SIZE, offset })
|
||||
const page = listFromEnvelope<ProgramCourseListItem>(res, "courses")
|
||||
all.push(...page)
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && all.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
offset += page.length
|
||||
}
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function fetchAllCourseModules(courseId: number): Promise<TopLevelCourseModuleItem[]> {
|
||||
const all: TopLevelCourseModuleItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getTopLevelCourseModules(courseId, { limit: PAGE_SIZE, offset })
|
||||
const page = listFromEnvelope<TopLevelCourseModuleItem>(res, "modules")
|
||||
all.push(...page)
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && all.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
offset += page.length
|
||||
}
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function fetchAllModuleLessons(moduleId: number): Promise<TopLevelModuleLessonItem[]> {
|
||||
const all: TopLevelModuleLessonItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getModuleLessons(moduleId, { limit: PAGE_SIZE, offset })
|
||||
const page = listFromEnvelope<TopLevelModuleLessonItem>(res, "lessons")
|
||||
all.push(...page)
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && all.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
offset += page.length
|
||||
}
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function parentListContainsPractice(
|
||||
tab: ParentTab,
|
||||
parentId: number,
|
||||
practiceId: number,
|
||||
): Promise<boolean> {
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const params = { limit: PAGE_SIZE, offset }
|
||||
const res =
|
||||
tab === "course"
|
||||
? await getPracticesByParentCourse(parentId, params)
|
||||
: tab === "module"
|
||||
? await getPracticesByParentModule(parentId, params)
|
||||
: await getPracticesByParentLesson(parentId, params)
|
||||
const page = listFromEnvelope<{ id?: number; ID?: number }>(res, "practices")
|
||||
if (page.some((p) => Number(p.id ?? p.ID) === practiceId)) return true
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && offset + page.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
offset += page.length
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Confirms which parent entity owns this practice when parent_kind is missing or unreliable. */
|
||||
async function detectParentTab(
|
||||
practiceId: number,
|
||||
parentId: number,
|
||||
hintedTab: ParentTab | null,
|
||||
): Promise<ParentTab | null> {
|
||||
if (hintedTab && (await parentListContainsPractice(hintedTab, parentId, practiceId))) {
|
||||
return hintedTab
|
||||
}
|
||||
const order: ParentTab[] =
|
||||
hintedTab == null
|
||||
? ["lesson", "module", "course"]
|
||||
: (["lesson", "module", "course"] as ParentTab[]).filter((tab) => tab !== hintedTab)
|
||||
for (const tab of order) {
|
||||
if (await parentListContainsPractice(tab, parentId, practiceId)) return tab
|
||||
}
|
||||
return hintedTab
|
||||
}
|
||||
|
||||
function buildCourseEditPath(programId: number, courseId: number, practiceId: number): string {
|
||||
return `/new-content/learn-english/${programId}/courses/${courseId}/edit-practice/${practiceId}?backTo=courses`
|
||||
}
|
||||
|
||||
function buildModuleEditPath(
|
||||
programId: number,
|
||||
courseId: number,
|
||||
moduleId: number,
|
||||
practiceId: number,
|
||||
): string {
|
||||
return `/new-content/learn-english/${programId}/courses/${courseId}/modules/${moduleId}/edit-practice/${practiceId}?backTo=module`
|
||||
}
|
||||
|
||||
function buildLessonEditPath(
|
||||
programId: number,
|
||||
courseId: number,
|
||||
moduleId: number,
|
||||
lessonId: number,
|
||||
practiceId: number,
|
||||
lessonTitle?: string,
|
||||
): string {
|
||||
const titleQuery = lessonTitle ? `lessonTitle=${encodeURIComponent(lessonTitle)}&` : ""
|
||||
return `/new-content/learn-english/${programId}/courses/${courseId}/modules/${moduleId}/lessons/${lessonId}/edit-practice/${practiceId}?${titleQuery}backTo=lesson`
|
||||
}
|
||||
|
||||
async function resolveFromDirectNavFields(
|
||||
practice: QuestionTypeDefinitionPractice,
|
||||
): Promise<string | null> {
|
||||
const programId = pickNum(practice.program_id)
|
||||
const courseId = pickNum(practice.course_id)
|
||||
const moduleId = pickNum(practice.module_id)
|
||||
const lessonId = pickNum(practice.lesson_id)
|
||||
if (!programId || !courseId) return null
|
||||
if (lessonId && moduleId) {
|
||||
return buildLessonEditPath(programId, courseId, moduleId, lessonId, practice.practice_id, practice.title)
|
||||
}
|
||||
if (moduleId) {
|
||||
return buildModuleEditPath(programId, courseId, moduleId, practice.practice_id)
|
||||
}
|
||||
return buildCourseEditPath(programId, courseId, practice.practice_id)
|
||||
}
|
||||
|
||||
async function findCoursePath(
|
||||
courseId: number,
|
||||
practiceId: number,
|
||||
): Promise<string | null> {
|
||||
const programs = await fetchAllLearningPrograms()
|
||||
for (const program of programs) {
|
||||
const courses = await fetchAllProgramCourses(program.id)
|
||||
const course = courses.find((c) => c.id === courseId)
|
||||
if (course) {
|
||||
const programId = course.program_id || program.id
|
||||
return buildCourseEditPath(programId, course.id, practiceId)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function findModulePath(
|
||||
moduleId: number,
|
||||
practiceId: number,
|
||||
): Promise<string | null> {
|
||||
const programs = await fetchAllLearningPrograms()
|
||||
for (const program of programs) {
|
||||
const courses = await fetchAllProgramCourses(program.id)
|
||||
for (const course of courses) {
|
||||
const modules = await fetchAllCourseModules(course.id)
|
||||
const module = modules.find((m) => m.id === moduleId)
|
||||
if (module) {
|
||||
const programId = module.program_id || course.program_id || program.id
|
||||
const resolvedCourseId = module.course_id || course.id
|
||||
return buildModuleEditPath(programId, resolvedCourseId, module.id, practiceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function findLessonPath(
|
||||
lessonId: number,
|
||||
practiceId: number,
|
||||
): Promise<string | null> {
|
||||
const programs = await fetchAllLearningPrograms()
|
||||
for (const program of programs) {
|
||||
const courses = await fetchAllProgramCourses(program.id)
|
||||
for (const course of courses) {
|
||||
const modules = await fetchAllCourseModules(course.id)
|
||||
for (const module of modules) {
|
||||
const lessons = await fetchAllModuleLessons(module.id)
|
||||
const lesson = lessons.find((l) => l.id === lessonId)
|
||||
if (lesson) {
|
||||
const programId = module.program_id || course.program_id || program.id
|
||||
const courseId = module.course_id || course.id
|
||||
return buildLessonEditPath(
|
||||
programId,
|
||||
courseId,
|
||||
module.id,
|
||||
lesson.id,
|
||||
practiceId,
|
||||
lesson.title,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function resolveForParent(
|
||||
practiceId: number,
|
||||
parent: { parent_kind: string; parent_id: number },
|
||||
): Promise<string | null> {
|
||||
const parentId = parent.parent_id
|
||||
if (parentId < 1) return null
|
||||
const hintedTab = parentTabFromKind(parent.parent_kind)
|
||||
const tab = await detectParentTab(practiceId, parentId, hintedTab)
|
||||
const resolvedTab = tab ?? hintedTab
|
||||
if (!resolvedTab) return null
|
||||
if (resolvedTab === "course") return findCoursePath(parentId, practiceId)
|
||||
if (resolvedTab === "module") return findModulePath(parentId, practiceId)
|
||||
return findLessonPath(parentId, practiceId)
|
||||
}
|
||||
|
||||
async function enrichPracticeFromFull(
|
||||
practice: QuestionTypeDefinitionPractice,
|
||||
): Promise<QuestionTypeDefinitionPractice> {
|
||||
try {
|
||||
const res = await getLearnEnglishPracticeFull(practice.practice_id)
|
||||
const full = unwrapPracticeFullData(res)
|
||||
const p = full?.practice
|
||||
if (!p) return practice
|
||||
const parents = parentsFromPractice(p)
|
||||
return {
|
||||
...practice,
|
||||
parents,
|
||||
parent_kind: parents[0]?.parent_kind,
|
||||
parent_id: parents[0]?.parent_id,
|
||||
lesson_id: p.lesson_id ?? practice.lesson_id,
|
||||
}
|
||||
} catch {
|
||||
return practice
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveLearnEnglishPath(
|
||||
practice: QuestionTypeDefinitionPractice,
|
||||
): Promise<string | null> {
|
||||
const direct = await resolveFromDirectNavFields(practice)
|
||||
if (direct) return direct
|
||||
|
||||
let working = practice
|
||||
if (!working.parents?.length) {
|
||||
working = await enrichPracticeFromFull(working)
|
||||
}
|
||||
|
||||
const parentList =
|
||||
working.parents?.length > 0
|
||||
? working.parents
|
||||
: parentsFromPractice(working)
|
||||
|
||||
for (const parent of parentList) {
|
||||
const path = await resolveForParent(working.practice_id, parent)
|
||||
if (path) return path
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a Learn English edit-practice route for a practice linked to a question type definition.
|
||||
*/
|
||||
export async function resolveLearnEnglishPracticeEditPath(
|
||||
practice: QuestionTypeDefinitionPractice,
|
||||
): Promise<string | null> {
|
||||
if ((practice.practice_kind || "LMS").toUpperCase() !== "LMS") return null
|
||||
return resolveLearnEnglishPath(practice)
|
||||
}
|
||||
|
|
@ -3,8 +3,42 @@ import type {
|
|||
ParentContextPractice,
|
||||
PracticePublishStatus,
|
||||
} from "../types/course.types"
|
||||
import { normalizePracticeParents } from "./practiceParents"
|
||||
import { isPublishedPublishStatus, normalizePublishStatus } from "./publishStatus"
|
||||
|
||||
export function normalizeParentContextPractice(raw: unknown): ParentContextPractice | null {
|
||||
if (!raw || typeof raw !== "object") return null
|
||||
const o = raw as Record<string, unknown>
|
||||
const id = Number(o.id ?? o.ID ?? o.Id)
|
||||
if (!Number.isFinite(id) || id <= 0) return null
|
||||
const parents = normalizePracticeParents(raw)
|
||||
const question_set_id = Number(o.question_set_id ?? o.QuestionSetId ?? o.questionSetId)
|
||||
return {
|
||||
id,
|
||||
parents,
|
||||
parent_kind: parents[0]?.parent_kind,
|
||||
parent_id: parents[0]?.parent_id,
|
||||
title: String(o.title ?? o.Title ?? ""),
|
||||
story_description: String(o.story_description ?? o.StoryDescription ?? ""),
|
||||
story_image: String(o.story_image ?? o.StoryImage ?? ""),
|
||||
question_set_id: Number.isFinite(question_set_id) ? question_set_id : 0,
|
||||
quick_tips: String(o.quick_tips ?? o.QuickTips ?? ""),
|
||||
publish_status:
|
||||
o.publish_status != null
|
||||
? String(o.publish_status)
|
||||
: o.PublishStatus != null
|
||||
? String(o.PublishStatus)
|
||||
: null,
|
||||
persona_id:
|
||||
o.persona_id != null && Number.isFinite(Number(o.persona_id))
|
||||
? Number(o.persona_id)
|
||||
: o.PersonaId != null && Number.isFinite(Number(o.PersonaId))
|
||||
? Number(o.PersonaId)
|
||||
: null,
|
||||
created_at: String(o.created_at ?? o.CreatedAt ?? ""),
|
||||
}
|
||||
}
|
||||
|
||||
export function unwrapPracticesList(
|
||||
res: {
|
||||
data?: GetPracticesByParentContextResponse & {
|
||||
|
|
@ -16,7 +50,10 @@ export function unwrapPracticesList(
|
|||
if (!body) return []
|
||||
const data = body.data ?? body.Data
|
||||
const raw = data?.practices
|
||||
return Array.isArray(raw) ? raw : []
|
||||
if (!Array.isArray(raw)) return []
|
||||
return raw
|
||||
.map((entry) => normalizeParentContextPractice(entry))
|
||||
.filter((entry): entry is ParentContextPractice => entry != null)
|
||||
}
|
||||
|
||||
export function practicePublishStatus(
|
||||
|
|
|
|||
114
src/lib/practiceContentPaths.ts
Normal file
114
src/lib/practiceContentPaths.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import type { PracticeParent } from "../types/course.types"
|
||||
import { formatPracticeParentLabel } from "./practiceParents"
|
||||
|
||||
export interface PracticeContentPathOptions {
|
||||
isExamPrep: boolean
|
||||
level?: string | null
|
||||
programType?: string | null
|
||||
courseId?: string | null
|
||||
unitId?: string | null
|
||||
moduleId?: string | null
|
||||
lessonId?: string | null
|
||||
lessonTitle?: string | null
|
||||
backTo?: string | null
|
||||
}
|
||||
|
||||
export function resolvePracticeParentFromPathOptions(
|
||||
options: PracticeContentPathOptions,
|
||||
): PracticeParent | null {
|
||||
const lessonId = options.lessonId?.trim()
|
||||
if (lessonId) {
|
||||
const id = Number(lessonId)
|
||||
if (Number.isFinite(id) && id > 0) {
|
||||
return { parent_kind: "LESSON", parent_id: id }
|
||||
}
|
||||
}
|
||||
|
||||
const backTo = options.backTo?.trim()
|
||||
const moduleId = options.moduleId?.trim()
|
||||
if (backTo === "module" && moduleId) {
|
||||
const id = Number(moduleId)
|
||||
if (Number.isFinite(id) && id > 0) {
|
||||
return { parent_kind: "MODULE", parent_id: id }
|
||||
}
|
||||
}
|
||||
|
||||
if (options.isExamPrep && moduleId && !lessonId) {
|
||||
const id = Number(moduleId)
|
||||
if (Number.isFinite(id) && id > 0) {
|
||||
return { parent_kind: "MODULE", parent_id: id }
|
||||
}
|
||||
}
|
||||
|
||||
const courseId = options.courseId?.trim()
|
||||
if ((backTo === "modules" || backTo === "courses") && courseId) {
|
||||
const id = Number(courseId)
|
||||
if (Number.isFinite(id) && id > 0) {
|
||||
return { parent_kind: "COURSE", parent_id: id }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function resolvePracticeParentSummaryFromPathOptions(
|
||||
options: PracticeContentPathOptions,
|
||||
parentLabel?: string | null,
|
||||
): string {
|
||||
const parent = resolvePracticeParentFromPathOptions(options)
|
||||
if (parent) return formatPracticeParentLabel(parent)
|
||||
if (parentLabel?.trim()) return parentLabel.trim()
|
||||
const lessonTitle = options.lessonTitle?.trim()
|
||||
if (options.lessonId?.trim()) {
|
||||
return `Lesson #${options.lessonId.trim()}${lessonTitle ? ` — ${lessonTitle}` : ""}`
|
||||
}
|
||||
if (options.moduleId?.trim()) return `Module #${options.moduleId.trim()}`
|
||||
if (options.courseId?.trim()) return `Course #${options.courseId.trim()}`
|
||||
return "selected content"
|
||||
}
|
||||
|
||||
function buildPracticeQuery(options: PracticeContentPathOptions): string {
|
||||
const params = new URLSearchParams()
|
||||
if (options.backTo?.trim()) params.set("backTo", options.backTo.trim())
|
||||
if (options.courseId?.trim()) params.set("courseId", options.courseId.trim())
|
||||
if (options.moduleId?.trim()) params.set("moduleId", options.moduleId.trim())
|
||||
if (options.lessonId?.trim()) params.set("lessonId", options.lessonId.trim())
|
||||
if (options.lessonTitle?.trim()) {
|
||||
params.set("lessonTitle", encodeURIComponent(options.lessonTitle.trim()))
|
||||
}
|
||||
const qs = params.toString()
|
||||
return qs ? `?${qs}` : ""
|
||||
}
|
||||
|
||||
function practiceBasePath(options: PracticeContentPathOptions): string {
|
||||
if (options.isExamPrep) {
|
||||
const programType = options.programType?.trim()
|
||||
const courseId = options.courseId?.trim()
|
||||
const unitId = options.unitId?.trim()
|
||||
const moduleId = options.moduleId?.trim()
|
||||
if (programType && courseId && unitId && moduleId) {
|
||||
return `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}`
|
||||
}
|
||||
if (programType && courseId) {
|
||||
return `/new-content/courses/${programType}/${courseId}`
|
||||
}
|
||||
if (programType) {
|
||||
return `/new-content/courses/${programType}`
|
||||
}
|
||||
return "/new-content/courses"
|
||||
}
|
||||
|
||||
const level = options.level?.trim() || "a1"
|
||||
return `/new-content/learn-english/${level}/courses`
|
||||
}
|
||||
|
||||
export function buildPracticeContentPaths(
|
||||
options: PracticeContentPathOptions,
|
||||
): { create: string; attach: string } {
|
||||
const base = practiceBasePath(options)
|
||||
const query = buildPracticeQuery(options)
|
||||
return {
|
||||
create: `${base}/add-practice${query}`,
|
||||
attach: `${base}/attach-practice${query}`,
|
||||
}
|
||||
}
|
||||
|
|
@ -6,20 +6,30 @@ import {
|
|||
createQuestion,
|
||||
createQuestionSet,
|
||||
} from "../api/courses.api"
|
||||
import type { PracticeParentKind } from "../types/course.types"
|
||||
import type { PracticeParent, PracticeParentKind } from "../types/course.types"
|
||||
import type { QuestionTypeDefinition } from "../types/questionTypeDefinition.types"
|
||||
import {
|
||||
buildCreatePracticeParentsPayload,
|
||||
dedupeParents,
|
||||
} from "./practiceParents"
|
||||
import {
|
||||
buildCreateQuestionFromDefinition,
|
||||
questionRowHasContent,
|
||||
validateDefinitionQuestion,
|
||||
type LearnEnglishDefinitionQuestionInput,
|
||||
} from "./learnEnglishDefinitionQuestion"
|
||||
import {
|
||||
resolveAssociatedQuestionId,
|
||||
validateQuestionAssociations,
|
||||
} from "./questionAssociations"
|
||||
|
||||
export type { LearnEnglishDefinitionQuestionInput } from "./learnEnglishDefinitionQuestion"
|
||||
|
||||
export interface PracticeCreationInput {
|
||||
parentKind: PracticeParentKind
|
||||
parentId: number
|
||||
parents?: PracticeParent[] | null
|
||||
/** @deprecated use parents — kept for exam-prep lesson API */
|
||||
parentKind?: PracticeParentKind
|
||||
parentId?: number
|
||||
status: "DRAFT" | "PUBLISHED"
|
||||
questionSetTitle: string
|
||||
questionSetDescription?: string | null
|
||||
|
|
@ -91,13 +101,18 @@ export async function executePracticeCreation(
|
|||
|
||||
const byId = new Map(opts.definitions.map((d) => [d.id, d]))
|
||||
|
||||
const linkedParents = dedupeParents(opts.parents ?? [])
|
||||
const createParents = buildCreatePracticeParentsPayload(linkedParents)
|
||||
const primaryParent = linkedParents[0] ?? null
|
||||
|
||||
// Step 1 — create question set
|
||||
const setRes = await createQuestionSet({
|
||||
title: opts.questionSetTitle.trim() || "Practice question set",
|
||||
description: opts.questionSetDescription?.trim() || null,
|
||||
set_type: "PRACTICE",
|
||||
owner_type: opts.parentKind,
|
||||
owner_id: opts.parentId,
|
||||
...(primaryParent
|
||||
? { owner_type: primaryParent.parent_kind, owner_id: primaryParent.parent_id }
|
||||
: {}),
|
||||
shuffle_questions: opts.shuffleQuestions,
|
||||
status: opts.status,
|
||||
...(opts.personaName?.trim() ? { persona: opts.personaName.trim() } : {}),
|
||||
|
|
@ -118,18 +133,49 @@ export async function executePracticeCreation(
|
|||
})
|
||||
.sort((a, b) => a.sortOrder - b.sortOrder)
|
||||
|
||||
const associationRows = toCreate.map(({ q, sortOrder }) => ({
|
||||
id: q.clientRowId ?? `row-${sortOrder}`,
|
||||
serverQuestionId: null as number | null,
|
||||
displayOrder: sortOrder,
|
||||
associatedQuestionId: q.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
|
||||
}))
|
||||
const associationErr = validateQuestionAssociations(associationRows)
|
||||
if (associationErr) throw new Error(associationErr)
|
||||
|
||||
// Steps 2 & 3 — create questions and attach to set (order from step 3 drag-and-drop)
|
||||
let displayOrder = 0
|
||||
for (const { q } of toCreate) {
|
||||
const rowIdToServerId = new Map<string, number>()
|
||||
for (const { q, sortOrder } of toCreate) {
|
||||
const def = byId.get(q.questionTypeDefinitionId)
|
||||
if (!def) throw new Error(`Missing definition #${q.questionTypeDefinitionId}`)
|
||||
displayOrder += 1
|
||||
const payload = buildCreateQuestionFromDefinition(def, q, opts.status)
|
||||
const qRes = await createQuestion(payload)
|
||||
const questionId = extractCreatedResourceId(qRes, "Could not create question")
|
||||
const rowKey = q.clientRowId ?? `row-${sortOrder}`
|
||||
rowIdToServerId.set(rowKey, questionId)
|
||||
|
||||
const associationRow = {
|
||||
id: rowKey,
|
||||
serverQuestionId: questionId,
|
||||
displayOrder: sortOrder,
|
||||
associatedQuestionId: q.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
|
||||
}
|
||||
const resolvedAssociationRows = associationRows.map((row) => ({
|
||||
...row,
|
||||
serverQuestionId: rowIdToServerId.get(row.id) ?? row.serverQuestionId,
|
||||
}))
|
||||
|
||||
await addQuestionToSet(setId, {
|
||||
question_id: questionId,
|
||||
display_order: displayOrder,
|
||||
associated_question_id: resolveAssociatedQuestionId(
|
||||
associationRow,
|
||||
resolvedAssociationRows,
|
||||
rowIdToServerId,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -145,8 +191,7 @@ export async function executePracticeCreation(
|
|||
publish_status: opts.status,
|
||||
})
|
||||
: await createParentLinkedPractice({
|
||||
parent_kind: opts.parentKind,
|
||||
parent_id: opts.parentId,
|
||||
parents: createParents,
|
||||
title: opts.practiceTitle.trim(),
|
||||
story_description: opts.storyDescription.trim(),
|
||||
story_image: opts.storyImage.trim(),
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import {
|
||||
updateExamPrepPracticeFull,
|
||||
updateLearnEnglishPracticeFull,
|
||||
updatePracticeParents,
|
||||
} from "../api/courses.api"
|
||||
import type { PracticePublishStatus } from "../types/course.types"
|
||||
import type { PracticeParent, PracticePublishStatus } from "../types/course.types"
|
||||
import type { QuestionTypeDefinition } from "../types/questionTypeDefinition.types"
|
||||
import { dedupeParents } from "./practiceParents"
|
||||
import {
|
||||
buildPracticeFullUpdateRequest,
|
||||
type PracticeFormState,
|
||||
|
|
@ -22,6 +24,8 @@ export interface PracticeEditInput {
|
|||
definitions: QuestionTypeDefinition[]
|
||||
isLearnEnglishLessonPractice: boolean
|
||||
lessonDefaultTitle?: string
|
||||
parents?: PracticeParent[]
|
||||
parentsChanged?: boolean
|
||||
}
|
||||
|
||||
export async function executePracticeUpdate(
|
||||
|
|
@ -42,5 +46,12 @@ export async function executePracticeUpdate(
|
|||
await updateExamPrepPracticeFull(opts.practiceId, payload)
|
||||
return
|
||||
}
|
||||
|
||||
await updateLearnEnglishPracticeFull(opts.practiceId, payload)
|
||||
|
||||
if (opts.parentsChanged && opts.parents) {
|
||||
await updatePracticeParents(opts.practiceId, {
|
||||
parents: dedupeParents(opts.parents),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import type {
|
|||
PracticeFullPractice,
|
||||
PracticeFullQuestionItem,
|
||||
PracticeFullQuestionSet,
|
||||
PracticeParent,
|
||||
PracticePublishStatus,
|
||||
QuestionOption,
|
||||
QuestionShortAnswer,
|
||||
|
|
@ -24,12 +25,20 @@ import {
|
|||
type LearnEnglishDefinitionQuestionInput,
|
||||
} from "./learnEnglishDefinitionQuestion"
|
||||
import { serializeMultipleChoiceSlotValue } from "./multipleChoiceSlotValue"
|
||||
import { normalizePracticeParents, parentsFromPractice } from "./practiceParents"
|
||||
import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator"
|
||||
import {
|
||||
resolveAssociatedQuestionId,
|
||||
validateQuestionAssociations,
|
||||
} from "./questionAssociations"
|
||||
|
||||
export interface PracticeFormQuestionRow {
|
||||
id: string
|
||||
serverQuestionId?: number | null
|
||||
displayOrder: number
|
||||
associatedQuestionId: number | null
|
||||
associatedAnchorRowId: string | null
|
||||
prerequisiteQuestionIds?: number[]
|
||||
questionTypeDefinitionId: number | null
|
||||
text: string
|
||||
difficultyLevel: "EASY" | "MEDIUM" | "HARD"
|
||||
|
|
@ -46,6 +55,7 @@ export interface PracticeFormState {
|
|||
storyImageUrl: string
|
||||
shuffleQuestions: boolean
|
||||
tips: string
|
||||
parents: PracticeParent[]
|
||||
questions: PracticeFormQuestionRow[]
|
||||
}
|
||||
|
||||
|
|
@ -197,6 +207,19 @@ export function normalizePracticeFullQuestion(
|
|||
return {
|
||||
...(id != null ? { id } : {}),
|
||||
display_order: displayOrder,
|
||||
associated_question_id:
|
||||
record.associated_question_id != null
|
||||
? Number(record.associated_question_id)
|
||||
: record.AssociatedQuestionId != null
|
||||
? Number(record.AssociatedQuestionId)
|
||||
: null,
|
||||
prerequisite_question_ids: Array.isArray(record.prerequisite_question_ids)
|
||||
? record.prerequisite_question_ids.map((v) => Number(v)).filter((n) => Number.isFinite(n))
|
||||
: Array.isArray(record.PrerequisiteQuestionIds)
|
||||
? record.PrerequisiteQuestionIds.map((v) => Number(v)).filter((n) =>
|
||||
Number.isFinite(n),
|
||||
)
|
||||
: undefined,
|
||||
question_text: pickStr(record, "question_text", "QuestionText", "questionText") || undefined,
|
||||
question_type: questionType,
|
||||
question_type_definition_id:
|
||||
|
|
@ -283,6 +306,12 @@ function normalizePracticeFullPractice(raw: unknown): PracticeFullPractice | nul
|
|||
"questionSetId",
|
||||
)
|
||||
if (id == null || questionSetId == null) return null
|
||||
const parents = parentsFromPractice({
|
||||
parents: normalizePracticeParents(record),
|
||||
parent_kind: pickStr(record, "parent_kind", "ParentKind", "parentKind") || undefined,
|
||||
parent_id: pickNum(record, "parent_id", "ParentId", "parentId") ?? undefined,
|
||||
})
|
||||
const lessonParent = parents.find((p) => p.parent_kind === "LESSON")
|
||||
return {
|
||||
id,
|
||||
title: pickStr(record, "title", "Title"),
|
||||
|
|
@ -296,9 +325,13 @@ function normalizePracticeFullPractice(raw: unknown): PracticeFullPractice | nul
|
|||
publish_status:
|
||||
pickStr(record, "publish_status", "PublishStatus", "publishStatus") || null,
|
||||
quick_tips: pickStr(record, "quick_tips", "QuickTips", "quickTips") || undefined,
|
||||
lesson_id: pickNum(record, "lesson_id", "LessonId", "lessonId") ?? undefined,
|
||||
parent_kind: pickStr(record, "parent_kind", "ParentKind", "parentKind") || undefined,
|
||||
parent_id: pickNum(record, "parent_id", "ParentId", "parentId") ?? undefined,
|
||||
parents,
|
||||
lesson_id:
|
||||
lessonParent?.parent_id ??
|
||||
pickNum(record, "lesson_id", "LessonId", "lessonId") ??
|
||||
undefined,
|
||||
parent_kind: parents[0]?.parent_kind,
|
||||
parent_id: parents[0]?.parent_id,
|
||||
created_at: pickStr(record, "created_at", "CreatedAt", "createdAt") || undefined,
|
||||
}
|
||||
}
|
||||
|
|
@ -495,6 +528,9 @@ function mapFullQuestionToFormRow(
|
|||
id: q.id != null ? `existing-${q.id}` : `q-${q.display_order}`,
|
||||
serverQuestionId: q.id ?? null,
|
||||
displayOrder: q.display_order,
|
||||
associatedQuestionId: q.associated_question_id ?? null,
|
||||
associatedAnchorRowId: null,
|
||||
prerequisiteQuestionIds: q.prerequisite_question_ids,
|
||||
questionTypeDefinitionId: defId,
|
||||
text,
|
||||
difficultyLevel,
|
||||
|
|
@ -515,6 +551,7 @@ export function mapPracticeFullToFormState(
|
|||
formData: PracticeFormState
|
||||
personaId: number | null
|
||||
preservedQuestionSet: PreservedQuestionSetFields
|
||||
parents: PracticeParent[]
|
||||
} {
|
||||
const { practice, question_set, questions } = data
|
||||
const sorted = [...questions].sort(
|
||||
|
|
@ -529,6 +566,8 @@ export function mapPracticeFullToFormState(
|
|||
id: "q1",
|
||||
displayOrder: 1,
|
||||
serverQuestionId: null,
|
||||
associatedQuestionId: null,
|
||||
associatedAnchorRowId: null,
|
||||
questionTypeDefinitionId: typeDefinitions[0]?.id ?? null,
|
||||
text: "",
|
||||
difficultyLevel: "EASY" as const,
|
||||
|
|
@ -552,6 +591,7 @@ export function mapPracticeFullToFormState(
|
|||
storyImageUrl: practice.story_image?.trim() || "",
|
||||
shuffleQuestions: Boolean(question_set.shuffle_questions),
|
||||
tips: practice.quick_tips?.trim() || "",
|
||||
parents: parentsFromPractice(practice),
|
||||
questions: formQuestions,
|
||||
},
|
||||
personaId:
|
||||
|
|
@ -567,6 +607,7 @@ export function mapPracticeFullToFormState(
|
|||
? "DRAFT"
|
||||
: "PUBLISHED",
|
||||
},
|
||||
parents: parentsFromPractice(practice),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -579,10 +620,12 @@ function buildFullUpdateQuestion(
|
|||
q: PracticeEditQuestionInput,
|
||||
status: PracticePublishStatus,
|
||||
displayOrder: number,
|
||||
associatedQuestionId: number | null,
|
||||
): PracticeFullQuestionItem {
|
||||
const created = buildCreateQuestionFromDefinition(def, q, status)
|
||||
const item: PracticeFullQuestionItem = {
|
||||
display_order: displayOrder,
|
||||
associated_question_id: associatedQuestionId,
|
||||
question_type: created.question_type,
|
||||
difficulty_level: created.difficulty_level,
|
||||
points: created.points,
|
||||
|
|
@ -663,14 +706,37 @@ export function buildPracticeFullUpdateRequest(
|
|||
})
|
||||
.sort((a, b) => a.sortOrder - b.sortOrder)
|
||||
|
||||
const associationRows = toUpdate.map(({ q, sortOrder }) => ({
|
||||
id: q.clientRowId ?? `update-${sortOrder}`,
|
||||
serverQuestionId: q.serverQuestionId ?? null,
|
||||
displayOrder: sortOrder,
|
||||
associatedQuestionId: q.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
|
||||
}))
|
||||
const associationErr = validateQuestionAssociations(associationRows)
|
||||
if (associationErr) throw new Error(associationErr)
|
||||
|
||||
let displayOrder = 0
|
||||
const questions: PracticeFullQuestionItem[] = []
|
||||
for (const { q } of toUpdate) {
|
||||
for (const { q, sortOrder } of toUpdate) {
|
||||
const def = byId.get(q.questionTypeDefinitionId)
|
||||
if (!def) continue
|
||||
displayOrder += 1
|
||||
const associationRow = {
|
||||
id: q.clientRowId ?? `update-${sortOrder}`,
|
||||
serverQuestionId: q.serverQuestionId ?? null,
|
||||
displayOrder: sortOrder,
|
||||
associatedQuestionId: q.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
|
||||
}
|
||||
questions.push(
|
||||
buildFullUpdateQuestion(def, q, opts.status, displayOrder),
|
||||
buildFullUpdateQuestion(
|
||||
def,
|
||||
q,
|
||||
opts.status,
|
||||
displayOrder,
|
||||
resolveAssociatedQuestionId(associationRow, associationRows),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
251
src/lib/practiceParentTitles.ts
Normal file
251
src/lib/practiceParentTitles.ts
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
import {
|
||||
getExamPrepCatalogCourses,
|
||||
getExamPrepCatalogUnits,
|
||||
getExamPrepModuleLessons,
|
||||
getExamPrepUnitModules,
|
||||
getLearningPrograms,
|
||||
getModuleLessons,
|
||||
getProgramCourses,
|
||||
getTopLevelCourseModules,
|
||||
} from "../api/courses.api"
|
||||
import type { PracticeParent, PracticeParentKind } from "../types/course.types"
|
||||
import {
|
||||
dedupeParents,
|
||||
formatPracticeParentLabel,
|
||||
formatPracticeParentsSummary,
|
||||
} from "./practiceParents"
|
||||
|
||||
const LIST_LIMIT = 200
|
||||
|
||||
export type PracticeParentTitleMap = Map<string, string>
|
||||
|
||||
export type PracticeParentTitleHints = {
|
||||
courses?: Record<number, string>
|
||||
modules?: Record<number, string>
|
||||
lessons?: Record<number, string>
|
||||
}
|
||||
|
||||
export function practiceParentKey(parent: PracticeParent): string {
|
||||
return `${parent.parent_kind}:${parent.parent_id}`
|
||||
}
|
||||
|
||||
function kindLabel(kind: PracticeParentKind): string {
|
||||
if (kind === "COURSE") return "Course"
|
||||
if (kind === "MODULE") return "Module"
|
||||
return "Lesson"
|
||||
}
|
||||
|
||||
export function formatPracticeParentDisplayLabel(
|
||||
parent: PracticeParent,
|
||||
titles?: PracticeParentTitleMap | null,
|
||||
): string {
|
||||
const title = titles?.get(practiceParentKey(parent))?.trim()
|
||||
if (title) return `${kindLabel(parent.parent_kind)}: ${title}`
|
||||
return formatPracticeParentLabel(parent)
|
||||
}
|
||||
|
||||
export function formatPracticeParentsDisplaySummary(
|
||||
parents: PracticeParent[],
|
||||
titles?: PracticeParentTitleMap | null,
|
||||
): string {
|
||||
const list = dedupeParents(parents)
|
||||
if (list.length === 0) return formatPracticeParentsSummary([])
|
||||
return list.map((parent) => formatPracticeParentDisplayLabel(parent, titles)).join(" · ")
|
||||
}
|
||||
|
||||
function applyHints(
|
||||
map: PracticeParentTitleMap,
|
||||
hints?: PracticeParentTitleHints,
|
||||
): void {
|
||||
for (const [id, title] of Object.entries(hints?.courses ?? {})) {
|
||||
const n = Number(id)
|
||||
if (Number.isFinite(n) && n > 0 && title?.trim()) map.set(`COURSE:${n}`, title.trim())
|
||||
}
|
||||
for (const [id, title] of Object.entries(hints?.modules ?? {})) {
|
||||
const n = Number(id)
|
||||
if (Number.isFinite(n) && n > 0 && title?.trim()) map.set(`MODULE:${n}`, title.trim())
|
||||
}
|
||||
for (const [id, title] of Object.entries(hints?.lessons ?? {})) {
|
||||
const n = Number(id)
|
||||
if (Number.isFinite(n) && n > 0 && title?.trim()) map.set(`LESSON:${n}`, title.trim())
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveLearnEnglishCourseTitles(
|
||||
ids: Set<number>,
|
||||
map: PracticeParentTitleMap,
|
||||
): Promise<void> {
|
||||
if (ids.size === 0) return
|
||||
const progRes = await getLearningPrograms({ limit: LIST_LIMIT, offset: 0 })
|
||||
const programs = progRes.data?.data?.programs ?? []
|
||||
for (const program of programs) {
|
||||
if (ids.size === 0) break
|
||||
const cRes = await getProgramCourses(program.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
for (const course of cRes.data?.data?.courses ?? []) {
|
||||
if (ids.has(course.id)) {
|
||||
map.set(`COURSE:${course.id}`, course.name?.trim() || `Course #${course.id}`)
|
||||
ids.delete(course.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveExamPrepCourseTitles(
|
||||
ids: Set<number>,
|
||||
map: PracticeParentTitleMap,
|
||||
): Promise<void> {
|
||||
if (ids.size === 0) return
|
||||
const res = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 })
|
||||
for (const course of res.data?.data?.catalog_courses ?? []) {
|
||||
if (ids.has(course.id)) {
|
||||
map.set(`COURSE:${course.id}`, course.name?.trim() || `Course #${course.id}`)
|
||||
ids.delete(course.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveLearnEnglishModuleTitles(
|
||||
ids: Set<number>,
|
||||
map: PracticeParentTitleMap,
|
||||
): Promise<void> {
|
||||
if (ids.size === 0) return
|
||||
const progRes = await getLearningPrograms({ limit: LIST_LIMIT, offset: 0 })
|
||||
const programs = progRes.data?.data?.programs ?? []
|
||||
for (const program of programs) {
|
||||
if (ids.size === 0) break
|
||||
const cRes = await getProgramCourses(program.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
const courses = cRes.data?.data?.courses ?? []
|
||||
const moduleBatches = await Promise.all(
|
||||
courses.map((course) =>
|
||||
getTopLevelCourseModules(course.id, { limit: LIST_LIMIT, offset: 0 }),
|
||||
),
|
||||
)
|
||||
for (let i = 0; i < courses.length; i++) {
|
||||
for (const module of moduleBatches[i].data?.data?.modules ?? []) {
|
||||
if (ids.has(module.id)) {
|
||||
map.set(`MODULE:${module.id}`, module.name?.trim() || `Module #${module.id}`)
|
||||
ids.delete(module.id)
|
||||
}
|
||||
}
|
||||
if (ids.size === 0) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveExamPrepModuleTitles(
|
||||
ids: Set<number>,
|
||||
map: PracticeParentTitleMap,
|
||||
): Promise<void> {
|
||||
if (ids.size === 0) return
|
||||
const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 })
|
||||
const catalogCourses = coursesRes.data?.data?.catalog_courses ?? []
|
||||
for (const course of catalogCourses) {
|
||||
if (ids.size === 0) break
|
||||
const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
const units = unitsRes.data?.data?.units ?? []
|
||||
for (const unit of units) {
|
||||
const modulesRes = await getExamPrepUnitModules(unit.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
for (const module of modulesRes.data?.data?.modules ?? []) {
|
||||
if (ids.has(module.id)) {
|
||||
map.set(`MODULE:${module.id}`, module.name?.trim() || `Module #${module.id}`)
|
||||
ids.delete(module.id)
|
||||
}
|
||||
}
|
||||
if (ids.size === 0) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveLearnEnglishLessonTitles(
|
||||
ids: Set<number>,
|
||||
map: PracticeParentTitleMap,
|
||||
): Promise<void> {
|
||||
if (ids.size === 0) return
|
||||
const progRes = await getLearningPrograms({ limit: LIST_LIMIT, offset: 0 })
|
||||
const programs = progRes.data?.data?.programs ?? []
|
||||
for (const program of programs) {
|
||||
if (ids.size === 0) break
|
||||
const cRes = await getProgramCourses(program.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
const courses = cRes.data?.data?.courses ?? []
|
||||
for (const course of courses) {
|
||||
if (ids.size === 0) break
|
||||
const mRes = await getTopLevelCourseModules(course.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
const modules = mRes.data?.data?.modules ?? []
|
||||
const lessonBatches = await Promise.all(
|
||||
modules.map((module) =>
|
||||
getModuleLessons(module.id, { limit: LIST_LIMIT, offset: 0 }),
|
||||
),
|
||||
)
|
||||
for (let i = 0; i < modules.length; i++) {
|
||||
for (const lesson of lessonBatches[i].data?.data?.lessons ?? []) {
|
||||
if (ids.has(lesson.id)) {
|
||||
map.set(`LESSON:${lesson.id}`, lesson.title?.trim() || `Lesson #${lesson.id}`)
|
||||
ids.delete(lesson.id)
|
||||
}
|
||||
}
|
||||
if (ids.size === 0) break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveExamPrepLessonTitles(
|
||||
ids: Set<number>,
|
||||
map: PracticeParentTitleMap,
|
||||
): Promise<void> {
|
||||
if (ids.size === 0) return
|
||||
const coursesRes = await getExamPrepCatalogCourses({ limit: LIST_LIMIT, offset: 0 })
|
||||
const catalogCourses = coursesRes.data?.data?.catalog_courses ?? []
|
||||
for (const course of catalogCourses) {
|
||||
if (ids.size === 0) break
|
||||
const unitsRes = await getExamPrepCatalogUnits(course.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
const units = unitsRes.data?.data?.units ?? []
|
||||
for (const unit of units) {
|
||||
if (ids.size === 0) break
|
||||
const modulesRes = await getExamPrepUnitModules(unit.id, { limit: LIST_LIMIT, offset: 0 })
|
||||
const modules = modulesRes.data?.data?.modules ?? []
|
||||
for (const module of modules) {
|
||||
if (ids.size === 0) break
|
||||
const lessonsRes = await getExamPrepModuleLessons(module.id, {
|
||||
limit: LIST_LIMIT,
|
||||
offset: 0,
|
||||
})
|
||||
for (const lesson of lessonsRes.data?.data?.lessons ?? []) {
|
||||
if (ids.has(lesson.id)) {
|
||||
map.set(`LESSON:${lesson.id}`, lesson.title?.trim() || `Lesson #${lesson.id}`)
|
||||
ids.delete(lesson.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolvePracticeParentTitles(
|
||||
parents: PracticeParent[],
|
||||
hints?: PracticeParentTitleHints,
|
||||
): Promise<PracticeParentTitleMap> {
|
||||
const map: PracticeParentTitleMap = new Map()
|
||||
applyHints(map, hints)
|
||||
|
||||
const normalized = dedupeParents(parents)
|
||||
const unresolvedCourses = new Set<number>()
|
||||
const unresolvedModules = new Set<number>()
|
||||
const unresolvedLessons = new Set<number>()
|
||||
|
||||
for (const parent of normalized) {
|
||||
if (map.has(practiceParentKey(parent))) continue
|
||||
if (parent.parent_kind === "COURSE") unresolvedCourses.add(parent.parent_id)
|
||||
if (parent.parent_kind === "MODULE") unresolvedModules.add(parent.parent_id)
|
||||
if (parent.parent_kind === "LESSON") unresolvedLessons.add(parent.parent_id)
|
||||
}
|
||||
|
||||
await resolveLearnEnglishCourseTitles(unresolvedCourses, map)
|
||||
await resolveExamPrepCourseTitles(unresolvedCourses, map)
|
||||
await resolveLearnEnglishModuleTitles(unresolvedModules, map)
|
||||
await resolveExamPrepModuleTitles(unresolvedModules, map)
|
||||
await resolveLearnEnglishLessonTitles(unresolvedLessons, map)
|
||||
await resolveExamPrepLessonTitles(unresolvedLessons, map)
|
||||
|
||||
return map
|
||||
}
|
||||
131
src/lib/practiceParents.ts
Normal file
131
src/lib/practiceParents.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import type { PracticeParent, PracticeParentKind } from "../types/course.types"
|
||||
|
||||
const PARENT_KINDS: PracticeParentKind[] = ["COURSE", "MODULE", "LESSON"]
|
||||
|
||||
export function isPracticeParentKind(value: string): value is PracticeParentKind {
|
||||
return PARENT_KINDS.includes(value.toUpperCase() as PracticeParentKind)
|
||||
}
|
||||
|
||||
export function normalizePracticeParent(row: unknown): PracticeParent | null {
|
||||
if (!row || typeof row !== "object") return null
|
||||
const o = row as Record<string, unknown>
|
||||
const kind = String(o.parent_kind ?? o.ParentKind ?? o.parentKind ?? "")
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
const parent_id = Number(o.parent_id ?? o.ParentId ?? o.parentId ?? o.id ?? o.ID)
|
||||
if (!isPracticeParentKind(kind)) return null
|
||||
if (!Number.isFinite(parent_id) || parent_id <= 0) return null
|
||||
return { parent_kind: kind, parent_id }
|
||||
}
|
||||
|
||||
export function normalizePracticeParents(raw: unknown): PracticeParent[] {
|
||||
if (!raw || typeof raw !== "object") return []
|
||||
const o = raw as Record<string, unknown>
|
||||
const parentsRaw = o.parents ?? o.Parents
|
||||
if (Array.isArray(parentsRaw)) {
|
||||
return dedupeParents(
|
||||
parentsRaw
|
||||
.map((entry) => normalizePracticeParent(entry))
|
||||
.filter((entry): entry is PracticeParent => entry != null),
|
||||
)
|
||||
}
|
||||
const single = normalizePracticeParent(raw)
|
||||
return single ? [single] : []
|
||||
}
|
||||
|
||||
/** Rollout helper: `parents[]` or legacy `parent_kind` + `parent_id`. */
|
||||
export function parentsFromPractice(practice: {
|
||||
parents?: PracticeParent[] | null
|
||||
parent_kind?: string
|
||||
parent_id?: number
|
||||
}): PracticeParent[] {
|
||||
if (practice.parents == null) return []
|
||||
if (practice.parents.length > 0) return dedupeParents(practice.parents)
|
||||
const kind = practice.parent_kind?.trim().toUpperCase() ?? ""
|
||||
const parent_id = practice.parent_id
|
||||
if (isPracticeParentKind(kind) && parent_id != null && parent_id > 0) {
|
||||
return [{ parent_kind: kind, parent_id }]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
export function dedupeParents(parents: PracticeParent[]): PracticeParent[] {
|
||||
const seen = new Set<string>()
|
||||
return parents.filter((p) => {
|
||||
if (!isPracticeParentKind(p.parent_kind) || p.parent_id <= 0) return false
|
||||
const key = `${p.parent_kind}:${p.parent_id}`
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function validatePracticeParents(
|
||||
parents: PracticeParent[],
|
||||
options?: { required?: boolean },
|
||||
): string | null {
|
||||
const required = options?.required !== false
|
||||
const normalized = dedupeParents(parents)
|
||||
if (normalized.length === 0) {
|
||||
return required ? "Select at least one course, module, or lesson." : null
|
||||
}
|
||||
for (let i = 0; i < parents.length; i++) {
|
||||
const row = parents[i]
|
||||
if (!isPracticeParentKind(row.parent_kind)) {
|
||||
return `Location ${i + 1}: choose a valid parent type.`
|
||||
}
|
||||
if (!Number.isFinite(row.parent_id) || row.parent_id <= 0) {
|
||||
return `Location ${i + 1}: enter a valid parent id.`
|
||||
}
|
||||
}
|
||||
const validRows = parents.filter(
|
||||
(p) => isPracticeParentKind(p.parent_kind) && p.parent_id > 0,
|
||||
)
|
||||
if (dedupeParents(validRows).length !== validRows.length) {
|
||||
return "The same location is listed twice."
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function formatPracticeParentLabel(parent: PracticeParent): string {
|
||||
return `${parent.parent_kind} #${parent.parent_id}`
|
||||
}
|
||||
|
||||
export function formatPracticeParentsSummary(parents: PracticeParent[]): string {
|
||||
const list = dedupeParents(parents)
|
||||
if (list.length === 0) return "Not attached to any course, module, or lesson"
|
||||
return list.map(formatPracticeParentLabel).join(" · ")
|
||||
}
|
||||
|
||||
export function isPracticeUnlinked(practice: {
|
||||
parents?: PracticeParent[] | null
|
||||
parent_kind?: string
|
||||
parent_id?: number
|
||||
}): boolean {
|
||||
return parentsFromPractice(practice).length === 0
|
||||
}
|
||||
|
||||
/** API create payload: null when no locations selected. */
|
||||
export function buildCreatePracticeParentsPayload(
|
||||
parents: PracticeParent[],
|
||||
): PracticeParent[] | null {
|
||||
const normalized = dedupeParents(parents)
|
||||
return normalized.length > 0 ? normalized : null
|
||||
}
|
||||
|
||||
export function practiceParentsEqual(a: PracticeParent[], b: PracticeParent[]): boolean {
|
||||
const left = dedupeParents(a)
|
||||
const right = dedupeParents(b)
|
||||
if (left.length !== right.length) return false
|
||||
const rightKeys = new Set(right.map((p) => `${p.parent_kind}:${p.parent_id}`))
|
||||
return left.every((p) => rightKeys.has(`${p.parent_kind}:${p.parent_id}`))
|
||||
}
|
||||
|
||||
export function primaryPracticeParent(parents: PracticeParent[]): PracticeParent | null {
|
||||
const list = dedupeParents(parents)
|
||||
return list[0] ?? null
|
||||
}
|
||||
|
||||
export function newParentRow(kind: PracticeParentKind = "LESSON"): PracticeParent {
|
||||
return { parent_kind: kind, parent_id: 0 }
|
||||
}
|
||||
170
src/lib/questionAssociations.ts
Normal file
170
src/lib/questionAssociations.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
export interface QuestionAssociationRow {
|
||||
id: string
|
||||
serverQuestionId?: number | null
|
||||
displayOrder?: number
|
||||
associatedQuestionId?: number | null
|
||||
associatedAnchorRowId?: string | null
|
||||
prerequisiteQuestionIds?: number[]
|
||||
text?: string
|
||||
}
|
||||
|
||||
export function isQuestionSectionAnchor(row: QuestionAssociationRow): boolean {
|
||||
return row.associatedQuestionId == null && !row.associatedAnchorRowId
|
||||
}
|
||||
|
||||
export function findAnchorRowForQuestion(
|
||||
row: QuestionAssociationRow,
|
||||
allQuestions: QuestionAssociationRow[],
|
||||
): QuestionAssociationRow | undefined {
|
||||
if (isQuestionSectionAnchor(row)) return undefined
|
||||
if (row.associatedQuestionId != null) {
|
||||
return allQuestions.find((q) => q.serverQuestionId === row.associatedQuestionId)
|
||||
}
|
||||
if (row.associatedAnchorRowId) {
|
||||
return allQuestions.find((q) => q.id === row.associatedAnchorRowId)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function resolveAssociatedQuestionId(
|
||||
row: QuestionAssociationRow,
|
||||
allQuestions: QuestionAssociationRow[],
|
||||
rowIdToServerId?: Map<string, number>,
|
||||
): number | null {
|
||||
if (isQuestionSectionAnchor(row)) return null
|
||||
if (row.associatedQuestionId != null && row.associatedQuestionId > 0) {
|
||||
return row.associatedQuestionId
|
||||
}
|
||||
const anchorRow = findAnchorRowForQuestion(row, allQuestions)
|
||||
if (!anchorRow) return null
|
||||
if (anchorRow.serverQuestionId != null && anchorRow.serverQuestionId > 0) {
|
||||
return anchorRow.serverQuestionId
|
||||
}
|
||||
if (rowIdToServerId?.has(anchorRow.id)) {
|
||||
return rowIdToServerId.get(anchorRow.id) ?? null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function validateQuestionAssociations(
|
||||
questions: QuestionAssociationRow[],
|
||||
): string | null {
|
||||
for (const q of questions) {
|
||||
if (isQuestionSectionAnchor(q)) continue
|
||||
|
||||
const selfId = q.serverQuestionId
|
||||
const assocId = resolveAssociatedQuestionId(q, questions)
|
||||
const anchor = findAnchorRowForQuestion(q, questions)
|
||||
|
||||
if (!anchor) {
|
||||
return `Question ${q.displayOrder ?? "?"}: select a section anchor or mark it as starting a new section.`
|
||||
}
|
||||
|
||||
if (selfId != null && assocId === selfId) {
|
||||
return "A question cannot be associated with itself."
|
||||
}
|
||||
|
||||
if (!isQuestionSectionAnchor(anchor)) {
|
||||
return `Question ${q.displayOrder ?? "?"}: associated question must be a section anchor.`
|
||||
}
|
||||
|
||||
const anchorOrder = anchor.displayOrder ?? 0
|
||||
const questionOrder = q.displayOrder ?? 0
|
||||
if (anchorOrder >= questionOrder) {
|
||||
return `Question ${q.displayOrder ?? "?"}: section anchor must appear before this question.`
|
||||
}
|
||||
|
||||
if (
|
||||
assocId == null &&
|
||||
anchor.serverQuestionId == null &&
|
||||
!q.associatedAnchorRowId
|
||||
) {
|
||||
return `Question ${q.displayOrder ?? "?"}: select a section anchor or mark it as starting a new section.`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function getSectionAnchorOptions(
|
||||
questions: QuestionAssociationRow[],
|
||||
currentRowId: string,
|
||||
): { value: number | string; label: string; serverId: number | null }[] {
|
||||
return questions
|
||||
.filter((q) => q.id !== currentRowId && isQuestionSectionAnchor(q))
|
||||
.sort((a, b) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0))
|
||||
.map((q) => ({
|
||||
value: q.serverQuestionId ?? q.id,
|
||||
label: `Q${q.displayOrder ?? "?"} — ${summarizeQuestionLabel(q)}`,
|
||||
serverId: q.serverQuestionId ?? null,
|
||||
}))
|
||||
}
|
||||
|
||||
export function summarizeQuestionLabel(row: QuestionAssociationRow): string {
|
||||
const text = String(row.text ?? "").trim()
|
||||
if (text) return text.length > 48 ? `${text.slice(0, 48)}…` : text
|
||||
if (row.serverQuestionId) return `Question #${row.serverQuestionId}`
|
||||
return "New question"
|
||||
}
|
||||
|
||||
export function sectionBadgeLabel(
|
||||
row: QuestionAssociationRow,
|
||||
allQuestions: QuestionAssociationRow[],
|
||||
): string {
|
||||
if (isQuestionSectionAnchor(row)) return "Section anchor"
|
||||
const anchor = findAnchorRowForQuestion(row, allQuestions)
|
||||
if (!anchor) return "No section"
|
||||
const sectionIndex =
|
||||
allQuestions
|
||||
.filter((q) => isQuestionSectionAnchor(q))
|
||||
.sort((a, b) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0))
|
||||
.findIndex((q) => q.id === anchor.id) + 1
|
||||
return sectionIndex > 0 ? `Section ${sectionIndex}` : "Linked section"
|
||||
}
|
||||
|
||||
export function fixAssociationsAfterReorder<T extends QuestionAssociationRow>(
|
||||
questions: T[],
|
||||
): T[] {
|
||||
return questions.map((q) => {
|
||||
if (isQuestionSectionAnchor(q)) return q
|
||||
const anchor = findAnchorRowForQuestion(q, questions)
|
||||
if (!anchor) {
|
||||
return { ...q, associatedQuestionId: null, associatedAnchorRowId: null }
|
||||
}
|
||||
if ((anchor.displayOrder ?? 0) >= (q.displayOrder ?? 0)) {
|
||||
return { ...q, associatedQuestionId: null, associatedAnchorRowId: null }
|
||||
}
|
||||
return q
|
||||
})
|
||||
}
|
||||
|
||||
export function setQuestionAsSectionAnchor<T extends QuestionAssociationRow>(
|
||||
row: T,
|
||||
): T {
|
||||
return { ...row, associatedQuestionId: null, associatedAnchorRowId: null }
|
||||
}
|
||||
|
||||
export function setQuestionSectionAnchorRef<T extends QuestionAssociationRow>(
|
||||
row: T,
|
||||
anchor: QuestionAssociationRow,
|
||||
): T {
|
||||
if (anchor.serverQuestionId != null && anchor.serverQuestionId > 0) {
|
||||
return {
|
||||
...row,
|
||||
associatedQuestionId: anchor.serverQuestionId,
|
||||
associatedAnchorRowId: null,
|
||||
}
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
associatedQuestionId: null,
|
||||
associatedAnchorRowId: anchor.id,
|
||||
}
|
||||
}
|
||||
|
||||
export function findLastSectionAnchor<T extends QuestionAssociationRow>(
|
||||
questions: T[],
|
||||
): T | undefined {
|
||||
const anchors = questions.filter((q) => isQuestionSectionAnchor(q))
|
||||
if (anchors.length === 0) return undefined
|
||||
return [...anchors].sort((a, b) => (b.displayOrder ?? 0) - (a.displayOrder ?? 0))[0]
|
||||
}
|
||||
|
|
@ -148,7 +148,7 @@ export function AcceptInvitePage() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen overflow-hidden">
|
||||
<div className="relative flex h-dvh overflow-hidden">
|
||||
<div className="relative hidden items-center justify-center bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400 lg:flex lg:w-1/2 xl:w-[55%]">
|
||||
<div className="absolute inset-0 overflow-hidden">
|
||||
<div className="absolute -left-20 -top-20 h-96 w-96 rounded-full bg-white/5" />
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ export function ForgotPasswordPage() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen overflow-hidden">
|
||||
<div className="relative flex h-dvh overflow-y-auto">
|
||||
{/* Decorative left panel */}
|
||||
<div className="hidden lg:flex lg:w-1/2 xl:w-[55%] items-center justify-center bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400 relative">
|
||||
{/* Abstract decorative shapes */}
|
||||
|
|
|
|||
|
|
@ -216,7 +216,7 @@ export function LoginPage() {
|
|||
const googleClientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen overflow-hidden">
|
||||
<div className="relative flex h-dvh overflow-y-auto">
|
||||
{/* Decorative left panel */}
|
||||
<div className="hidden lg:flex lg:w-1/2 xl:w-[55%] items-center justify-center bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400 relative">
|
||||
{/* Abstract decorative shapes */}
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ export function VerificationPage() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-grayScale-100 px-4 py-12">
|
||||
<div className="flex h-dvh items-center justify-center overflow-y-auto bg-grayScale-100 px-4 py-12">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="rounded-2xl bg-white p-8 shadow-soft">
|
||||
<div className="mb-8">
|
||||
|
|
|
|||
|
|
@ -19,6 +19,12 @@ import {
|
|||
validateLearnEnglishQuestionsWithDefinitions,
|
||||
} from "../../lib/learnEnglishPracticePublish";
|
||||
import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator";
|
||||
import {
|
||||
buildCreatePracticeParentsPayload,
|
||||
dedupeParents,
|
||||
formatPracticeParentsSummary,
|
||||
validatePracticeParents,
|
||||
} from "../../lib/practiceParents";
|
||||
|
||||
import { ContextStep } from "./components/practice-steps/ContextStep";
|
||||
import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||
|
|
@ -41,19 +47,25 @@ export function AddPracticeFlow() {
|
|||
courseId: routeCourseId,
|
||||
unitId: routeUnitId,
|
||||
moduleId: routeModuleId,
|
||||
definitionId: routeDefinitionId,
|
||||
} = useParams<{
|
||||
level?: string;
|
||||
programType?: string;
|
||||
courseId?: string;
|
||||
unitId?: string;
|
||||
moduleId?: string;
|
||||
definitionId?: string;
|
||||
}>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const backToParam = searchParams.get("backTo");
|
||||
const lessonId = searchParams.get("lessonId");
|
||||
const lessonTitleRaw = searchParams.get("lessonTitle");
|
||||
|
||||
const isExamPrep = Boolean(programType?.trim());
|
||||
const seedDefinitionId = routeDefinitionId ? Number(routeDefinitionId) : NaN;
|
||||
const isFromQuestionType =
|
||||
Number.isFinite(seedDefinitionId) && seedDefinitionId > 0;
|
||||
|
||||
const isExamPrep = Boolean(programType?.trim()) && !isFromQuestionType;
|
||||
|
||||
const effectiveBackTo = useMemo(() => {
|
||||
if (backToParam?.trim()) return backToParam.trim();
|
||||
|
|
@ -128,8 +140,9 @@ export function AddPracticeFlow() {
|
|||
? `Program ${level}`
|
||||
: null;
|
||||
|
||||
const backLabel =
|
||||
effectiveBackTo === "module"
|
||||
const backLabel = isFromQuestionType
|
||||
? "Back to Question Types"
|
||||
: effectiveBackTo === "module"
|
||||
? "Back to Module"
|
||||
: effectiveBackTo === "modules"
|
||||
? "Back to Modules"
|
||||
|
|
@ -140,6 +153,7 @@ export function AddPracticeFlow() {
|
|||
: "Back to Courses";
|
||||
|
||||
const backPath = useMemo(() => {
|
||||
if (isFromQuestionType) return "/new-content/question-types";
|
||||
if (isExamPrep) {
|
||||
if (
|
||||
effectiveBackTo === "module" &&
|
||||
|
|
@ -173,6 +187,7 @@ export function AddPracticeFlow() {
|
|||
unitId,
|
||||
moduleId,
|
||||
level,
|
||||
isFromQuestionType,
|
||||
]);
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(1);
|
||||
|
|
@ -193,10 +208,15 @@ export function AddPracticeFlow() {
|
|||
storyImageUrl: "",
|
||||
shuffleQuestions: false,
|
||||
tips: "",
|
||||
parents: [] as { parent_kind: PracticeParentKind; parent_id: number }[],
|
||||
questions: [
|
||||
{
|
||||
id: "q1",
|
||||
displayOrder: 1,
|
||||
serverQuestionId: null as number | null,
|
||||
associatedQuestionId: null as number | null,
|
||||
associatedAnchorRowId: null as string | null,
|
||||
prerequisiteQuestionIds: [] as number[],
|
||||
questionTypeDefinitionId: null as number | null,
|
||||
text: "",
|
||||
difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD",
|
||||
|
|
@ -251,7 +271,9 @@ export function AddPracticeFlow() {
|
|||
...fd,
|
||||
questions: fd.questions.map((q) => {
|
||||
if (q.questionTypeDefinitionId != null) return q;
|
||||
const def = typeDefinitions[0];
|
||||
const def = isFromQuestionType
|
||||
? typeDefinitions.find((d) => d.id === seedDefinitionId) ?? typeDefinitions[0]
|
||||
: typeDefinitions[0];
|
||||
return {
|
||||
...q,
|
||||
questionTypeDefinitionId: def.id,
|
||||
|
|
@ -259,16 +281,58 @@ export function AddPracticeFlow() {
|
|||
};
|
||||
}),
|
||||
}));
|
||||
}, [typeDefinitions]);
|
||||
}, [typeDefinitions, isFromQuestionType, seedDefinitionId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isFromQuestionType || typeDefinitions.length === 0) return;
|
||||
const def = typeDefinitions.find((d) => d.id === seedDefinitionId);
|
||||
if (!def) return;
|
||||
setFormData((fd) => ({
|
||||
...fd,
|
||||
questions: fd.questions.map((q, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...q,
|
||||
questionTypeDefinitionId: def.id,
|
||||
dynamicFieldValues: emptyDynamicFieldValuesForDefinition(def),
|
||||
}
|
||||
: q,
|
||||
),
|
||||
}));
|
||||
}, [isFromQuestionType, seedDefinitionId, typeDefinitions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!parentContext || isExamPrep) return;
|
||||
setFormData((fd) => {
|
||||
const seeded = dedupeParents([
|
||||
{ parent_kind: parentContext.kind, parent_id: parentContext.id },
|
||||
...(fd.parents ?? []),
|
||||
]);
|
||||
return { ...fd, parents: seeded };
|
||||
});
|
||||
}, [parentContext, isExamPrep]);
|
||||
|
||||
const submitPractice = async (status: "DRAFT" | "PUBLISHED") => {
|
||||
if (!parentContext) {
|
||||
if (!parentContext && !isExamPrep && !isFromQuestionType) {
|
||||
toast.error("Missing practice parent", {
|
||||
description:
|
||||
"Open this screen from a course, module, or lesson so the API receives parent_kind and parent_id.",
|
||||
"Open this screen from a course, module, or lesson so the API receives at least one parent location.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const parents = dedupeParents(
|
||||
isExamPrep && parentContext
|
||||
? [{ parent_kind: parentContext.kind, parent_id: parentContext.id }]
|
||||
: formData.parents,
|
||||
);
|
||||
const parentsErr = validatePracticeParents(parents, {
|
||||
required: !isFromQuestionType,
|
||||
});
|
||||
if (parentsErr) {
|
||||
toast.error("Check practice locations", { description: parentsErr });
|
||||
return;
|
||||
}
|
||||
const createParents = buildCreatePracticeParentsPayload(parents);
|
||||
if (
|
||||
!isLearnEnglishLessonPractice &&
|
||||
(!formData.title.trim() || !formData.description.trim())
|
||||
|
|
@ -293,6 +357,7 @@ export function AddPracticeFlow() {
|
|||
}
|
||||
const persona = personaFromId(selectedPersona, personas);
|
||||
const mappedQuestions = formData.questions.map((q, index) => ({
|
||||
clientRowId: q.id,
|
||||
questionText: String(q.text ?? "").trim(),
|
||||
questionTypeDefinitionId: Number(q.questionTypeDefinitionId),
|
||||
difficultyLevel: (q.difficultyLevel ?? "EASY") as
|
||||
|
|
@ -304,6 +369,8 @@ export function AddPracticeFlow() {
|
|||
Number.isFinite(Number(q.displayOrder)) && Number(q.displayOrder) > 0
|
||||
? Number(q.displayOrder)
|
||||
: index + 1,
|
||||
associatedQuestionId: q.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
|
||||
dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) },
|
||||
mcqOptions: (q.mcqOptions ?? []).map(
|
||||
(o: { text?: string; isCorrect?: boolean }) => ({
|
||||
|
|
@ -331,15 +398,17 @@ export function AddPracticeFlow() {
|
|||
const useExamPrepLessonApi =
|
||||
isExamPrep &&
|
||||
isLessonPractice &&
|
||||
parentContext.kind === "LESSON" &&
|
||||
parentContext?.kind === "LESSON" &&
|
||||
parentContext != null &&
|
||||
Number.isFinite(parentContext.id);
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await executePracticeCreation({
|
||||
parentKind: parentContext.kind,
|
||||
parentId: parentContext.id,
|
||||
examPrepLessonId: useExamPrepLessonApi ? parentContext.id : undefined,
|
||||
parents: createParents,
|
||||
parentKind: parentContext?.kind,
|
||||
parentId: parentContext?.id,
|
||||
examPrepLessonId: useExamPrepLessonApi ? parentContext!.id : undefined,
|
||||
status,
|
||||
questionSetTitle: isLearnEnglishLessonPractice
|
||||
? lessonDefaultTitle
|
||||
|
|
@ -393,9 +462,13 @@ export function AddPracticeFlow() {
|
|||
Practice Published Successfully!
|
||||
</h1>
|
||||
<p className="text-grayScale-600 text-md mb-14 max-w-lg font-medium leading-relaxed">
|
||||
{lessonId
|
||||
? "Your speaking practice is saved and linked to this lesson’s question set."
|
||||
: "Your speaking practice is saved for the linked course or module."}
|
||||
{isFromQuestionType
|
||||
? dedupeParents(formData.parents).length > 0
|
||||
? "Your practice is saved with the selected locations. You can edit questions or attach more locations anytime."
|
||||
: "Your practice is saved as a draft shell. Attach it to courses, modules, or lessons when you are ready."
|
||||
: lessonId
|
||||
? "Your speaking practice is saved and linked to this lesson’s question set."
|
||||
: "Your speaking practice is saved for the linked course or module."}
|
||||
</p>
|
||||
<div className="flex flex-col gap-4 w-full max-w-[400px]">
|
||||
<Button
|
||||
|
|
@ -419,6 +492,10 @@ export function AddPracticeFlow() {
|
|||
{
|
||||
id: "q1",
|
||||
displayOrder: 1,
|
||||
serverQuestionId: null as number | null,
|
||||
associatedQuestionId: null as number | null,
|
||||
associatedAnchorRowId: null as string | null,
|
||||
prerequisiteQuestionIds: [] as number[],
|
||||
questionTypeDefinitionId:
|
||||
typeDefinitions[0]?.id ?? (null as number | null),
|
||||
text: "",
|
||||
|
|
@ -449,8 +526,20 @@ export function AddPracticeFlow() {
|
|||
);
|
||||
}
|
||||
|
||||
const useLearnEnglishContextStep =
|
||||
(Boolean(parentContext) && !isExamPrep) || isFromQuestionType;
|
||||
|
||||
const reviewParentSummary =
|
||||
formData.parents.length > 0
|
||||
? formatPracticeParentsSummary(formData.parents)
|
||||
: isFromQuestionType
|
||||
? formatPracticeParentsSummary([])
|
||||
: parentSummary;
|
||||
|
||||
const seededQuestionType = typeDefinitions.find((d) => d.id === seedDefinitionId);
|
||||
|
||||
const renderStep = () => {
|
||||
if (isModuleContext) {
|
||||
if (useLearnEnglishContextStep) {
|
||||
switch (currentStep) {
|
||||
case 1:
|
||||
return (
|
||||
|
|
@ -503,9 +592,14 @@ export function AddPracticeFlow() {
|
|||
prevStep={prevStep}
|
||||
onEditContext={() => setCurrentStep(1)}
|
||||
onEditQuestions={() => setCurrentStep(3)}
|
||||
parentSummary={parentSummary}
|
||||
parentSummary={reviewParentSummary}
|
||||
typeDefinitions={typeDefinitions}
|
||||
canPublish={parentContext !== null}
|
||||
canPublish={
|
||||
isFromQuestionType ||
|
||||
formData.parents.length > 0 ||
|
||||
parentContext !== null
|
||||
}
|
||||
allowUnlinkedParents={isFromQuestionType}
|
||||
submitting={submitting}
|
||||
onSaveDraft={() => void submitPractice("DRAFT")}
|
||||
onPublish={() => void submitPractice("PUBLISHED")}
|
||||
|
|
@ -594,7 +688,7 @@ export function AddPracticeFlow() {
|
|||
<div className=" mb-10">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold text-[#0F172A]">
|
||||
Add New Practice
|
||||
{isFromQuestionType ? "Create Practice from Question Type" : "Add New Practice"}
|
||||
</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
|
|
@ -605,8 +699,20 @@ export function AddPracticeFlow() {
|
|||
</Button>
|
||||
</div>
|
||||
<p className="text-grayScale-400 text-base">
|
||||
Create a practice with story details, a persona, and questions from your question type library.
|
||||
{isFromQuestionType
|
||||
? `Build a practice using ${seededQuestionType?.display_name ?? "the selected question type"}. Locations are optional — attach courses, modules, or lessons later.`
|
||||
: "Create a practice with story details, a persona, and questions from your question type library."}
|
||||
</p>
|
||||
{isFromQuestionType && seededQuestionType ? (
|
||||
<div className="mt-4 rounded-xl border border-violet-200 bg-violet-50/80 px-4 py-3 text-sm text-violet-950">
|
||||
<p className="font-semibold text-violet-900">Question type</p>
|
||||
<p className="mt-1 text-violet-800/90">
|
||||
<span className="font-medium">{seededQuestionType.display_name}</span>
|
||||
<span className="mx-1.5 text-violet-400">·</span>
|
||||
<span className="font-mono text-xs">#{seededQuestionType.id}</span>
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
{lessonId ? (
|
||||
<div className="mt-4 rounded-xl border border-violet-200 bg-violet-50/80 px-4 py-3 text-sm text-violet-950">
|
||||
<p className="font-semibold text-violet-900">Lesson practice</p>
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { Card } from "../../components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
|
|
@ -552,18 +553,20 @@ export function CourseDetailPage() {
|
|||
</ContentPageDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
variant="outline"
|
||||
className="rounded-[6px] border-brand-500 text-brand-500 "
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/new-content/learn-english/${programIdParam}/courses/add-practice?backTo=modules&courseId=${courseIdParam}`,
|
||||
)
|
||||
}
|
||||
pathOptions={{
|
||||
isExamPrep: false,
|
||||
level: programIdParam,
|
||||
courseId: courseIdParam,
|
||||
backTo: "modules",
|
||||
}}
|
||||
parentLabel={displayTitle}
|
||||
>
|
||||
<Calendar className="h-4 w-4" />
|
||||
Add Practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
<Button
|
||||
className="rounded-[6px] bg-brand-500 font-semibold hover:bg-brand-600"
|
||||
onClick={() => setIsAddModuleOpen(true)}
|
||||
|
|
@ -901,18 +904,20 @@ export function CourseDetailPage() {
|
|||
: "Try another status filter or add a new practice."}
|
||||
</p>
|
||||
{practices.length === 0 ? (
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
variant="outline"
|
||||
className="flex h-12 items-center gap-2 rounded-xl border-brand-500 px-8 font-bold text-brand-500 transition-all hover:bg-brand-50"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/new-content/learn-english/${programIdParam}/courses/add-practice?backTo=modules&courseId=${courseIdParam}`,
|
||||
)
|
||||
}
|
||||
pathOptions={{
|
||||
isExamPrep: false,
|
||||
level: programIdParam,
|
||||
courseId: courseIdParam,
|
||||
backTo: "modules",
|
||||
}}
|
||||
parentLabel={displayTitle}
|
||||
>
|
||||
<Calendar className="h-5 w-5" />
|
||||
Add Practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,12 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|||
import { ArrowLeft, Plus, FileText, Video } from "lucide-react";
|
||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
||||
import {
|
||||
buildPracticeContentPaths,
|
||||
type PracticeContentPathOptions,
|
||||
} from "../../lib/practiceContentPaths";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Card } from "../../components/ui/card";
|
||||
import {
|
||||
|
|
@ -78,6 +84,25 @@ export function CourseModuleDetailPage() {
|
|||
const parsedUnitId = Number(unitId);
|
||||
|
||||
const [activeTab, setActiveTab] = useState<"video" | "practice">("video");
|
||||
const [lessonPracticeChoice, setLessonPracticeChoice] =
|
||||
useState<PracticeContentPathOptions | null>(null);
|
||||
const lessonPracticeChoicePaths = useMemo(
|
||||
() =>
|
||||
lessonPracticeChoice
|
||||
? buildPracticeContentPaths(lessonPracticeChoice)
|
||||
: null,
|
||||
[lessonPracticeChoice],
|
||||
);
|
||||
const modulePracticePathOptions = useMemo(
|
||||
(): PracticeContentPathOptions => ({
|
||||
isExamPrep: true,
|
||||
programType,
|
||||
courseId,
|
||||
unitId,
|
||||
moduleId,
|
||||
}),
|
||||
[programType, courseId, unitId, moduleId],
|
||||
);
|
||||
const [moduleTitle, setModuleTitle] = useState("Module");
|
||||
const [moduleDescription, setModuleDescription] = useState("—");
|
||||
const [modulePublishStatus, setModulePublishStatus] = useState<
|
||||
|
|
@ -631,9 +656,6 @@ export function CourseModuleDetailPage() {
|
|||
}
|
||||
};
|
||||
|
||||
const lessonAttachPracticePath = (lesson: (typeof lessons)[number]) =>
|
||||
`/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/add-practice?lessonId=${lesson.id}&lessonTitle=${encodeURIComponent(lesson.title)}`;
|
||||
|
||||
const lessonPracticesPath = (lesson: (typeof lessons)[number]) =>
|
||||
`/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/lessons/${lesson.id}/practices?lessonTitle=${encodeURIComponent(lesson.title)}`;
|
||||
|
||||
|
|
@ -668,18 +690,15 @@ export function CourseModuleDetailPage() {
|
|||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
variant="outline"
|
||||
className="h-10 px-6 rounded-[6px] border-brand-500 text-brand-500 font-bold hover:bg-brand-50 transition-all flex items-center gap-2 shadow-sm"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/add-practice`,
|
||||
)
|
||||
}
|
||||
pathOptions={modulePracticePathOptions}
|
||||
parentLabel={moduleTitle}
|
||||
>
|
||||
<FileText className="h-5 w-5" />
|
||||
Add Practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
<Dialog
|
||||
open={createLessonOpen}
|
||||
onOpenChange={(open) => {
|
||||
|
|
@ -947,7 +966,17 @@ export function CourseModuleDetailPage() {
|
|||
onEdit={() => openEditLesson(lesson)}
|
||||
onDelete={() => setDeletingLessonId(lesson.id)}
|
||||
description={lesson.description}
|
||||
onAddPractice={() => navigate(lessonAttachPracticePath(lesson))}
|
||||
onAddPractice={() =>
|
||||
setLessonPracticeChoice({
|
||||
isExamPrep: true,
|
||||
programType,
|
||||
courseId,
|
||||
unitId,
|
||||
moduleId,
|
||||
lessonId: String(lesson.id),
|
||||
lessonTitle: lesson.title,
|
||||
})
|
||||
}
|
||||
onViewPractices={() => navigate(lessonPracticesPath(lesson))}
|
||||
onTogglePublishStatus={(nextStatus) =>
|
||||
void handleToggleLessonPublishStatus(lesson.id, nextStatus)
|
||||
|
|
@ -1197,6 +1226,23 @@ export function CourseModuleDetailPage() {
|
|||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{lessonPracticeChoice && lessonPracticeChoicePaths ? (
|
||||
<PracticeActionChoiceDialog
|
||||
open={lessonPracticeChoice != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setLessonPracticeChoice(null)
|
||||
}}
|
||||
createHref={lessonPracticeChoicePaths.create}
|
||||
attachHref={lessonPracticeChoicePaths.attach}
|
||||
pathOptions={lessonPracticeChoice}
|
||||
parentLabel={
|
||||
lessonPracticeChoice.lessonTitle
|
||||
? `Lesson — ${lessonPracticeChoice.lessonTitle}`
|
||||
: null
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Link,
|
||||
useNavigate,
|
||||
|
|
@ -21,6 +21,13 @@ import {
|
|||
validateLearnEnglishQuestionsWithDefinitions,
|
||||
} from "../../lib/learnEnglishPracticePublish";
|
||||
import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator";
|
||||
import {
|
||||
dedupeParents,
|
||||
formatPracticeParentsSummary,
|
||||
practiceParentsEqual,
|
||||
validatePracticeParents,
|
||||
} from "../../lib/practiceParents";
|
||||
import type { PracticeParent } from "../../types/course.types";
|
||||
import {
|
||||
mapPracticeFullToFormState,
|
||||
unwrapPracticeFullData,
|
||||
|
|
@ -223,6 +230,7 @@ export function EditPracticeFlow() {
|
|||
storyImageUrl: "",
|
||||
shuffleQuestions: false,
|
||||
tips: "",
|
||||
parents: [] as PracticeParent[],
|
||||
questions: [
|
||||
{
|
||||
id: "q1",
|
||||
|
|
@ -250,6 +258,7 @@ export function EditPracticeFlow() {
|
|||
);
|
||||
const [definitionsLoading, setDefinitionsLoading] = useState(true);
|
||||
const [definitionsError, setDefinitionsError] = useState<string | null>(null);
|
||||
const initialParentsRef = useRef<PracticeParent[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
|
@ -292,6 +301,7 @@ export function EditPracticeFlow() {
|
|||
if (cancelled) return;
|
||||
setFormData(mapped.formData);
|
||||
setPreservedQuestionSet(mapped.preservedQuestionSet);
|
||||
initialParentsRef.current = mapped.parents;
|
||||
if (mapped.personaId != null) {
|
||||
setSelectedPersona(String(mapped.personaId));
|
||||
}
|
||||
|
|
@ -337,6 +347,7 @@ export function EditPracticeFlow() {
|
|||
}
|
||||
|
||||
const mappedQuestions = formData.questions.map((q, index) => ({
|
||||
clientRowId: q.id,
|
||||
questionText: String(q.text ?? "").trim(),
|
||||
questionTypeDefinitionId: Number(q.questionTypeDefinitionId),
|
||||
difficultyLevel: (q.difficultyLevel ?? "EASY") as "EASY" | "MEDIUM" | "HARD",
|
||||
|
|
@ -346,6 +357,8 @@ export function EditPracticeFlow() {
|
|||
? Number(q.displayOrder)
|
||||
: index + 1,
|
||||
serverQuestionId: q.serverQuestionId ?? null,
|
||||
associatedQuestionId: q.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: q.associatedAnchorRowId ?? null,
|
||||
dynamicFieldValues: { ...(q.dynamicFieldValues ?? {}) },
|
||||
mcqOptions: (q.mcqOptions ?? []).map(
|
||||
(o: { text?: string; isCorrect?: boolean }) => ({
|
||||
|
|
@ -370,6 +383,14 @@ export function EditPracticeFlow() {
|
|||
lessonTitleDisplay?.trim() ||
|
||||
(lessonId ? `Lesson ${lessonId} practice` : "Lesson practice");
|
||||
|
||||
if (!isExamPrep) {
|
||||
const parentsErr = validatePracticeParents(formData.parents);
|
||||
if (parentsErr) {
|
||||
toast.error("Check practice locations", { description: parentsErr });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await executePracticeUpdate({
|
||||
|
|
@ -386,10 +407,17 @@ export function EditPracticeFlow() {
|
|||
definitions: typeDefinitions,
|
||||
isLearnEnglishLessonPractice,
|
||||
lessonDefaultTitle,
|
||||
parents: dedupeParents(formData.parents),
|
||||
parentsChanged:
|
||||
!isExamPrep &&
|
||||
!practiceParentsEqual(formData.parents, initialParentsRef.current),
|
||||
});
|
||||
toast.success(
|
||||
status === "PUBLISHED" ? "Practice updated and published" : "Practice saved as draft",
|
||||
);
|
||||
if (!isExamPrep) {
|
||||
initialParentsRef.current = dedupeParents(formData.parents);
|
||||
}
|
||||
setIsSaved(true);
|
||||
} catch (e) {
|
||||
toast.error("Could not update practice", {
|
||||
|
|
@ -466,6 +494,11 @@ export function EditPracticeFlow() {
|
|||
);
|
||||
}
|
||||
|
||||
const reviewParentSummary =
|
||||
formData.parents.length > 0
|
||||
? formatPracticeParentsSummary(formData.parents)
|
||||
: parentSummary;
|
||||
|
||||
const renderStep = () => {
|
||||
const useContextStep =
|
||||
isModuleContext || isCourseContext || isLessonContext;
|
||||
|
|
@ -481,7 +514,8 @@ export function EditPracticeFlow() {
|
|||
onCancel={() => navigate(backPath)}
|
||||
isLessonPractice={isLearnEnglishLessonPractice}
|
||||
lessonTitle={lessonTitleDisplay}
|
||||
parentSummary={parentSummary}
|
||||
parentSummary={reviewParentSummary}
|
||||
showParentsEditor={!isExamPrep}
|
||||
/>
|
||||
);
|
||||
case 2:
|
||||
|
|
@ -523,7 +557,7 @@ export function EditPracticeFlow() {
|
|||
prevStep={prevStep}
|
||||
onEditContext={() => setCurrentStep(1)}
|
||||
onEditQuestions={() => setCurrentStep(3)}
|
||||
parentSummary={parentSummary}
|
||||
parentSummary={reviewParentSummary}
|
||||
typeDefinitions={typeDefinitions}
|
||||
canPublish
|
||||
submitting={submitting}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import {
|
|||
} from "../../api/courses.api";
|
||||
import { Badge } from "../../components/ui/badge";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { Card, CardContent } from "../../components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
|
|
@ -68,6 +69,7 @@ function mapExamPrepPracticeToCard(
|
|||
): ParentContextPractice {
|
||||
return {
|
||||
id: practice.id,
|
||||
parents: [{ parent_kind: "LESSON", parent_id: practice.lesson_id }],
|
||||
parent_kind: "LESSON",
|
||||
parent_id: practice.lesson_id,
|
||||
title: practice.title,
|
||||
|
|
@ -332,9 +334,31 @@ export function LessonPracticesPage() {
|
|||
const displayTitle =
|
||||
lessonTitle || (validLesson ? `Lesson #${lid}` : "Lesson practices");
|
||||
|
||||
const addPracticeHref = isExamPrep
|
||||
? `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/add-practice?lessonId=${lid}&lessonTitle=${encodeURIComponent(lessonTitle || displayTitle)}`
|
||||
: `/new-content/learn-english/${level}/courses/add-practice?backTo=module&courseId=${courseId}&moduleId=${moduleId}&lessonId=${lid}&lessonTitle=${encodeURIComponent(lessonTitle || displayTitle)}`;
|
||||
const practicePathOptions = useMemo(
|
||||
() => ({
|
||||
isExamPrep,
|
||||
level,
|
||||
programType,
|
||||
courseId,
|
||||
unitId,
|
||||
moduleId,
|
||||
lessonId: validLesson ? String(lid) : null,
|
||||
lessonTitle: lessonTitle || displayTitle,
|
||||
backTo: isExamPrep ? "lesson" : "module",
|
||||
}),
|
||||
[
|
||||
isExamPrep,
|
||||
level,
|
||||
programType,
|
||||
courseId,
|
||||
unitId,
|
||||
moduleId,
|
||||
validLesson,
|
||||
lid,
|
||||
lessonTitle,
|
||||
displayTitle,
|
||||
],
|
||||
);
|
||||
|
||||
const editPracticeHref = (practiceId: number) => {
|
||||
const titleQuery = lessonTitle
|
||||
|
|
@ -449,14 +473,15 @@ export function LessonPracticesPage() {
|
|||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col gap-2 sm:flex-row lg:flex-col">
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
type="button"
|
||||
className="h-11 rounded-xl bg-brand-500 px-6 font-semibold shadow-md shadow-brand-500/20 hover:bg-brand-600"
|
||||
onClick={() => void navigate(addPracticeHref)}
|
||||
pathOptions={practicePathOptions}
|
||||
parentLabel={displayTitle}
|
||||
>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Add practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
|
|
@ -528,14 +553,15 @@ export function LessonPracticesPage() {
|
|||
give learners a structured speaking activity after the video.
|
||||
</p>
|
||||
<div className="mt-8 flex flex-col gap-3 sm:flex-row">
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
type="button"
|
||||
className="h-11 rounded-xl bg-brand-500 px-8 font-semibold shadow-md shadow-brand-500/15 hover:bg-brand-600"
|
||||
onClick={() => void navigate(addPracticeHref)}
|
||||
pathOptions={practicePathOptions}
|
||||
parentLabel={displayTitle}
|
||||
>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Create practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
|
|
|
|||
309
src/pages/content-management/LinkExistingPracticeFlow.tsx
Normal file
309
src/pages/content-management/LinkExistingPracticeFlow.tsx
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
import { useMemo, useState } from "react"
|
||||
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom"
|
||||
import { ArrowLeft, Link2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Stepper } from "../../components/ui/stepper"
|
||||
import successIcon from "../../assets/success.svg"
|
||||
import type { ParentContextPractice, PracticeParentKind } from "../../types/course.types"
|
||||
import { attachPracticeToParent } from "../../lib/attachPracticeToParent"
|
||||
import { learnEnglishPracticeApiErrorMessage } from "../../lib/learnEnglishPracticePublish"
|
||||
import { formatPracticeParentLabel } from "../../lib/practiceParents"
|
||||
import type { PracticeParentTitleHints } from "../../lib/practiceParentTitles"
|
||||
import { LinkExistingPracticeReviewStep } from "./components/practice-steps/LinkExistingPracticeReviewStep"
|
||||
import { SelectPracticeToAttachStep } from "./components/practice-steps/SelectPracticeToAttachStep"
|
||||
|
||||
const STEP_LABELS = ["Select practice", "Review"] as const
|
||||
|
||||
export function LinkExistingPracticeFlow() {
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
level,
|
||||
programType,
|
||||
courseId: routeCourseId,
|
||||
unitId: routeUnitId,
|
||||
moduleId: routeModuleId,
|
||||
} = useParams<{
|
||||
level?: string
|
||||
programType?: string
|
||||
courseId?: string
|
||||
unitId?: string
|
||||
moduleId?: string
|
||||
}>()
|
||||
const [searchParams] = useSearchParams()
|
||||
const backToParam = searchParams.get("backTo")
|
||||
const lessonId = searchParams.get("lessonId")
|
||||
const lessonTitleRaw = searchParams.get("lessonTitle")
|
||||
|
||||
const isExamPrep = Boolean(programType?.trim())
|
||||
|
||||
const effectiveBackTo = useMemo(() => {
|
||||
if (backToParam?.trim()) return backToParam.trim()
|
||||
if (isExamPrep && routeModuleId) return "module"
|
||||
if (isExamPrep && routeCourseId) return "courses"
|
||||
return null
|
||||
}, [backToParam, isExamPrep, routeModuleId, routeCourseId])
|
||||
|
||||
const courseId = isExamPrep
|
||||
? routeCourseId ?? searchParams.get("courseId")
|
||||
: searchParams.get("courseId")
|
||||
const moduleId = isExamPrep
|
||||
? routeModuleId ?? searchParams.get("moduleId")
|
||||
: searchParams.get("moduleId")
|
||||
const unitId = isExamPrep ? routeUnitId : null
|
||||
|
||||
const lessonTitleDisplay = (() => {
|
||||
const raw = lessonTitleRaw?.trim()
|
||||
if (!raw) return null
|
||||
try {
|
||||
return decodeURIComponent(raw)
|
||||
} catch {
|
||||
return raw
|
||||
}
|
||||
})()
|
||||
|
||||
const isModuleContext = effectiveBackTo === "module"
|
||||
const isCourseContext =
|
||||
effectiveBackTo === "modules" || effectiveBackTo === "courses"
|
||||
|
||||
const parentContext = useMemo((): {
|
||||
kind: PracticeParentKind
|
||||
id: number
|
||||
} | null => {
|
||||
const lid = lessonId ? Number(lessonId) : NaN
|
||||
if (Number.isFinite(lid) && lid > 0) return { kind: "LESSON", id: lid }
|
||||
const mid = moduleId ? Number(moduleId) : NaN
|
||||
if (isModuleContext && Number.isFinite(mid) && mid > 0)
|
||||
return { kind: "MODULE", id: mid }
|
||||
const cid = courseId ? Number(courseId) : NaN
|
||||
if (isCourseContext && Number.isFinite(cid) && cid > 0)
|
||||
return { kind: "COURSE", id: cid }
|
||||
if (isExamPrep && !courseId && !moduleId && !lessonId && programType) {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}, [lessonId, moduleId, courseId, isModuleContext, isCourseContext, isExamPrep, programType])
|
||||
|
||||
const targetParent = useMemo(
|
||||
() =>
|
||||
parentContext
|
||||
? { parent_kind: parentContext.kind, parent_id: parentContext.id }
|
||||
: null,
|
||||
[parentContext],
|
||||
)
|
||||
|
||||
const targetSummary = useMemo(() => {
|
||||
if (targetParent) return formatPracticeParentLabel(targetParent)
|
||||
if (lessonId)
|
||||
return `Lesson #${lessonId}${lessonTitleDisplay ? ` — ${lessonTitleDisplay}` : ""}`
|
||||
if (isModuleContext && moduleId) return `Module #${moduleId}`
|
||||
if (isCourseContext && courseId) return `Course #${courseId}`
|
||||
return "selected content"
|
||||
}, [
|
||||
targetParent,
|
||||
lessonId,
|
||||
lessonTitleDisplay,
|
||||
isModuleContext,
|
||||
isCourseContext,
|
||||
moduleId,
|
||||
courseId,
|
||||
])
|
||||
|
||||
const backLabel =
|
||||
effectiveBackTo === "module"
|
||||
? "Back to Module"
|
||||
: effectiveBackTo === "modules"
|
||||
? "Back to Modules"
|
||||
: effectiveBackTo === "courses"
|
||||
? "Back to Course"
|
||||
: isExamPrep
|
||||
? "Back to Program"
|
||||
: "Back to Courses"
|
||||
|
||||
const backPath = useMemo(() => {
|
||||
if (isExamPrep) {
|
||||
if (
|
||||
effectiveBackTo === "module" &&
|
||||
programType &&
|
||||
courseId &&
|
||||
unitId &&
|
||||
moduleId
|
||||
) {
|
||||
return `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}`
|
||||
}
|
||||
if (effectiveBackTo === "courses" && programType && courseId) {
|
||||
return `/new-content/courses/${programType}/${courseId}`
|
||||
}
|
||||
if (programType) {
|
||||
return `/new-content/courses/${programType}`
|
||||
}
|
||||
return "/new-content"
|
||||
}
|
||||
if (effectiveBackTo === "module" && level && courseId && moduleId) {
|
||||
return `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}`
|
||||
}
|
||||
if (effectiveBackTo === "modules" && level && courseId) {
|
||||
return `/new-content/learn-english/${level}/courses/${courseId}`
|
||||
}
|
||||
return `/new-content/learn-english/${level}/courses`
|
||||
}, [
|
||||
isExamPrep,
|
||||
effectiveBackTo,
|
||||
programType,
|
||||
courseId,
|
||||
unitId,
|
||||
moduleId,
|
||||
level,
|
||||
])
|
||||
|
||||
const parentTitleHints = useMemo((): PracticeParentTitleHints => {
|
||||
const hints: PracticeParentTitleHints = {}
|
||||
const lid = lessonId ? Number(lessonId) : NaN
|
||||
if (Number.isFinite(lid) && lid > 0 && lessonTitleDisplay?.trim()) {
|
||||
hints.lessons = { [lid]: lessonTitleDisplay.trim() }
|
||||
}
|
||||
return hints
|
||||
}, [lessonId, lessonTitleDisplay])
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(1)
|
||||
const [isComplete, setIsComplete] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [selectedPractice, setSelectedPractice] = useState<ParentContextPractice | null>(
|
||||
null,
|
||||
)
|
||||
|
||||
if (!parentContext || !targetParent) {
|
||||
return (
|
||||
<div className="space-y-8 px-6 pb-16 pt-6">
|
||||
<div className="mx-auto max-w-lg py-16 text-center">
|
||||
<h1 className="text-2xl font-bold text-grayScale-900">Missing content context</h1>
|
||||
<p className="mt-2 text-sm text-grayScale-600">
|
||||
Open attach practice from a course, module, or lesson so the API knows where to link
|
||||
the practice.
|
||||
</p>
|
||||
<Button
|
||||
className="mt-6 rounded-[6px]"
|
||||
variant="outline"
|
||||
onClick={() => navigate(backPath)}
|
||||
>
|
||||
{backLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const submitAttach = async () => {
|
||||
if (!selectedPractice) return
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await attachPracticeToParent(selectedPractice, targetParent)
|
||||
toast.success("Practice linked successfully")
|
||||
setIsComplete(true)
|
||||
} catch (e) {
|
||||
toast.error("Could not link practice", {
|
||||
description: learnEnglishPracticeApiErrorMessage(e),
|
||||
})
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (isComplete) {
|
||||
return (
|
||||
<div className="flex min-h-[60vh] flex-col items-center justify-center px-4 pb-20 text-center animate-in fade-in zoom-in duration-500">
|
||||
<div className="relative mb-10">
|
||||
<div className="absolute inset-0 rounded-full bg-brand-500/10 blur-3xl" />
|
||||
<img src={successIcon} alt="" className="relative h-28 w-28" />
|
||||
</div>
|
||||
<h1 className="mb-2 text-[28px] font-bold text-grayScale-900">
|
||||
Practice linked successfully
|
||||
</h1>
|
||||
<p className="mb-14 max-w-lg text-base font-medium leading-relaxed text-grayScale-600">
|
||||
<span className="font-semibold text-grayScale-900">
|
||||
{selectedPractice?.title?.trim() || `Practice #${selectedPractice?.id}`}
|
||||
</span>{" "}
|
||||
is now attached to {targetSummary}.
|
||||
</p>
|
||||
<Button
|
||||
onClick={() => navigate(backPath)}
|
||||
className="h-14 rounded-[6px] bg-brand-500 px-10 text-[16px] font-bold text-white shadow-xl shadow-brand-500/20"
|
||||
>
|
||||
{backLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8 px-6 pb-16 pt-6">
|
||||
<div className="mx-auto w-full max-w-7xl">
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<Link
|
||||
to={backPath}
|
||||
className="flex items-center gap-2 text-[15px] font-medium text-grayScale-600 decoration-none transition-colors hover:text-brand-500"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
{backLabel}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="mb-10">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold text-[#0F172A]">Attach Existing Practice</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-10 rounded-[8px] border-grayScale-200 bg-white px-6 font-bold text-grayScale-600 hover:bg-grayScale-50"
|
||||
onClick={() => navigate(backPath)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-base text-grayScale-400">
|
||||
Browse your practice library and link an existing practice to this content location.
|
||||
</p>
|
||||
<div className="mt-4 rounded-xl border border-violet-200 bg-violet-50/80 px-4 py-3 text-sm text-violet-950">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-violet-100 text-violet-700">
|
||||
<Link2 className="h-4 w-4" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold text-violet-900">Attach to</p>
|
||||
<p className="mt-1 text-violet-800/90">
|
||||
<span className="font-medium">{targetSummary}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto mb-12 w-[70%] max-w-md">
|
||||
<Stepper steps={[...STEP_LABELS]} currentStep={currentStep} />
|
||||
</div>
|
||||
|
||||
<div className="mx-auto max-w-4xl">
|
||||
{currentStep === 1 ? (
|
||||
<SelectPracticeToAttachStep
|
||||
targetParent={targetParent}
|
||||
targetSummary={targetSummary}
|
||||
selectedPracticeId={selectedPractice?.id ?? null}
|
||||
onSelect={setSelectedPractice}
|
||||
nextStep={() => setCurrentStep(2)}
|
||||
onCancel={() => navigate(backPath)}
|
||||
/>
|
||||
) : selectedPractice ? (
|
||||
<LinkExistingPracticeReviewStep
|
||||
practice={selectedPractice}
|
||||
targetParent={targetParent}
|
||||
targetSummary={targetSummary}
|
||||
titleHints={parentTitleHints}
|
||||
saving={submitting}
|
||||
onBack={() => setCurrentStep(1)}
|
||||
onConfirm={() => void submitAttach()}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -20,6 +20,9 @@ import type {
|
|||
} from "../../types/course.types";
|
||||
import { unwrapPracticesList } from "../../lib/parentContextPractice";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
||||
import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../lib/practiceContentPaths";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
|
|
@ -70,6 +73,25 @@ export function ModuleDetailPage() {
|
|||
const [practiceSearch, setPracticeSearch] = useState("");
|
||||
const [practicePublishStatusFilter, setPracticePublishStatusFilter] =
|
||||
useState<PublishStatusFilter>("all");
|
||||
const [lessonPracticeChoice, setLessonPracticeChoice] =
|
||||
useState<PracticeContentPathOptions | null>(null);
|
||||
const lessonPracticeChoicePaths = useMemo(
|
||||
() =>
|
||||
lessonPracticeChoice
|
||||
? buildPracticeContentPaths(lessonPracticeChoice)
|
||||
: null,
|
||||
[lessonPracticeChoice],
|
||||
);
|
||||
const modulePracticePathOptions = useMemo(
|
||||
(): PracticeContentPathOptions => ({
|
||||
isExamPrep: false,
|
||||
level,
|
||||
courseId,
|
||||
moduleId,
|
||||
backTo: "module",
|
||||
}),
|
||||
[level, courseId, moduleId],
|
||||
);
|
||||
const [lessons, setLessons] = useState<TopLevelModuleLessonItem[]>([]);
|
||||
const [lessonsLoading, setLessonsLoading] = useState(true);
|
||||
const [lessonsLoadError, setLessonsLoadError] = useState<string | null>(null);
|
||||
|
|
@ -472,18 +494,15 @@ export function ModuleDetailPage() {
|
|||
</ContentPageDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
variant="outline"
|
||||
className="rounded-[6px] border-brand-500 text-brand-500 "
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/new-content/learn-english/${level}/courses/add-practice?backTo=module&courseId=${courseId}&moduleId=${moduleId}`,
|
||||
)
|
||||
}
|
||||
pathOptions={modulePracticePathOptions}
|
||||
parentLabel={displayModuleName}
|
||||
>
|
||||
<Calendar className="h-4 w-4" />
|
||||
Add Practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
<Button
|
||||
className="rounded-[6px] bg-brand-500 font-semibold hover:bg-brand-600"
|
||||
onClick={() =>
|
||||
|
|
@ -578,9 +597,15 @@ export function ModuleDetailPage() {
|
|||
onDelete={() => setDeletingLesson(lesson)}
|
||||
description={lesson.description}
|
||||
onAddPractice={() =>
|
||||
navigate(
|
||||
`/new-content/learn-english/${level}/courses/add-practice?backTo=module&courseId=${courseId}&moduleId=${moduleId}&lessonId=${lesson.id}&lessonTitle=${encodeURIComponent(lesson.title)}`,
|
||||
)
|
||||
setLessonPracticeChoice({
|
||||
isExamPrep: false,
|
||||
level,
|
||||
courseId,
|
||||
moduleId,
|
||||
lessonId: String(lesson.id),
|
||||
lessonTitle: lesson.title,
|
||||
backTo: "module",
|
||||
})
|
||||
}
|
||||
onViewPractices={() =>
|
||||
navigate(
|
||||
|
|
@ -690,18 +715,15 @@ export function ModuleDetailPage() {
|
|||
: "Try different keywords or clear the publish status filter."}
|
||||
</p>
|
||||
{practices.length === 0 ? (
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
variant="outline"
|
||||
className="h-12 px-8 rounded-xl border-brand-500 text-brand-500 font-bold hover:bg-brand-50 transition-all flex items-center gap-2"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/new-content/learn-english/${level}/courses/add-practice?backTo=module&courseId=${courseId}&moduleId=${moduleId}`,
|
||||
)
|
||||
}
|
||||
pathOptions={modulePracticePathOptions}
|
||||
parentLabel={displayModuleName}
|
||||
>
|
||||
<Calendar className="h-5 w-5" />
|
||||
Add Practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -865,6 +887,23 @@ export function ModuleDetailPage() {
|
|||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lessonPracticeChoice && lessonPracticeChoicePaths ? (
|
||||
<PracticeActionChoiceDialog
|
||||
open={lessonPracticeChoice != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setLessonPracticeChoice(null)
|
||||
}}
|
||||
createHref={lessonPracticeChoicePaths.create}
|
||||
attachHref={lessonPracticeChoicePaths.attach}
|
||||
pathOptions={lessonPracticeChoice}
|
||||
parentLabel={
|
||||
lessonPracticeChoice.lessonTitle
|
||||
? `Lesson — ${lessonPracticeChoice.lessonTitle}`
|
||||
: null
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ import {
|
|||
} from "../../components/ui/dialog"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Textarea } from "../../components/ui/textarea"
|
||||
import { formatPracticeParentsSummary, parentsFromPractice } from "../../lib/practiceParents"
|
||||
import type {
|
||||
LearningProgramListItem,
|
||||
ParentContextPractice,
|
||||
|
|
@ -598,6 +599,7 @@ export function PracticeDetailsPage() {
|
|||
...practice,
|
||||
...payload,
|
||||
id: practice.id,
|
||||
parents: parentsFromPractice({ ...practice, ...payload }),
|
||||
parent_kind: practice.parent_kind,
|
||||
parent_id: practice.parent_id,
|
||||
created_at: practice.created_at,
|
||||
|
|
@ -952,10 +954,10 @@ export function PracticeDetailsPage() {
|
|||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary" className="font-mono text-[10px] uppercase tracking-wider">
|
||||
{practice.parent_kind}
|
||||
{formatPracticeParentsSummary(parentsFromPractice(practice))}
|
||||
</Badge>
|
||||
<span className="text-xs text-grayScale-500">
|
||||
parent #{practice.parent_id} · practice #{practice.id}
|
||||
practice #{practice.id}
|
||||
</span>
|
||||
</div>
|
||||
{flowMode === "view" && (
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
X,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { Card } from "../../components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
|
|
@ -648,16 +649,14 @@ export function ProgramDetailPage() {
|
|||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Button
|
||||
<PracticeActionButton
|
||||
variant="outline"
|
||||
className="h-10 px-6 rounded-[6px] border-brand-500 text-brand-500 font-bold flex items-center gap-2"
|
||||
onClick={() =>
|
||||
navigate(`/new-content/courses/${programType}/add-practice`)
|
||||
}
|
||||
pathOptions={{ isExamPrep: true, programType }}
|
||||
>
|
||||
<FileText className="h-5 w-5" />
|
||||
Add Practice
|
||||
</Button>
|
||||
</PracticeActionButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ import { countActiveFilters } from "../../lib/adminFilterUtils"
|
|||
import { cn } from "../../lib/utils"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
||||
import { QuestionTypeDefinitionPracticesDialog } from "./components/QuestionTypeDefinitionPracticesDialog"
|
||||
import {
|
||||
deleteQuestionTypeDefinition,
|
||||
getQuestionTypeDefinitions,
|
||||
|
|
@ -69,6 +70,7 @@ export function QuestionTypeLibraryPage() {
|
|||
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 hasActiveFilters =
|
||||
query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all"
|
||||
|
|
@ -363,6 +365,10 @@ export function QuestionTypeLibraryPage() {
|
|||
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={() => openDeleteConfirm(d)}
|
||||
/>
|
||||
))}
|
||||
|
|
@ -441,6 +447,14 @@ export function QuestionTypeLibraryPage() {
|
|||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<QuestionTypeDefinitionPracticesDialog
|
||||
definition={definitionForPractices}
|
||||
open={definitionForPractices !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDefinitionForPractices(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
<Dialog open={definitionPendingDelete !== null} onOpenChange={handleDeleteDialogOpenChange}>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
|
|
|
|||
|
|
@ -190,8 +190,7 @@ export function CreatePracticeWizard({ parent, onCreated }: Props) {
|
|||
setSaving(true)
|
||||
try {
|
||||
await createParentLinkedPractice({
|
||||
parent_kind: parent.kind,
|
||||
parent_id: parent.id,
|
||||
parents: [{ parent_kind: parent.kind, parent_id: parent.id }],
|
||||
title: practiceTitle.trim(),
|
||||
story_description: storyDescription.trim(),
|
||||
story_image: storyImage.trim(),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
import { useMemo, useState } from "react"
|
||||
import type { ComponentProps } from "react"
|
||||
import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../../lib/practiceContentPaths"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { PracticeActionChoiceDialog } from "./PracticeActionChoiceDialog"
|
||||
|
||||
interface PracticeActionButtonProps
|
||||
extends Omit<ComponentProps<typeof Button>, "onClick"> {
|
||||
pathOptions: PracticeContentPathOptions
|
||||
parentLabel?: string | null
|
||||
}
|
||||
|
||||
export function PracticeActionButton({
|
||||
pathOptions,
|
||||
parentLabel,
|
||||
children,
|
||||
...buttonProps
|
||||
}: PracticeActionButtonProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const paths = useMemo(
|
||||
() => buildPracticeContentPaths(pathOptions),
|
||||
[pathOptions],
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button type="button" onClick={() => setOpen(true)} {...buttonProps}>
|
||||
{children}
|
||||
</Button>
|
||||
<PracticeActionChoiceDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
createHref={paths.create}
|
||||
attachHref={paths.attach}
|
||||
pathOptions={pathOptions}
|
||||
parentLabel={parentLabel}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
import { Link2, Plus } from "lucide-react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import {
|
||||
resolvePracticeParentFromPathOptions,
|
||||
type PracticeContentPathOptions,
|
||||
} from "../../../lib/practiceContentPaths"
|
||||
|
||||
interface PracticeActionChoiceDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
createHref: string
|
||||
attachHref: string
|
||||
pathOptions: PracticeContentPathOptions
|
||||
parentLabel?: string | null
|
||||
}
|
||||
|
||||
export function PracticeActionChoiceDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
createHref,
|
||||
attachHref,
|
||||
pathOptions,
|
||||
parentLabel,
|
||||
}: PracticeActionChoiceDialogProps) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const openAttachPage = () => {
|
||||
if (!resolvePracticeParentFromPathOptions(pathOptions)) {
|
||||
toast.error("Missing content context", {
|
||||
description:
|
||||
"Open attach practice from a course, module, or lesson so the API knows where to link the practice.",
|
||||
})
|
||||
return
|
||||
}
|
||||
onOpenChange(false)
|
||||
navigate(attachHref)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg rounded-2xl border-grayScale-200 p-0 sm:max-w-lg">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5 text-left">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Add practice
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-left text-sm text-grayScale-600">
|
||||
{parentLabel ? (
|
||||
<>
|
||||
Choose how to add a practice for{" "}
|
||||
<span className="font-semibold text-grayScale-800">{parentLabel}</span>.
|
||||
</>
|
||||
) : (
|
||||
"Create a new practice or link an existing one from your library."
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-3 px-6 py-5 sm:grid-cols-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onOpenChange(false)
|
||||
navigate(createHref)
|
||||
}}
|
||||
className="group flex flex-col gap-3 rounded-xl border border-grayScale-200 bg-white p-5 text-left transition-all hover:border-brand-300 hover:shadow-md"
|
||||
>
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
|
||||
<Plus className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-bold text-grayScale-900">Create new practice</p>
|
||||
<p className="text-xs leading-relaxed text-grayScale-500">
|
||||
Start the 4-step wizard with story details, persona, and questions.
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={openAttachPage}
|
||||
className="group flex flex-col gap-3 rounded-xl border border-grayScale-200 bg-white p-5 text-left transition-all hover:border-brand-300 hover:shadow-md"
|
||||
>
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-violet-50 text-violet-700">
|
||||
<Link2 className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-bold text-grayScale-900">Attach existing practice</p>
|
||||
<p className="text-xs leading-relaxed text-grayScale-500">
|
||||
Pick a practice from the library and link it to this content.
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-grayScale-100 px-6 py-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full rounded-[8px]"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { Edit2, Sparkles, Trash2, Layers, Shield } from "lucide-react"
|
||||
import { Edit2, GraduationCap, Plus, Sparkles, Trash2, Layers, Shield } from "lucide-react"
|
||||
import { Badge } from "../../../components/ui/badge"
|
||||
import { Card } from "../../../components/ui/card"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
|
|
@ -14,6 +14,8 @@ export interface QuestionTypeDefinitionCardModel {
|
|||
responseKindsCount: number
|
||||
onEdit?: () => void
|
||||
onDelete?: () => void
|
||||
onViewPractices?: () => void
|
||||
onCreatePractice?: () => void
|
||||
deleteDisabled?: boolean
|
||||
}
|
||||
|
||||
|
|
@ -27,6 +29,8 @@ export function QuestionTypeCard({
|
|||
responseKindsCount,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onViewPractices,
|
||||
onCreatePractice,
|
||||
deleteDisabled,
|
||||
}: QuestionTypeDefinitionCardModel) {
|
||||
const statusLabel = (status || "—").toString()
|
||||
|
|
@ -69,6 +73,32 @@ export function QuestionTypeCard({
|
|||
{statusLabel}
|
||||
</Badge>
|
||||
<div className="flex items-center gap-1">
|
||||
{onCreatePractice ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-9 w-9 p-0"
|
||||
onClick={onCreatePractice}
|
||||
aria-label="Create practice"
|
||||
title="Create practice"
|
||||
>
|
||||
<Plus className="h-4 w-4 text-brand-600" />
|
||||
</Button>
|
||||
) : null}
|
||||
{onViewPractices ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-9 w-9 p-0"
|
||||
onClick={onViewPractices}
|
||||
aria-label="View practices"
|
||||
title="View practices"
|
||||
>
|
||||
<GraduationCap className="h-4 w-4 text-grayScale-500" />
|
||||
</Button>
|
||||
) : null}
|
||||
{onEdit ? (
|
||||
<Button type="button" variant="ghost" size="sm" className="h-9 w-9 p-0" onClick={onEdit} aria-label="Edit">
|
||||
<Edit2 className="h-4 w-4 text-grayScale-500" />
|
||||
|
|
|
|||
|
|
@ -0,0 +1,304 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { ChevronDown, ChevronLeft, ChevronRight, GraduationCap, Pencil, Plus } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getQuestionTypeDefinitionPractices } from "../../../api/questionTypeDefinitions.api"
|
||||
import { Badge } from "../../../components/ui/badge"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import { resolveLearnEnglishPracticeEditPath } from "../../../lib/learnEnglishPracticeEditPath"
|
||||
import { formatPracticeParentsSummary } from "../../../lib/practiceParents"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination"
|
||||
import type {
|
||||
QuestionTypeDefinition,
|
||||
QuestionTypeDefinitionPractice,
|
||||
} from "../../../types/questionTypeDefinition.types"
|
||||
|
||||
function formatDate(iso?: string): string {
|
||||
if (!iso) return "—"
|
||||
const d = new Date(iso)
|
||||
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString()
|
||||
}
|
||||
|
||||
function publishStatusClass(status?: string): string {
|
||||
const s = (status || "").toUpperCase()
|
||||
if (s === "PUBLISHED") return "bg-[#F0FDF4] text-[#16A34A]"
|
||||
if (s === "DRAFT") return "bg-amber-50 text-amber-800"
|
||||
return "bg-grayScale-50 text-grayScale-600"
|
||||
}
|
||||
|
||||
interface QuestionTypeDefinitionPracticesDialogProps {
|
||||
definition: QuestionTypeDefinition | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function QuestionTypeDefinitionPracticesDialog({
|
||||
definition,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: QuestionTypeDefinitionPracticesDialogProps) {
|
||||
const navigate = useNavigate()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [practices, setPractices] = useState<QuestionTypeDefinitionPractice[]>([])
|
||||
const [totalCount, setTotalCount] = useState(0)
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [editingPracticeId, setEditingPracticeId] = useState<number | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!definition) return
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await getQuestionTypeDefinitionPractices(definition.id, {
|
||||
limit: pageSize,
|
||||
offset,
|
||||
})
|
||||
setPractices(result.practices)
|
||||
setTotalCount(result.total_count)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.error("Failed to load practices for this definition")
|
||||
setPractices([])
|
||||
setTotalCount(0)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [definition, offset, pageSize])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !definition) return
|
||||
void load()
|
||||
}, [open, definition, load])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setOffset(0)
|
||||
setPageSize(DEFAULT_TABLE_PAGE_SIZE)
|
||||
setPractices([])
|
||||
setTotalCount(0)
|
||||
setEditingPracticeId(null)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleCreatePractice = () => {
|
||||
if (!definition) return
|
||||
onOpenChange(false)
|
||||
navigate(`/new-content/question-types/${definition.id}/create-practice`)
|
||||
}
|
||||
|
||||
const handleEditPractice = async (practice: QuestionTypeDefinitionPractice) => {
|
||||
setEditingPracticeId(practice.practice_id)
|
||||
try {
|
||||
const path = await resolveLearnEnglishPracticeEditPath(practice)
|
||||
if (!path) {
|
||||
toast.error("Could not open practice editor", {
|
||||
description: "This practice could not be linked to its course context.",
|
||||
})
|
||||
return
|
||||
}
|
||||
onOpenChange(false)
|
||||
navigate(path)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.error("Failed to open practice editor")
|
||||
} finally {
|
||||
setEditingPracticeId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const canPrev = offset > 0
|
||||
const canNext = offset + pageSize < totalCount
|
||||
const pageStart = totalCount === 0 ? 0 : offset + 1
|
||||
const pageEnd = Math.min(offset + practices.length, totalCount)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-3xl overflow-hidden rounded-2xl border-grayScale-200 p-0 sm:max-w-3xl">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5 text-left">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<GraduationCap className="h-5 w-5 text-brand-600 shrink-0" aria-hidden />
|
||||
Practices using this definition
|
||||
</DialogTitle>
|
||||
{definition ? (
|
||||
<DialogDescription className="text-left text-grayScale-600">
|
||||
<span className="font-semibold text-grayScale-800">{definition.display_name}</span>
|
||||
<span className="mx-1.5 text-grayScale-300">·</span>
|
||||
<span className="font-mono text-xs text-grayScale-500">
|
||||
#{definition.id} · {definition.key}
|
||||
</span>
|
||||
</DialogDescription>
|
||||
) : null}
|
||||
{definition ? (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="rounded-[8px] bg-brand-600 hover:bg-brand-500"
|
||||
onClick={handleCreatePractice}
|
||||
>
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
Create practice
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex max-h-[calc(90vh-8rem)] flex-col">
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 px-6 py-16">
|
||||
<SpinnerIcon className="h-8 w-8 text-brand-500" />
|
||||
<p className="text-sm text-grayScale-500">Loading practices…</p>
|
||||
</div>
|
||||
) : practices.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 px-6 py-16 text-center">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-grayScale-100 text-grayScale-400">
|
||||
<GraduationCap className="h-7 w-7" aria-hidden />
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-grayScale-700">No practices found</p>
|
||||
<p className="max-w-sm text-xs text-grayScale-500">
|
||||
No published or draft practices currently contain questions built from this definition.
|
||||
</p>
|
||||
{definition ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="mt-2 rounded-[8px] bg-brand-600 hover:bg-brand-500"
|
||||
onClick={handleCreatePractice}
|
||||
>
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
Create practice with this type
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-grayScale-100 overflow-y-auto px-2 py-2">
|
||||
{practices.map((practice) => (
|
||||
<li key={`${practice.practice_kind}-${practice.practice_id}`} className="px-4 py-4">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0 space-y-1.5">
|
||||
<p className="text-sm font-semibold text-grayScale-900 leading-snug">{practice.title}</p>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-grayScale-500">
|
||||
<span className="font-mono">practice #{practice.practice_id}</span>
|
||||
<span className="text-grayScale-300">·</span>
|
||||
<span className="font-mono">set #{practice.question_set_id}</span>
|
||||
{practice.parents && practice.parents.length > 0 ? (
|
||||
<>
|
||||
<span className="text-grayScale-300">·</span>
|
||||
<span>{formatPracticeParentsSummary(practice.parents)}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-grayScale-300">·</span>
|
||||
<span className="italic text-amber-700">Unlinked</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{practice.story_description?.trim() ? (
|
||||
<p className="line-clamp-2 text-xs text-grayScale-500">{practice.story_description}</p>
|
||||
) : null}
|
||||
<p className="text-[11px] text-grayScale-400">Created {formatDate(practice.created_at)}</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-2 sm:flex-col sm:items-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 rounded-[8px] border-grayScale-200 px-3 text-xs font-semibold"
|
||||
disabled={editingPracticeId === practice.practice_id}
|
||||
onClick={() => void handleEditPractice(practice)}
|
||||
>
|
||||
{editingPracticeId === practice.practice_id ? (
|
||||
<SpinnerIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||
) : (
|
||||
<Pencil className="mr-1.5 h-3.5 w-3.5" />
|
||||
)}
|
||||
Edit practice
|
||||
</Button>
|
||||
<Badge
|
||||
className={cn(
|
||||
"border-none px-2.5 py-0.5 text-[11px] font-bold shadow-none",
|
||||
publishStatusClass(practice.publish_status),
|
||||
)}
|
||||
>
|
||||
{practice.publish_status || "—"}
|
||||
</Badge>
|
||||
<Badge variant="secondary" className="font-mono text-[10px] uppercase tracking-wider">
|
||||
{practice.matching_question_count} matching question
|
||||
{practice.matching_question_count === 1 ? "" : "s"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{!loading && totalCount > 0 ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 border-t border-grayScale-100 bg-grayScale-50/60 px-6 py-4">
|
||||
<div className="flex flex-wrap items-center gap-3 text-xs text-grayScale-500">
|
||||
<span>
|
||||
Showing {pageStart}–{pageEnd} of {totalCount}
|
||||
</span>
|
||||
<span className="hidden h-4 w-px bg-grayScale-200 sm:inline" />
|
||||
<span className="flex items-center gap-2">
|
||||
Per page
|
||||
<div className="relative">
|
||||
<select
|
||||
value={pageSize}
|
||||
disabled={loading}
|
||||
onChange={(e) => {
|
||||
setPageSize(Number(e.target.value))
|
||||
setOffset(0)
|
||||
}}
|
||||
className="h-8 appearance-none rounded-[8px] border border-grayScale-200 bg-white pl-2.5 pr-8 text-sm font-medium text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-brand-200"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="rounded-[8px] border-grayScale-200"
|
||||
disabled={!canPrev || loading}
|
||||
onClick={() => setOffset((o) => Math.max(0, o - pageSize))}
|
||||
>
|
||||
<ChevronLeft className="mr-1 h-4 w-4" />
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="rounded-[8px] border-grayScale-200"
|
||||
disabled={!canNext || loading}
|
||||
onClick={() => setOffset((o) => o + pageSize)}
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,21 +1,37 @@
|
|||
import { useRef, useState, type ChangeEvent } from "react";
|
||||
import { ArrowRight, Loader2, Upload } from "lucide-react";
|
||||
import { ArrowRight, ChevronDown, ChevronUp, Loader2, Upload } 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 { toast } from "sonner";
|
||||
import { uploadImageFile } from "../../../../api/files.api";
|
||||
import type { PracticeParent } from "../../../../types/course.types";
|
||||
import { PracticeParentsField } from "./PracticeParentsField";
|
||||
import { formatPracticeParentsSummary } from "../../../../lib/practiceParents";
|
||||
|
||||
interface ContextStepProps {
|
||||
formData: any;
|
||||
setFormData: (data: any) => void;
|
||||
formData: {
|
||||
title?: string;
|
||||
description?: string;
|
||||
storyImageUrl?: string;
|
||||
shuffleQuestions?: boolean;
|
||||
tips?: string;
|
||||
parents?: PracticeParent[];
|
||||
};
|
||||
setFormData: (data: ContextStepProps["formData"]) => void;
|
||||
nextStep: () => void;
|
||||
onCancel: () => void;
|
||||
/** Lesson-linked practice: no title, story description, or story image on step 1. */
|
||||
isLessonPractice?: boolean;
|
||||
lessonTitle?: string | null;
|
||||
parentSummary?: string | null;
|
||||
/** Learn English LMS — show multi-parent picker. */
|
||||
showParentsEditor?: boolean;
|
||||
lockedParentKey?: string | null;
|
||||
/** When true, locations are optional and the picker can stay collapsed. */
|
||||
parentsOptional?: boolean;
|
||||
parentsCollapsedDefault?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -29,9 +45,14 @@ export function ContextStep({
|
|||
isLessonPractice = false,
|
||||
lessonTitle = null,
|
||||
parentSummary = null,
|
||||
showParentsEditor = false,
|
||||
lockedParentKey = null,
|
||||
parentsOptional = false,
|
||||
parentsCollapsedDefault = false,
|
||||
}: ContextStepProps) {
|
||||
const storyFileRef = useRef<HTMLInputElement>(null);
|
||||
const [uploadingStory, setUploadingStory] = useState(false);
|
||||
const [parentsExpanded, setParentsExpanded] = useState(!parentsCollapsedDefault);
|
||||
|
||||
const handleStoryImageFile = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
|
|
@ -55,6 +76,11 @@ export function ContextStep({
|
|||
? true
|
||||
: Boolean(formData.title?.trim()) && Boolean(formData.description?.trim());
|
||||
|
||||
const parentsSummary =
|
||||
formData.parents && formData.parents.length > 0
|
||||
? formatPracticeParentsSummary(formData.parents)
|
||||
: parentSummary;
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden border-grayScale-300 rounded-2xl bg-white animate-in fade-in duration-500">
|
||||
<div className="border-b border-grayScale-50 px-8 pt-8 pb-4">
|
||||
|
|
@ -91,16 +117,64 @@ export function ContextStep({
|
|||
</div>
|
||||
|
||||
<div className="space-y-8 p-10">
|
||||
{parentSummary ? (
|
||||
{parentsSummary && !showParentsEditor ? (
|
||||
<div className="rounded-xl border border-brand-100 bg-brand-50/50 px-4 py-3 text-sm text-grayScale-800">
|
||||
<p className="font-semibold text-brand-700">LMS parent</p>
|
||||
<p className="mt-1">{parentSummary}</p>
|
||||
<p className="mt-1">{parentsSummary}</p>
|
||||
<p className="mt-1 text-xs text-grayScale-500">
|
||||
The question set and practice will be linked to this course, module, or lesson.
|
||||
The question set and practice will be linked to these locations.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showParentsEditor ? (
|
||||
parentsOptional ? (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-xl border border-amber-200 bg-amber-50/80 px-4 py-3 text-sm text-amber-950">
|
||||
<p className="font-semibold text-amber-900">Locations optional</p>
|
||||
<p className="mt-1 text-amber-900/90">
|
||||
You can create this practice now and attach it to courses, modules, or lessons
|
||||
later from the practice editor.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setParentsExpanded((open) => !open)}
|
||||
className="flex w-full items-center justify-between rounded-xl border border-grayScale-200 bg-grayScale-50/60 px-4 py-3 text-left transition-colors hover:bg-grayScale-50"
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-800">Locations (optional)</p>
|
||||
<p className="mt-0.5 text-xs text-grayScale-500">
|
||||
{parentsSummary &&
|
||||
parentsSummary !== "Not attached to any course, module, or lesson"
|
||||
? parentsSummary
|
||||
: "Skip for now — attach later"}
|
||||
</p>
|
||||
</div>
|
||||
{parentsExpanded ? (
|
||||
<ChevronUp className="h-4 w-4 shrink-0 text-grayScale-500" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-grayScale-500" />
|
||||
)}
|
||||
</button>
|
||||
{parentsExpanded ? (
|
||||
<PracticeParentsField
|
||||
parents={formData.parents ?? []}
|
||||
lockedParentKey={lockedParentKey}
|
||||
optional
|
||||
onChange={(parents) => setFormData({ ...formData, parents })}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<PracticeParentsField
|
||||
parents={formData.parents ?? []}
|
||||
lockedParentKey={lockedParentKey}
|
||||
onChange={(parents) => setFormData({ ...formData, parents })}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
|
||||
{!isLessonPractice ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
|
|
|
|||
|
|
@ -0,0 +1,196 @@
|
|||
import { useMemo } from "react"
|
||||
import { Loader2, Rocket } from "lucide-react"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
import { Card } from "../../../../components/ui/card"
|
||||
import {
|
||||
mergedParentsForAttach,
|
||||
practiceAlreadyLinkedToParent,
|
||||
} from "../../../../lib/attachPracticeToParent"
|
||||
import { dedupeParents } from "../../../../lib/practiceParents"
|
||||
import {
|
||||
formatPracticeParentDisplayLabel,
|
||||
formatPracticeParentsDisplaySummary,
|
||||
type PracticeParentTitleHints,
|
||||
} from "../../../../lib/practiceParentTitles"
|
||||
import type { ParentContextPractice, PracticeParent } from "../../../../types/course.types"
|
||||
import { cn } from "../../../../lib/utils"
|
||||
import { usePracticeParentTitles } from "../../../../hooks/usePracticeParentTitles"
|
||||
|
||||
interface LinkExistingPracticeReviewStepProps {
|
||||
practice: ParentContextPractice
|
||||
targetParent: PracticeParent
|
||||
targetSummary: string
|
||||
titleHints?: PracticeParentTitleHints
|
||||
saving?: boolean
|
||||
onBack: () => void
|
||||
onConfirm: () => void
|
||||
variant?: "page" | "dialog"
|
||||
}
|
||||
|
||||
function ParentsSummaryValue({
|
||||
loading,
|
||||
text,
|
||||
}: {
|
||||
loading: boolean
|
||||
text: string
|
||||
}) {
|
||||
if (loading) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-2 text-grayScale-500">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
Loading locations…
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return <>{text}</>
|
||||
}
|
||||
|
||||
export function LinkExistingPracticeReviewStep({
|
||||
practice,
|
||||
targetParent,
|
||||
targetSummary,
|
||||
titleHints,
|
||||
saving = false,
|
||||
onBack,
|
||||
onConfirm,
|
||||
variant = "page",
|
||||
}: LinkExistingPracticeReviewStepProps) {
|
||||
const currentParentList = useMemo(
|
||||
() => dedupeParents(practice.parents ?? []),
|
||||
[practice.parents],
|
||||
)
|
||||
const afterParentList = useMemo(
|
||||
() => mergedParentsForAttach(practice, targetParent),
|
||||
[practice, targetParent],
|
||||
)
|
||||
const parentsToResolve = useMemo(
|
||||
() => dedupeParents([...currentParentList, ...afterParentList, targetParent]),
|
||||
[currentParentList, afterParentList, targetParent],
|
||||
)
|
||||
|
||||
const { titles, loading: titlesLoading } = usePracticeParentTitles(
|
||||
parentsToResolve,
|
||||
titleHints,
|
||||
)
|
||||
|
||||
const currentParents = formatPracticeParentsDisplaySummary(currentParentList, titles)
|
||||
const afterParents = formatPracticeParentsDisplaySummary(afterParentList, titles)
|
||||
const attachToLabel = titlesLoading
|
||||
? targetSummary
|
||||
: formatPracticeParentDisplayLabel(targetParent, titles)
|
||||
const alreadyLinked = practiceAlreadyLinkedToParent(practice, targetParent)
|
||||
const isDialog = variant === "dialog"
|
||||
|
||||
const reviewCard = (
|
||||
<Card
|
||||
className={cn(
|
||||
"overflow-hidden border-grayScale-200 bg-white shadow-sm",
|
||||
isDialog ? "rounded-xl p-5" : "rounded-2xl p-6",
|
||||
)}
|
||||
>
|
||||
<h2
|
||||
className={cn(
|
||||
"font-bold text-grayScale-900",
|
||||
isDialog ? "text-lg" : "text-xl",
|
||||
)}
|
||||
>
|
||||
Review attachment
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-grayScale-500">
|
||||
Confirm linking this practice to the selected content location.
|
||||
</p>
|
||||
|
||||
<dl className="mt-6 space-y-4 text-sm">
|
||||
<div>
|
||||
<dt className="text-xs font-bold uppercase tracking-wider text-grayScale-500">
|
||||
Practice
|
||||
</dt>
|
||||
<dd className="mt-1 font-semibold text-grayScale-900">
|
||||
{practice.title?.trim() || `Practice #${practice.id}`}
|
||||
</dd>
|
||||
<dd className="mt-0.5 font-mono text-xs text-grayScale-500">
|
||||
#{practice.id} · question set #{practice.question_set_id}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs font-bold uppercase tracking-wider text-grayScale-500">
|
||||
Attach to
|
||||
</dt>
|
||||
<dd className="mt-1 font-medium text-brand-700">
|
||||
<ParentsSummaryValue loading={titlesLoading} text={attachToLabel} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs font-bold uppercase tracking-wider text-grayScale-500">
|
||||
Current locations
|
||||
</dt>
|
||||
<dd className="mt-1 text-grayScale-700">
|
||||
<ParentsSummaryValue loading={titlesLoading} text={currentParents} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs font-bold uppercase tracking-wider text-grayScale-500">
|
||||
After attachment
|
||||
</dt>
|
||||
<dd className="mt-1 font-medium text-grayScale-900">
|
||||
<ParentsSummaryValue loading={titlesLoading} text={afterParents} />
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{alreadyLinked ? (
|
||||
<div className="mt-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950">
|
||||
This practice is already linked to this location.
|
||||
</div>
|
||||
) : null}
|
||||
</Card>
|
||||
)
|
||||
|
||||
const actions = (
|
||||
<div className="flex flex-col-reverse items-stretch justify-between gap-3 sm:flex-row sm:items-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onBack}
|
||||
disabled={saving}
|
||||
className="h-10 rounded-[6px] border-grayScale-200 bg-white px-8 text-sm font-bold text-grayScale-600"
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onConfirm}
|
||||
disabled={saving || alreadyLinked || titlesLoading}
|
||||
className="h-10 gap-2 rounded-[6px] bg-brand-500 px-8 text-sm font-bold text-white hover:bg-brand-600 disabled:opacity-50"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Linking…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4" />
|
||||
Link practice
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
|
||||
if (isDialog) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{reviewCard}
|
||||
{actions}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
{reviewCard}
|
||||
{actions}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
import { Input } from "../../../../components/ui/input"
|
||||
import type { PracticeParent, PracticeParentKind } from "../../../../types/course.types"
|
||||
import { dedupeParents, newParentRow } from "../../../../lib/practiceParents"
|
||||
|
||||
const KIND_OPTIONS: { value: PracticeParentKind; label: string }[] = [
|
||||
{ value: "COURSE", label: "Course" },
|
||||
{ value: "MODULE", label: "Module" },
|
||||
{ value: "LESSON", label: "Lesson" },
|
||||
]
|
||||
|
||||
interface PracticeParentsFieldProps {
|
||||
parents: PracticeParent[]
|
||||
onChange: (parents: PracticeParent[]) => void
|
||||
disabled?: boolean
|
||||
/** When set, this row cannot be removed (contextual entry point). */
|
||||
lockedParentKey?: string | null
|
||||
/** When true, all rows can be cleared (unlinked practice). */
|
||||
optional?: boolean
|
||||
}
|
||||
|
||||
function parentKey(parent: PracticeParent): string {
|
||||
return `${parent.parent_kind}:${parent.parent_id}`
|
||||
}
|
||||
|
||||
export function PracticeParentsField({
|
||||
parents,
|
||||
onChange,
|
||||
disabled = false,
|
||||
lockedParentKey = null,
|
||||
optional = false,
|
||||
}: PracticeParentsFieldProps) {
|
||||
const rows = parents.length > 0 ? parents : [newParentRow()]
|
||||
|
||||
const updateRow = (index: number, patch: Partial<PracticeParent>) => {
|
||||
const next = rows.map((row, i) => (i === index ? { ...row, ...patch } : row))
|
||||
onChange(dedupeParents(next))
|
||||
}
|
||||
|
||||
const removeRow = (index: number) => {
|
||||
const row = rows[index]
|
||||
if (lockedParentKey && parentKey(row) === lockedParentKey) return
|
||||
if (rows.length <= 1) {
|
||||
if (optional) onChange([])
|
||||
return
|
||||
}
|
||||
onChange(rows.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const addRow = () => {
|
||||
onChange([...rows, newParentRow()])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-grayScale-800">Attached locations</p>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
{optional
|
||||
? "Attach now or leave empty and link this practice later."
|
||||
: "Link this practice to one or more courses, modules, or lessons. Each location can only have one practice."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ul className="space-y-2">
|
||||
{rows.map((row, index) => {
|
||||
const key = parentKey(row)
|
||||
const isLocked = Boolean(lockedParentKey && key === lockedParentKey && row.parent_id > 0)
|
||||
return (
|
||||
<li
|
||||
key={`${index}-${row.parent_kind}`}
|
||||
className="flex flex-wrap items-center gap-2 rounded-xl border border-grayScale-200 bg-grayScale-50/50 px-3 py-2.5"
|
||||
>
|
||||
<select
|
||||
value={row.parent_kind}
|
||||
disabled={disabled || isLocked}
|
||||
onChange={(e) =>
|
||||
updateRow(index, { parent_kind: e.target.value as PracticeParentKind })
|
||||
}
|
||||
className="h-9 rounded-[8px] border border-grayScale-200 bg-white px-2.5 text-sm font-medium text-grayScale-700 focus:outline-none focus:ring-2 focus:ring-brand-200"
|
||||
>
|
||||
{KIND_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
disabled={disabled || isLocked}
|
||||
value={row.parent_id > 0 ? row.parent_id : ""}
|
||||
onChange={(e) =>
|
||||
updateRow(index, { parent_id: Number(e.target.value) || 0 })
|
||||
}
|
||||
placeholder="Parent id"
|
||||
className="h-9 w-28 rounded-[8px] border-grayScale-200 font-mono text-sm"
|
||||
/>
|
||||
<span className="text-xs text-grayScale-400 hidden sm:inline">
|
||||
{row.parent_kind} parent id from the content hierarchy
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="ml-auto h-8 w-8 p-0 text-grayScale-400 hover:text-red-600"
|
||||
disabled={disabled || rows.length <= 1 || isLocked}
|
||||
onClick={() => removeRow(index)}
|
||||
aria-label="Remove location"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
onClick={addRow}
|
||||
className="rounded-[8px] border-grayScale-200 text-xs font-semibold"
|
||||
>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />
|
||||
Add location
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -30,6 +30,7 @@ export type PracticeSequentialReviewProps = {
|
|||
saveError?: string | null;
|
||||
canPublish?: boolean;
|
||||
showMissingParentWarning?: boolean;
|
||||
showUnlinkedBanner?: boolean;
|
||||
onEditContext?: () => void;
|
||||
onEditQuestions?: () => void;
|
||||
onBack: () => void;
|
||||
|
|
@ -133,6 +134,7 @@ export function PracticeSequentialReview({
|
|||
saveError = null,
|
||||
canPublish = true,
|
||||
showMissingParentWarning = false,
|
||||
showUnlinkedBanner = false,
|
||||
onEditContext,
|
||||
onEditQuestions,
|
||||
onBack,
|
||||
|
|
@ -143,7 +145,12 @@ export function PracticeSequentialReview({
|
|||
sectionTitle = "Create Practice Questions",
|
||||
sectionSubtitle = "Define the dialogue flow and interactions for this scenario.",
|
||||
}: PracticeSequentialReviewProps) {
|
||||
const filledQuestions = questions.filter((q) => q.questionText.trim());
|
||||
const filledQuestions = questions.filter(
|
||||
(q) =>
|
||||
q.questionText.trim() ||
|
||||
q.voicePrompt.trim() ||
|
||||
q.sampleAnswerVoicePrompt.trim(),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-full space-y-6">
|
||||
|
|
@ -160,6 +167,16 @@ export function PracticeSequentialReview({
|
|||
</div>
|
||||
) : null}
|
||||
|
||||
{showUnlinkedBanner && parentLink === "Not attached to any course, module, or lesson" ? (
|
||||
<div className="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950">
|
||||
<p className="font-semibold">Not attached yet</p>
|
||||
<p className="mt-1 text-amber-900/90">
|
||||
This practice will be saved without course, module, or lesson links. Attach locations
|
||||
later from the practice editor.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showMissingParentWarning && !canPublish ? (
|
||||
<div className="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950">
|
||||
<p className="font-semibold">Missing parent for the API</p>
|
||||
|
|
@ -284,7 +301,7 @@ export function PracticeSequentialReview({
|
|||
{filledQuestions.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="max-h-[min(70vh,40rem)] space-y-6 overflow-y-auto overscroll-y-contain px-6 py-5">
|
||||
<div className="space-y-6 px-6 py-5">
|
||||
{filledQuestions.map((question, index) => (
|
||||
<div key={question.id} className="space-y-3">
|
||||
<span className="text-sm font-bold text-grayScale-400">
|
||||
|
|
@ -333,7 +350,7 @@ export function PracticeSequentialReview({
|
|||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="max-h-[min(70vh,40rem)] space-y-6 overflow-y-auto overscroll-y-contain px-6 py-5">
|
||||
<div className="space-y-6 px-6 py-5">
|
||||
{filledQuestions.map((question, index) => (
|
||||
<div key={question.id} className="space-y-3">
|
||||
<span className="text-sm font-bold text-grayScale-400">
|
||||
|
|
|
|||
|
|
@ -0,0 +1,111 @@
|
|||
import { Select } from "../../../../components/ui/select"
|
||||
import {
|
||||
getSectionAnchorOptions,
|
||||
isQuestionSectionAnchor,
|
||||
setQuestionSectionAnchorRef,
|
||||
type QuestionAssociationRow,
|
||||
} from "../../../../lib/questionAssociations"
|
||||
|
||||
type QuestionAssociationFieldProps = {
|
||||
question: QuestionAssociationRow
|
||||
allQuestions: QuestionAssociationRow[]
|
||||
onChange: (patch: {
|
||||
associatedQuestionId: number | null
|
||||
associatedAnchorRowId: string | null
|
||||
}) => void
|
||||
}
|
||||
|
||||
export function QuestionAssociationField({
|
||||
question,
|
||||
allQuestions,
|
||||
onChange,
|
||||
}: QuestionAssociationFieldProps) {
|
||||
const isAnchor = isQuestionSectionAnchor(question)
|
||||
const anchorOptions = getSectionAnchorOptions(allQuestions, question.id)
|
||||
const selectedValue =
|
||||
question.associatedQuestionId != null
|
||||
? String(question.associatedQuestionId)
|
||||
: question.associatedAnchorRowId ?? ""
|
||||
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border border-sky-100 bg-sky-50/50 p-3">
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-sky-800">
|
||||
Section grouping
|
||||
</p>
|
||||
<label className="flex items-center gap-2 text-sm text-grayScale-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isAnchor}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
onChange({ associatedQuestionId: null, associatedAnchorRowId: null })
|
||||
return
|
||||
}
|
||||
const firstAnchor = anchorOptions[0]
|
||||
if (!firstAnchor) return
|
||||
const anchorRow = allQuestions.find(
|
||||
(q) =>
|
||||
q.serverQuestionId === firstAnchor.serverId ||
|
||||
q.id === String(firstAnchor.value),
|
||||
)
|
||||
if (!anchorRow) return
|
||||
const next = setQuestionSectionAnchorRef(question, anchorRow)
|
||||
onChange({
|
||||
associatedQuestionId: next.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: next.associatedAnchorRowId ?? null,
|
||||
})
|
||||
}}
|
||||
/>
|
||||
Starts a new section (anchor)
|
||||
</label>
|
||||
|
||||
{!isAnchor ? (
|
||||
<div className="space-y-1">
|
||||
<label className="text-[10px] font-medium uppercase tracking-wide text-grayScale-500">
|
||||
Section anchor
|
||||
</label>
|
||||
<Select
|
||||
value={selectedValue}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value
|
||||
if (!value) {
|
||||
onChange({ associatedQuestionId: null, associatedAnchorRowId: null })
|
||||
return
|
||||
}
|
||||
const anchorRow = allQuestions.find(
|
||||
(q) => q.id === value || String(q.serverQuestionId ?? "") === value,
|
||||
)
|
||||
if (!anchorRow) return
|
||||
const next = setQuestionSectionAnchorRef(question, anchorRow)
|
||||
onChange({
|
||||
associatedQuestionId: next.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: next.associatedAnchorRowId ?? null,
|
||||
})
|
||||
}}
|
||||
>
|
||||
<option value="">Select section anchor…</option>
|
||||
{anchorOptions.map((opt) => (
|
||||
<option key={String(opt.value)} value={String(opt.value)}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<p className="text-[10px] text-grayScale-400">
|
||||
Learners complete earlier sections before this question unlocks.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-grayScale-500">
|
||||
This question opens a new section. Link follow-up questions to it using the
|
||||
section anchor dropdown.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{question.prerequisiteQuestionIds && question.prerequisiteQuestionIds.length > 0 ? (
|
||||
<p className="text-[10px] text-grayScale-500">
|
||||
Prerequisites (from API): {question.prerequisiteQuestionIds.join(", ")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -38,13 +38,23 @@ import {
|
|||
legacyQuestionTypeFromDefinition,
|
||||
} from "../../../../lib/learnEnglishDefinitionQuestion";
|
||||
import { validateLearnEnglishQuestionsWithDefinitions } from "../../../../lib/learnEnglishPracticePublish";
|
||||
import {
|
||||
fixAssociationsAfterReorder,
|
||||
findLastSectionAnchor,
|
||||
sectionBadgeLabel,
|
||||
setQuestionSectionAnchorRef,
|
||||
validateQuestionAssociations,
|
||||
} from "../../../../lib/questionAssociations";
|
||||
import { cn } from "../../../../lib/utils";
|
||||
import { toast } from "sonner";
|
||||
import { QuestionAssociationField } from "./QuestionAssociationField";
|
||||
|
||||
function syncQuestionDisplayOrders<T extends { displayOrder?: number }>(
|
||||
questions: T[],
|
||||
): T[] {
|
||||
return questions.map((q, index) => ({ ...q, displayOrder: index + 1 }));
|
||||
return fixAssociationsAfterReorder(
|
||||
questions.map((q, index) => ({ ...q, displayOrder: index + 1 })),
|
||||
);
|
||||
}
|
||||
|
||||
function truncateText(value: string, max = 100): string {
|
||||
|
|
@ -152,11 +162,17 @@ function defaultMcqOptions() {
|
|||
];
|
||||
}
|
||||
|
||||
function createEmptyQuestionRow(id: string, displayOrder = 1) {
|
||||
function createEmptyQuestionRow(id: string, displayOrder = 1, inheritAnchor?: {
|
||||
associatedQuestionId: number | null
|
||||
associatedAnchorRowId: string | null
|
||||
}) {
|
||||
return {
|
||||
id,
|
||||
displayOrder,
|
||||
serverQuestionId: null as number | null,
|
||||
associatedQuestionId: inheritAnchor?.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: inheritAnchor?.associatedAnchorRowId ?? null,
|
||||
prerequisiteQuestionIds: [] as number[],
|
||||
questionTypeDefinitionId: null as number | null,
|
||||
text: "",
|
||||
difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD",
|
||||
|
|
@ -273,9 +289,22 @@ export function QuestionsStep({
|
|||
setFormData({ ...formData, questions: newQuestions });
|
||||
};
|
||||
|
||||
const addQuestion = () => {
|
||||
const addQuestion = (startNewSection = false) => {
|
||||
const id = `q${Date.now()}`;
|
||||
const row = createEmptyQuestionRow(id);
|
||||
const lastAnchor = startNewSection ? undefined : findLastSectionAnchor(formData.questions);
|
||||
const inheritAnchor = lastAnchor
|
||||
? (() => {
|
||||
const linked = setQuestionSectionAnchorRef(
|
||||
{ id, associatedQuestionId: null, associatedAnchorRowId: null },
|
||||
lastAnchor,
|
||||
);
|
||||
return {
|
||||
associatedQuestionId: linked.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: linked.associatedAnchorRowId ?? null,
|
||||
};
|
||||
})()
|
||||
: undefined;
|
||||
const row = createEmptyQuestionRow(id, formData.questions.length + 1, inheritAnchor);
|
||||
if (typeDefinitions[0]) {
|
||||
row.questionTypeDefinitionId = typeDefinitions[0].id;
|
||||
row.dynamicFieldValues = emptyDynamicFieldValuesForDefinition(
|
||||
|
|
@ -511,8 +540,9 @@ export function QuestionsStep({
|
|||
<div className="space-y-1 px-2">
|
||||
<h2 className="text-2xl font-bold text-grayScale-700">Questions</h2>
|
||||
<p className="text-grayScale-400 text-lg">
|
||||
Choose a question type for each item, then fill in the fields that type requires. Collapse cards to
|
||||
compare and drag them into order. Questions are saved when you publish or save the practice.
|
||||
Choose a question type for each item, then fill in the fields that type requires.
|
||||
Group questions into sections so learners complete earlier blocks before later ones unlock.
|
||||
Collapse cards to compare and drag them into order.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
@ -618,6 +648,9 @@ export function QuestionsStep({
|
|||
<span className="rounded-full bg-grayScale-100 px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-grayScale-600">
|
||||
{q.difficultyLevel ?? "EASY"}
|
||||
</span>
|
||||
<span className="rounded-full bg-sky-100 px-2.5 py-0.5 text-[11px] font-semibold text-sky-800">
|
||||
{sectionBadgeLabel(q, formData.questions)}
|
||||
</span>
|
||||
<span className="text-xs font-medium text-grayScale-500">
|
||||
{q.points ?? 1} pt{(q.points ?? 1) === 1 ? "" : "s"}
|
||||
</span>
|
||||
|
|
@ -679,6 +712,16 @@ export function QuestionsStep({
|
|||
|
||||
<QuestionCollapsibleBody expanded={isExpanded}>
|
||||
<div className="space-y-6 px-4 pb-6 pt-4 sm:px-5 sm:pb-7">
|
||||
<QuestionAssociationField
|
||||
question={q}
|
||||
allQuestions={formData.questions}
|
||||
onChange={(patch) => {
|
||||
const newQuestions = [...formData.questions];
|
||||
newQuestions[i] = { ...newQuestions[i], ...patch };
|
||||
setFormData({ ...formData, questions: newQuestions });
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<label className="text-[10px] font-bold uppercase tracking-widest text-grayScale-700">
|
||||
|
|
@ -830,10 +873,10 @@ export function QuestionsStep({
|
|||
</DragOverlay>
|
||||
</DndContext>
|
||||
|
||||
<div className="flex items-center gap-8 pt-4">
|
||||
<div className="flex flex-wrap items-center gap-6 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={addQuestion}
|
||||
onClick={() => addQuestion(false)}
|
||||
disabled={definitionsLoading || typeDefinitions.length === 0}
|
||||
className="flex items-center gap-3 text-base font-bold text-brand-500 transition-all hover:opacity-80 disabled:opacity-40"
|
||||
>
|
||||
|
|
@ -842,6 +885,17 @@ export function QuestionsStep({
|
|||
</div>
|
||||
Add question
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => addQuestion(true)}
|
||||
disabled={definitionsLoading || typeDefinitions.length === 0}
|
||||
className="flex items-center gap-3 text-base font-bold text-sky-700 transition-all hover:opacity-80 disabled:opacity-40"
|
||||
>
|
||||
<div className="flex h-5 w-5 items-center justify-center rounded-full border-2 border-sky-600">
|
||||
<Plus className="h-3 w-3 stroke-[4]" />
|
||||
</div>
|
||||
Start new section
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-8">
|
||||
|
|
@ -857,9 +911,13 @@ export function QuestionsStep({
|
|||
type="button"
|
||||
onClick={() => {
|
||||
const mapped = formData.questions.map((row: typeof formData.questions[0]) => ({
|
||||
clientRowId: row.id,
|
||||
questionText: String(row.text ?? "").trim(),
|
||||
questionTypeDefinitionId: Number(row.questionTypeDefinitionId),
|
||||
dynamicFieldValues: { ...(row.dynamicFieldValues ?? {}) },
|
||||
displayOrder: row.displayOrder,
|
||||
associatedQuestionId: row.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: row.associatedAnchorRowId ?? null,
|
||||
mcqOptions: (row.mcqOptions ?? []).map(
|
||||
(o: { text?: string; isCorrect?: boolean }) => ({
|
||||
option_text: String(o.text ?? ""),
|
||||
|
|
@ -869,6 +927,19 @@ export function QuestionsStep({
|
|||
trueFalseAnswerIsTrue: row.trueFalseCorrect !== false,
|
||||
shortAnswers: (row.shortAnswers ?? []).map((s: string) => String(s)),
|
||||
}));
|
||||
const associationErr = validateQuestionAssociations(
|
||||
formData.questions.map((row: typeof formData.questions[0]) => ({
|
||||
id: row.id,
|
||||
serverQuestionId: row.serverQuestionId ?? null,
|
||||
displayOrder: row.displayOrder,
|
||||
associatedQuestionId: row.associatedQuestionId ?? null,
|
||||
associatedAnchorRowId: row.associatedAnchorRowId ?? null,
|
||||
})),
|
||||
);
|
||||
if (associationErr) {
|
||||
toast.error("Check question sections", { description: associationErr });
|
||||
return;
|
||||
}
|
||||
const msg = validateLearnEnglishQuestionsWithDefinitions(
|
||||
mapped,
|
||||
typeDefinitions,
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ interface ReviewStepProps {
|
|||
onPublish: () => void;
|
||||
publishLabel?: string;
|
||||
publishingLabel?: string;
|
||||
allowUnlinkedParents?: boolean;
|
||||
}
|
||||
|
||||
export function ReviewStep({
|
||||
|
|
@ -62,6 +63,7 @@ export function ReviewStep({
|
|||
onPublish,
|
||||
publishLabel,
|
||||
publishingLabel,
|
||||
allowUnlinkedParents = false,
|
||||
}: ReviewStepProps) {
|
||||
const persona = personaFromId(selectedPersona, personas);
|
||||
|
||||
|
|
@ -112,7 +114,8 @@ export function ReviewStep({
|
|||
questions={reviewQuestions}
|
||||
saving={submitting}
|
||||
canPublish={canPublish}
|
||||
showMissingParentWarning
|
||||
showMissingParentWarning={!allowUnlinkedParents}
|
||||
showUnlinkedBanner={allowUnlinkedParents}
|
||||
onEditContext={onEditContext}
|
||||
onEditQuestions={onEditQuestions}
|
||||
onBack={prevStep}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,386 @@
|
|||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { ArrowRight, ChevronLeft, ChevronRight, Search } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../../../components/ui/button"
|
||||
import { Card } from "../../../../components/ui/card"
|
||||
import { Input } from "../../../../components/ui/input"
|
||||
import { SpinnerIcon } from "../../../../components/ui/spinner-icon"
|
||||
import { practiceAlreadyLinkedToParent } from "../../../../lib/attachPracticeToParent"
|
||||
import { fetchAllPractices } from "../../../../lib/fetchAllPractices"
|
||||
import { learnEnglishPracticeApiErrorMessage } from "../../../../lib/learnEnglishPracticePublish"
|
||||
import { formatPracticeParentsSummary } from "../../../../lib/practiceParents"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../../../lib/tablePagination"
|
||||
import type { ParentContextPractice, PracticeParent } from "../../../../types/course.types"
|
||||
import { cn } from "../../../../lib/utils"
|
||||
import { SearchHighlight, getSearchTokens } from "../../../../components/SearchHighlight"
|
||||
|
||||
interface SelectPracticeToAttachStepProps {
|
||||
targetParent: PracticeParent
|
||||
targetSummary: string
|
||||
selectedPracticeId: number | null
|
||||
onSelect: (practice: ParentContextPractice) => void
|
||||
nextStep: () => void
|
||||
onCancel: () => void
|
||||
variant?: "page" | "dialog"
|
||||
}
|
||||
|
||||
function publishStatusClass(status?: string | null): string {
|
||||
const s = (status || "").toUpperCase()
|
||||
if (s === "PUBLISHED") return "bg-[#F0FDF4] text-[#16A34A]"
|
||||
if (s === "DRAFT") return "bg-amber-50 text-amber-800"
|
||||
return "bg-grayScale-50 text-grayScale-600"
|
||||
}
|
||||
|
||||
function matchesPracticeSearch(
|
||||
practice: ParentContextPractice,
|
||||
query: string,
|
||||
): boolean {
|
||||
const tokens = getSearchTokens(query)
|
||||
if (tokens.length === 0) return true
|
||||
const haystack = [
|
||||
practice.title ?? "",
|
||||
practice.story_description ?? "",
|
||||
String(practice.id),
|
||||
String(practice.question_set_id),
|
||||
formatPracticeParentsSummary(practice.parents ?? []),
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return tokens.every((token) => haystack.includes(token.toLowerCase()))
|
||||
}
|
||||
|
||||
export function SelectPracticeToAttachStep({
|
||||
targetParent,
|
||||
targetSummary,
|
||||
selectedPracticeId,
|
||||
onSelect,
|
||||
nextStep,
|
||||
onCancel,
|
||||
variant = "page",
|
||||
}: SelectPracticeToAttachStepProps) {
|
||||
const isDialog = variant === "dialog"
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [allPractices, setAllPractices] = useState<ParentContextPractice[]>([])
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [unlinkedOnly, setUnlinkedOnly] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const practices = await fetchAllPractices(unlinkedOnly)
|
||||
setAllPractices(practices)
|
||||
} catch (e) {
|
||||
toast.error("Could not load practices", {
|
||||
description: learnEnglishPracticeApiErrorMessage(e),
|
||||
})
|
||||
setAllPractices([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [unlinkedOnly])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
setOffset(0)
|
||||
}, [searchInput, unlinkedOnly, pageSize])
|
||||
|
||||
const filteredPractices = useMemo(
|
||||
() => allPractices.filter((practice) => matchesPracticeSearch(practice, searchInput)),
|
||||
[allPractices, searchInput],
|
||||
)
|
||||
|
||||
const totalCount = filteredPractices.length
|
||||
const practices = useMemo(
|
||||
() => filteredPractices.slice(offset, offset + pageSize),
|
||||
[filteredPractices, offset, pageSize],
|
||||
)
|
||||
|
||||
const pageStart = totalCount === 0 ? 0 : offset + 1
|
||||
const pageEnd = Math.min(offset + practices.length, totalCount)
|
||||
const canPrev = offset > 0
|
||||
const canNext = offset + pageSize < totalCount
|
||||
|
||||
const canContinue = selectedPracticeId != null
|
||||
|
||||
const header = (
|
||||
<div
|
||||
className={cn(
|
||||
"border-b border-grayScale-50",
|
||||
isDialog ? "px-5 py-4" : "px-8 pt-8 pb-4",
|
||||
)}
|
||||
>
|
||||
<h2
|
||||
className={cn(
|
||||
"font-bold leading-none text-grayScale-900",
|
||||
isDialog ? "text-lg" : "text-xl",
|
||||
)}
|
||||
>
|
||||
Select a practice
|
||||
</h2>
|
||||
<p className={cn("text-grayScale-600", isDialog ? "mt-1 text-sm" : "mt-3 text-base")}>
|
||||
Link an existing practice to{" "}
|
||||
<span className="font-medium text-grayScale-800">{targetSummary}</span>.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
const filters = (
|
||||
<div
|
||||
className={cn(
|
||||
"space-y-4 border-b border-grayScale-100",
|
||||
isDialog ? "px-5 py-3" : "px-8 py-5",
|
||||
)}
|
||||
>
|
||||
<div className="relative min-w-0">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder="Search by title, id, or location…"
|
||||
className="h-10 rounded-[8px] border-grayScale-200 pl-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Show:</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUnlinkedOnly(false)}
|
||||
className={cn(
|
||||
"rounded-full px-3 py-1 text-xs font-semibold transition-colors",
|
||||
!unlinkedOnly
|
||||
? "bg-brand-500 text-white"
|
||||
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
All practices
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUnlinkedOnly(true)}
|
||||
className={cn(
|
||||
"rounded-full px-3 py-1 text-xs font-semibold transition-colors",
|
||||
unlinkedOnly
|
||||
? "bg-brand-500 text-white"
|
||||
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
Unlinked only
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const listBody = (
|
||||
<div className={cn(isDialog ? "min-h-[220px]" : "min-h-[280px]")}>
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 px-6 py-16">
|
||||
<SpinnerIcon className="h-8 w-8 text-brand-500" />
|
||||
<p className="text-sm text-grayScale-500">Loading practices…</p>
|
||||
</div>
|
||||
) : practices.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 px-6 py-16 text-center">
|
||||
<p className="text-sm font-semibold text-grayScale-700">No practices found</p>
|
||||
<p className="max-w-sm text-xs text-grayScale-500">
|
||||
{unlinkedOnly
|
||||
? "No unlinked practices match your search. Try all practices or create a new shell from Question Types."
|
||||
: "Try a different search, switch to unlinked only, or create a new practice instead."}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-grayScale-100">
|
||||
{practices.map((practice) => {
|
||||
const alreadyLinked = practiceAlreadyLinkedToParent(practice, targetParent)
|
||||
const isSelected = practice.id === selectedPracticeId
|
||||
const parentsLabel = formatPracticeParentsSummary(practice.parents ?? [])
|
||||
return (
|
||||
<li key={practice.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={alreadyLinked}
|
||||
onClick={() => onSelect(practice)}
|
||||
className={cn(
|
||||
"flex w-full flex-col gap-2 text-left transition-colors sm:flex-row sm:items-start sm:justify-between",
|
||||
isDialog ? "px-5 py-3.5" : "px-8 py-4",
|
||||
alreadyLinked
|
||||
? "cursor-not-allowed bg-grayScale-50/80 opacity-60"
|
||||
: isSelected
|
||||
? "bg-brand-50/60"
|
||||
: "hover:bg-grayScale-50",
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 flex-1 space-y-1.5">
|
||||
<p className="text-sm font-semibold leading-snug text-grayScale-900">
|
||||
<SearchHighlight
|
||||
text={practice.title?.trim() || `Practice #${practice.id}`}
|
||||
query={searchInput}
|
||||
/>
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-grayScale-500">
|
||||
<span className="font-mono">
|
||||
<SearchHighlight text={`#${practice.id}`} query={searchInput} />
|
||||
</span>
|
||||
<span className="text-grayScale-300">·</span>
|
||||
<span className="font-mono">
|
||||
<SearchHighlight
|
||||
text={`set #${practice.question_set_id}`}
|
||||
query={searchInput}
|
||||
/>
|
||||
</span>
|
||||
<span className="text-grayScale-300">·</span>
|
||||
<span>
|
||||
<SearchHighlight text={parentsLabel} query={searchInput} />
|
||||
</span>
|
||||
</div>
|
||||
{practice.story_description?.trim() ? (
|
||||
<p className="line-clamp-2 text-xs text-grayScale-500">
|
||||
<SearchHighlight
|
||||
text={practice.story_description}
|
||||
query={searchInput}
|
||||
/>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"rounded px-2 py-0.5 text-[10px] font-bold uppercase",
|
||||
publishStatusClass(practice.publish_status),
|
||||
)}
|
||||
>
|
||||
{(practice.publish_status || "—").toString()}
|
||||
</span>
|
||||
{alreadyLinked ? (
|
||||
<span className="text-[11px] font-semibold text-brand-600">
|
||||
Already linked
|
||||
</span>
|
||||
) : isSelected ? (
|
||||
<span className="text-[11px] font-semibold text-brand-600">Selected</span>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
const pagination =
|
||||
!loading && totalCount > 0 ? (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-wrap items-center justify-between gap-3 border-t border-grayScale-100 text-xs text-grayScale-500",
|
||||
isDialog ? "px-5 py-2.5" : "px-8 py-3",
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
Showing {pageStart}–{pageEnd} of {totalCount}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||
className="h-8 rounded-[8px] border border-grayScale-200 bg-white px-2 text-xs"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size} / page
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
disabled={!canPrev}
|
||||
onClick={() => setOffset((o) => Math.max(0, o - pageSize))}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
disabled={!canNext}
|
||||
onClick={() => setOffset((o) => o + pageSize)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null
|
||||
|
||||
const footer = (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between border-t border-grayScale-100",
|
||||
isDialog
|
||||
? "bg-grayScale-50/60 px-5 py-3.5"
|
||||
: "bg-[#F8FAFC] p-4 px-12",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"text-grayScale-500 transition-colors hover:text-grayScale-700",
|
||||
isDialog ? "text-sm" : "text-[14px] font-bold",
|
||||
)}
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={!canContinue}
|
||||
onClick={nextStep}
|
||||
className={cn(
|
||||
"bg-brand-500 font-bold text-white hover:bg-brand-600 disabled:opacity-50",
|
||||
isDialog
|
||||
? "h-10 rounded-[6px] px-8 text-sm"
|
||||
: "flex h-10 items-center gap-2 rounded-[6px] px-10 text-[14px] transition-all active:scale-95",
|
||||
)}
|
||||
>
|
||||
Next: Review
|
||||
<ArrowRight className={cn(isDialog ? "ml-2 h-4 w-4" : "h-5 w-5")} />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
|
||||
if (isDialog) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
{header}
|
||||
{filters}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{listBody}</div>
|
||||
{pagination}
|
||||
{footer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="animate-in fade-in overflow-hidden rounded-2xl border-grayScale-300 bg-white shadow-sm duration-500">
|
||||
{header}
|
||||
<div className="relative" aria-hidden="true">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-grayScale-200" />
|
||||
</div>
|
||||
<div className="relative flex justify-center">
|
||||
<div className="h-[0.5px] w-full rounded-full opacity-20" style={{ background: "gray" }} />
|
||||
</div>
|
||||
</div>
|
||||
{filters}
|
||||
{listBody}
|
||||
{pagination}
|
||||
{footer}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,7 +1,10 @@
|
|||
import { questionTypeDefinitionListLabel } from "../../../../api/questionTypeDefinitions.api";
|
||||
import type { QuestionTypeDefinition } from "../../../../types/questionTypeDefinition.types";
|
||||
import {
|
||||
definitionUsesDynamicPayload,
|
||||
dynamicPromptFromFieldValues,
|
||||
legacyQuestionTypeFromDefinition,
|
||||
questionRowHasContent,
|
||||
} from "../../../../lib/learnEnglishDefinitionQuestion";
|
||||
import type { PracticeReviewQuestion } from "./PracticeSequentialReview";
|
||||
|
||||
|
|
@ -33,6 +36,54 @@ function firstUrlFromSchema(
|
|||
return "";
|
||||
}
|
||||
|
||||
function practiceReviewQuestionText(
|
||||
q: {
|
||||
text?: string;
|
||||
dynamicFieldValues?: Record<string, string>;
|
||||
questionTypeDefinitionId?: number | null;
|
||||
},
|
||||
def: QuestionTypeDefinition | undefined,
|
||||
): string {
|
||||
const text = String(q.text ?? "").trim();
|
||||
if (text) return text;
|
||||
|
||||
const values = q.dynamicFieldValues ?? {};
|
||||
if (def) {
|
||||
const prompt = dynamicPromptFromFieldValues(def, values);
|
||||
if (prompt) return prompt;
|
||||
}
|
||||
|
||||
const rawValues = Object.values(values)
|
||||
.map((v) => String(v ?? "").trim())
|
||||
.filter((v) => v && !v.startsWith("{") && !v.startsWith("["));
|
||||
if (rawValues[0]) return rawValues[0];
|
||||
|
||||
if (def) return questionTypeDefinitionListLabel(def);
|
||||
return "";
|
||||
}
|
||||
|
||||
function questionHasReviewContent(
|
||||
q: {
|
||||
text?: string;
|
||||
dynamicFieldValues?: Record<string, string>;
|
||||
questionTypeDefinitionId?: number | null;
|
||||
},
|
||||
def: QuestionTypeDefinition | undefined,
|
||||
voicePrompt: string,
|
||||
sampleAnswerVoicePrompt: string,
|
||||
): boolean {
|
||||
if (voicePrompt || sampleAnswerVoicePrompt) return true;
|
||||
if (!def) return Boolean(String(q.text ?? "").trim());
|
||||
return questionRowHasContent(
|
||||
{
|
||||
questionText: String(q.text ?? "").trim(),
|
||||
questionTypeDefinitionId: q.questionTypeDefinitionId ?? 0,
|
||||
dynamicFieldValues: q.dynamicFieldValues ?? {},
|
||||
},
|
||||
def,
|
||||
);
|
||||
}
|
||||
|
||||
export function mapFormQuestionsForPracticeReview(
|
||||
questions: {
|
||||
id: string;
|
||||
|
|
@ -42,7 +93,7 @@ export function mapFormQuestionsForPracticeReview(
|
|||
}[],
|
||||
typeDefinitions: QuestionTypeDefinition[],
|
||||
): PracticeReviewQuestion[] {
|
||||
return questions.map((q) => {
|
||||
return questions.flatMap((q) => {
|
||||
const def = typeDefinitions.find(
|
||||
(d) => d.id === q.questionTypeDefinitionId,
|
||||
);
|
||||
|
|
@ -73,11 +124,19 @@ export function mapFormQuestionsForPracticeReview(
|
|||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: q.id,
|
||||
questionText: String(q.text ?? "").trim(),
|
||||
voicePrompt,
|
||||
sampleAnswerVoicePrompt,
|
||||
};
|
||||
if (
|
||||
!questionHasReviewContent(q, def, voicePrompt, sampleAnswerVoicePrompt)
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: q.id,
|
||||
questionText: practiceReviewQuestionText(q, def),
|
||||
voicePrompt,
|
||||
sampleAnswerVoicePrompt,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export function InfoLayout({
|
|||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<div className="relative min-h-screen overflow-hidden bg-[#fefcff] px-4 py-10 sm:px-6">
|
||||
<div className="relative h-dvh overflow-y-auto bg-[#fefcff] px-4 py-10 sm:px-6">
|
||||
<div className="pointer-events-none absolute -left-24 -top-24 h-72 w-72 rounded-full bg-[#f3e8ff]" />
|
||||
<div className="pointer-events-none absolute -right-20 top-24 h-64 w-64 rounded-full bg-[#f5ecff]" />
|
||||
<div className="mx-auto w-full max-w-5xl rounded-2xl border border-[#eadff7] bg-white px-6 py-6 shadow-[0_20px_60px_rgba(83,33,120,0.08)] sm:px-10 sm:py-8">
|
||||
|
|
|
|||
|
|
@ -547,8 +547,11 @@ export interface GetTopLevelModuleLessonsResponse {
|
|||
/** Practice returned by GET /courses|modules|lessons/.../practices (Learn English parent-linked practice). */
|
||||
export interface ParentContextPractice {
|
||||
id: number
|
||||
parent_kind: string
|
||||
parent_id: number
|
||||
parents: PracticeParent[] | null
|
||||
/** @deprecated use parents[] */
|
||||
parent_kind?: string
|
||||
/** @deprecated use parents[] */
|
||||
parent_id?: number
|
||||
title: string
|
||||
story_description: string
|
||||
story_image: string
|
||||
|
|
@ -572,8 +575,24 @@ export interface GetPracticesByParentContextResponse {
|
|||
metadata: unknown | null
|
||||
}
|
||||
|
||||
/** GET /practices — paginated list of all Learn English practices. */
|
||||
export type GetPracticesListResponse = GetPracticesByParentContextResponse
|
||||
|
||||
export interface GetPracticesListParams {
|
||||
limit?: number
|
||||
offset?: number
|
||||
search?: string
|
||||
/** `true` → `parents: null` only; `false` → practices with parent links. */
|
||||
unlinked_only?: boolean
|
||||
}
|
||||
|
||||
export type PracticeParentKind = "COURSE" | "MODULE" | "LESSON"
|
||||
|
||||
export interface PracticeParent {
|
||||
parent_kind: PracticeParentKind
|
||||
parent_id: number
|
||||
}
|
||||
|
||||
export type PracticePublishStatus = "DRAFT" | "PUBLISHED"
|
||||
|
||||
export type ContentAccessTier = "FREE" | "PREMIUM"
|
||||
|
|
@ -588,10 +607,12 @@ export interface PublishStatusOnlyRequest {
|
|||
publish_status: PracticePublishStatus
|
||||
}
|
||||
|
||||
/** POST /practices — create practice linked to a course, module, or lesson (Learn English). */
|
||||
/** POST /practices — create practice linked to one or more hierarchy nodes (Learn English). */
|
||||
export interface CreateParentLinkedPracticeRequest {
|
||||
parent_kind: PracticeParentKind
|
||||
parent_id: number
|
||||
parents?: PracticeParent[] | null
|
||||
/** Legacy single-parent create; used when parents is omitted. */
|
||||
parent_kind?: PracticeParentKind
|
||||
parent_id?: number
|
||||
title: string
|
||||
story_description: string
|
||||
story_image: string
|
||||
|
|
@ -609,8 +630,9 @@ export interface CreateParentLinkedPracticeResponse {
|
|||
metadata: unknown | null
|
||||
}
|
||||
|
||||
/** Body for PUT /practices/:id (Learn English parent-linked practice). */
|
||||
/** Body for PUT /practices/:id (Learn English practice shell — includes parent links). */
|
||||
export interface UpdateParentLinkedPracticeRequest {
|
||||
parents?: PracticeParent[]
|
||||
title?: string
|
||||
story_description?: string
|
||||
story_image?: string
|
||||
|
|
@ -633,10 +655,25 @@ export interface UpdateParentLinkedPracticeResponse {
|
|||
metadata: unknown | null
|
||||
}
|
||||
|
||||
/** PUT /practices/:id/parents — replace all parent links on a practice. */
|
||||
export interface UpdatePracticeParentsRequest {
|
||||
parents: PracticeParent[]
|
||||
}
|
||||
|
||||
export interface UpdatePracticeParentsResponse {
|
||||
message: string
|
||||
data: ParentContextPractice
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: unknown | null
|
||||
}
|
||||
|
||||
/** Question row in GET/PUT /practices/:id/full and /exam-prep/practices/:id/full. */
|
||||
export interface PracticeFullQuestionItem {
|
||||
id?: number | null
|
||||
display_order: number
|
||||
associated_question_id?: number | null
|
||||
prerequisite_question_ids?: number[]
|
||||
question_text?: string
|
||||
question_type: string
|
||||
question_type_definition_id?: number | null
|
||||
|
|
@ -681,8 +718,12 @@ export interface PracticeFullPractice {
|
|||
question_set_id: number
|
||||
publish_status?: PracticePublishStatus | string | null
|
||||
quick_tips?: string
|
||||
parents?: PracticeParent[]
|
||||
/** @deprecated use parents[] */
|
||||
lesson_id?: number
|
||||
/** @deprecated use parents[] */
|
||||
parent_kind?: string
|
||||
/** @deprecated use parents[] */
|
||||
parent_id?: number
|
||||
created_at?: string
|
||||
}
|
||||
|
|
@ -1236,6 +1277,7 @@ export interface CreateQuestionSetRequest {
|
|||
export interface AddQuestionToSetRequest {
|
||||
display_order?: number
|
||||
question_id: number
|
||||
associated_question_id?: number | null
|
||||
}
|
||||
|
||||
export interface QuestionOption {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
/** Dynamic question type definition builder (admin) — aligns with POST /questions/type-definitions */
|
||||
|
||||
import type { PracticeParent } from "./course.types"
|
||||
|
||||
/** GET /questions/component-catalog — `data` object shape */
|
||||
export interface QuestionComponentCatalog {
|
||||
stimulus_component_kinds: string[]
|
||||
|
|
@ -56,3 +58,41 @@ export interface DynamicQuestionPayload {
|
|||
stimulus: DynamicElementInstance[]
|
||||
response: DynamicElementInstance[]
|
||||
}
|
||||
|
||||
/** Row from GET /questions/type-definitions/:id/practices */
|
||||
export interface QuestionTypeDefinitionPractice {
|
||||
practice_kind: string
|
||||
practice_id: number
|
||||
question_set_id: number
|
||||
title: string
|
||||
story_description?: string
|
||||
story_image?: string
|
||||
quick_tips?: string
|
||||
publish_status?: string
|
||||
parents: PracticeParent[] | null
|
||||
/** @deprecated use parents[] */
|
||||
parent_kind?: string
|
||||
/** @deprecated use parents[] */
|
||||
parent_id?: number
|
||||
/** When returned by the API, used to build edit routes without hierarchy search. */
|
||||
program_id?: number
|
||||
course_id?: number
|
||||
module_id?: number
|
||||
lesson_id?: number
|
||||
matching_question_count: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface QuestionTypeDefinitionPracticesParams {
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export interface QuestionTypeDefinitionPracticesResult {
|
||||
question_type_definition_id: number
|
||||
practices: QuestionTypeDefinitionPractice[]
|
||||
total_count: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user