From af1ea866c2cabb2197a437ef7c726bd1d182c95a Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Fri, 23 Oct 2026 16:14:06 +0530 Subject: [PATCH 1/7] feat: Enhance Dynamic Assess functionality and improve content handling - Introduced new endpoints and fields for Dynamic Course Assessment in ContentEditorService. - Added logic to handle reading and refreshing content body specifically for Dynamic Assess. - Implemented new utility functions for determining the deepest category code and handling skill pool counts. - Enhanced taxonomy tests to cover new functionality. - Updated mock services to simulate new Dynamic Assess behaviors. - Expanded useEditor hook to manage Dynamic Assess state, including refresh polling and validation for skill and difficulty target. - Added tests for Dynamic Assess content view gating, refresh body polling, and edge cases in generation. --- src/ContentEditor.test.tsx | 116 ++++++- src/ContentEditor.tsx | 40 ++- src/components/EditorPreview.test.tsx | 70 ++++- src/components/EditorPreview.tsx | 29 +- src/components/Header.test.tsx | 40 +++ src/components/Header.tsx | 70 +++-- src/components/MetadataDrawer.test.tsx | 356 +++++++++++++++++++++- src/components/MetadataDrawer.tsx | 290 ++++++++++++++++-- src/constants.ts | 6 + src/difficultyTarget.ts | 25 ++ src/dynamicAssessDraw.test.ts | 88 ++++++ src/dynamicAssessDraw.ts | 121 ++++++++ src/editor.scss | 113 +++++++ src/i18n/i18n.test.ts | 21 ++ src/i18n/translations.ar.ts | 33 ++ src/i18n/translations.en.ts | 33 ++ src/i18n/translations.fr.ts | 33 ++ src/i18n/translations.hi.ts | 33 ++ src/i18n/translations.pt.ts | 33 ++ src/i18n/translations.ta.ts | 33 ++ src/icons.tsx | 9 + src/poolPlan.test.ts | 32 ++ src/poolPlan.ts | 78 +++++ src/services/ContentEditorService.test.ts | 125 ++++++++ src/services/ContentEditorService.ts | 75 ++++- src/taxonomy.test.ts | 17 +- src/taxonomy.ts | 6 + src/test/mockEd.ts | 3 + src/types.ts | 3 + src/useEditor.test.ts | 314 +++++++++++++++++++ src/useEditor.ts | 149 ++++++++- 31 files changed, 2316 insertions(+), 78 deletions(-) create mode 100644 src/difficultyTarget.ts create mode 100644 src/dynamicAssessDraw.test.ts create mode 100644 src/dynamicAssessDraw.ts create mode 100644 src/poolPlan.test.ts create mode 100644 src/poolPlan.ts diff --git a/src/ContentEditor.test.tsx b/src/ContentEditor.test.tsx index cb9e165..023a7c6 100644 --- a/src/ContentEditor.test.tsx +++ b/src/ContentEditor.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { describe, it, expect, vi } from 'vitest'; import ContentEditor from './ContentEditor'; import type { ContentEditorService } from './services/ContentEditorService'; @@ -11,6 +11,9 @@ function svc(over: Record = {}) { readContent: vi.fn().mockResolvedValue(mockContent), createLock: vi.fn().mockResolvedValue({}), retireLock: vi.fn().mockResolvedValue(undefined), + readFormFields: vi.fn().mockResolvedValue([]), + readFramework: vi.fn().mockResolvedValue([]), + searchFrameworks: vi.fn().mockResolvedValue([]), getBase: () => ({ baseUrl: '', apiSlug: '/action', headers: {}, fetchImpl: fetch }), getEndpoints: () => ({}), ...over, @@ -44,3 +47,114 @@ describe(' — existing content', () => { expect(await screen.findByText('Failed to load content.')).toBeInTheDocument(); }); }); + +describe(' — Dynamic Assess empty state', () => { + it('shows a placeholder instead of the legacy player when no body has been generated yet (positive)', async () => { + const service = svc({ + readContent: vi.fn().mockResolvedValue({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + totalQuestions: 0, + }), + }); + render(); + expect(await screen.findByText('No questions generated yet')).toBeInTheDocument(); + expect(screen.getByText(/save to generate the questions/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Edit details' })).toBeInTheDocument(); + expect(screen.queryByText('PDF')).not.toBeInTheDocument(); + }); + + it('shows the normal preview once the job has written questions, even for a never-published Draft (negative)', async () => { + const service = svc({ + readContent: vi.fn().mockResolvedValue({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + status: 'Draft', + pkgVersion: 0, + totalQuestions: 3, + }), + }); + render(); + await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0)); + expect(screen.queryByText('No questions generated yet')).not.toBeInTheDocument(); + }); + + it('does not point a reviewer at a Generate button they do not have (positive)', async () => { + const service = svc({ + readContent: vi.fn().mockResolvedValue({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + status: 'Review', + totalQuestions: 0, + }), + }); + const reviewerContext = { ...mockContext, user: { ...mockContext.user!, roles: ['CONTENT_REVIEWER'] } }; + render(); + expect(await screen.findByText('No questions have been generated for this content yet.')).toBeInTheDocument(); + expect(screen.queryByText(/save to generate the questions/)).not.toBeInTheDocument(); + }); +}); + +describe(' — Dynamic Assess generating overlay', () => { + const staleBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 2, M: 0, D: 0 } } }) } } }] }, + }); + const daContent = (over: Record = {}) => ({ + ...mockContent, + primaryCategory: 'Dynamic Course Assessment', + totalQuestions: 3, + lastUpdatedOn: 't0', + skill: ['Physics'], + difficultyTarget: '{"E":1,"M":1,"D":1}', + body: staleBody, + ...over, + }); + + it('shows a blocking loader while questions generate and removes it once the job writes (positive)', async () => { + let written = false; + const service = svc({ + readContent: vi.fn().mockImplementation(async () => daContent(written ? { lastUpdatedOn: 't1' } : {})), + refreshContentBody: vi.fn().mockResolvedValue({}), + }); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Regenerate/ })); + expect(await screen.findByRole('status')).toHaveTextContent('Generating questions'); + // The settings banner stays hidden behind the loader while generating. + expect(screen.queryByText('Settings changed since the questions were generated')).not.toBeInTheDocument(); + written = true; + await waitFor(() => expect(screen.queryByText('Generating questions')).not.toBeInTheDocument(), { timeout: 8000 }); + expect(await screen.findByText('Questions generated')).toBeInTheDocument(); + }, 10000); + + it('never shows the loader or a Generate button for ordinary content (negative)', async () => { + render(); + await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0)); + expect(screen.queryByRole('button', { name: /Regenerate/ })).not.toBeInTheDocument(); + expect(screen.queryByText('Generating questions')).not.toBeInTheDocument(); + }); +}); + +describe(' — Dynamic Assess stale settings banner', () => { + const generatedBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 3, M: 3, D: 3 } } }) } } }] }, + }); + const daContent = (over: Record = {}) => ({ + ...mockContent, primaryCategory: 'Dynamic Course Assessment', totalQuestions: 9, + skill: ['Physics'], difficultyTarget: '{"E":3,"M":3,"D":3}', body: generatedBody, ...over, + }); + + it('warns the creator and disables Send for Review when settings changed after generation (positive)', async () => { + const service = svc({ readContent: vi.fn().mockResolvedValue(daContent({ difficultyTarget: '{"E":3,"M":2,"D":3}' })) }); + render(); + expect(await screen.findByRole('alert')).toHaveTextContent('Settings changed since the questions were generated'); + expect(screen.getByText(/Click Regenerate to update them/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Send for review/i })).toBeDisabled(); + }); + + it('shows no banner when the settings match the generated questions (negative)', async () => { + const service = svc({ readContent: vi.fn().mockResolvedValue(daContent()) }); + render(); + await waitFor(() => expect(screen.getAllByText('Sample content').length).toBeGreaterThan(0)); + expect(screen.queryByText('Settings changed since the questions were generated')).not.toBeInTheDocument(); + }); +}); diff --git a/src/ContentEditor.tsx b/src/ContentEditor.tsx index a55a9ec..bc79e02 100644 --- a/src/ContentEditor.tsx +++ b/src/ContentEditor.tsx @@ -14,7 +14,7 @@ import TranscriptsDrawer from './components/TranscriptsDrawer'; import AssetPickerModal from './components/AssetPickerModal'; import Toast from './components/Toast'; import { t } from './i18n/i18n'; -import { CheckIcon } from './icons'; +import { CheckIcon, InfoIcon, RefreshIcon } from './icons'; export type ContentEditorProps = UseEditorOptions; @@ -35,7 +35,32 @@ const ContentEditor: React.FC = (props) => { {(ed.view === 'upload' || ed.view === 'uploading') && (
)} - {ed.view === 'player' && } + {ed.view === 'player' && ed.isDynamicAssess && !ed.hasGeneratedBody && ( +
+ +

{t(ed.lang, 'DYNAMIC_ASSESS_EMPTY_TITLE')}

+ {/* Only an editor can save details (which generates); reviewers/readers just see it's empty. */} +

{t(ed.lang, ed.mode === 'edit' ? 'DYNAMIC_ASSESS_EMPTY_SUB' : 'DYNAMIC_ASSESS_EMPTY_SUB_READONLY')}

+ {ed.mode === 'edit' && ( + + )} +
+ )} + {/* Only when the saved settings don't match the questions and nothing is regenerating, e.g. a failed or older generation. */} + {ed.view === 'player' && ed.dynamicAssessStale && !ed.dynamicAssessRefreshing && ( +
+ +
+

{t(ed.lang, 'DYNAMIC_ASSESS_STALE_TITLE')}

+

{t(ed.lang, ed.mode === 'edit' ? 'DYNAMIC_ASSESS_STALE_SUB' : 'DYNAMIC_ASSESS_STALE_SUB_READONLY')}

+
+
+ )} + {ed.view === 'player' && !(ed.isDynamicAssess && !ed.hasGeneratedBody) && ( + + )}
ed.setDrawer(null)} /> @@ -67,6 +92,17 @@ const ContentEditor: React.FC = (props) => {
)} + {/* Blocks editing while the job writes the quiz, so a stale save can't race it. */} + {ed.isDynamicAssess && ed.dynamicAssessRefreshing && ( +
+
+
+

{t(ed.lang, 'DYNAMIC_ASSESS_GENERATING_TITLE')}

+

{t(ed.lang, 'DYNAMIC_ASSESS_GENERATING_SUB')}

+
+
+ )} + {/* Upload success overlay */} {ed.uploadSuccess && (
diff --git a/src/components/EditorPreview.test.tsx b/src/components/EditorPreview.test.tsx index 25e27c2..c634090 100644 --- a/src/components/EditorPreview.test.tsx +++ b/src/components/EditorPreview.test.tsx @@ -1,6 +1,6 @@ -import { render, screen } from '@testing-library/react'; -import { describe, it, expect } from 'vitest'; -import EditorPreview from './EditorPreview'; +import { render, screen, fireEvent } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import EditorPreview, { rendererData } from './EditorPreview'; import { makeEd, mockContext, mockContent } from '../test/mockEd'; describe('', () => { @@ -93,4 +93,68 @@ describe('', () => { const secondIframe = container.querySelector('iframe'); expect(secondIframe).not.toBe(firstIframe); }); + + it('hands the ECML body to the renderer as data, so a generated Dynamic Assess lesson can play (positive)', () => { + const body = '{"theme":{"id":"theme","stage":[]}}'; + const ed = makeEd({ isDynamicAssess: true, content: { ...mockContent, mimeType: 'application/vnd.ekstep.ecml-archive', artifactUrl: undefined, body } }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledWith(expect.objectContaining({ data: { theme: { id: 'theme', stage: [] } } })); + }); + + it('gives the renderer only the draw in metadata.body too, never the full pool (positive)', () => { + const ids = ['a1', 'a2', 'a3']; + const body = JSON.stringify({ theme: { stage: [{ 'org.ekstep.questionset': [{ + config: { __cdata: JSON.stringify({ dynamic_assess: { target: { E: 1, M: 0, D: 0 }, levels: Object.fromEntries(ids.map((id) => [id, 'EASY'])) } }) }, + data: { __cdata: JSON.stringify(ids.map((id) => ({ identifier: id }))) }, + 'org.ekstep.question': ids.map((id) => ({ id })), + }] }] } }); + const ed = makeEd({ isDynamicAssess: true, content: { ...mockContent, mimeType: 'application/vnd.ekstep.ecml-archive', artifactUrl: undefined, body } }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + const cfg = initializePreview.mock.calls[0]![0] as { metadata: { body: string }; data: unknown }; + const quiz = JSON.parse(cfg.metadata.body).theme.stage[0]['org.ekstep.questionset'][0]; + expect(quiz['org.ekstep.question']).toHaveLength(1); + expect(JSON.parse(cfg.metadata.body)).toEqual(cfg.data); + }); + + it('passes ordinary content metadata through untouched (negative)', () => { + const ed = makeEd({ isDynamicAssess: false, content: mockContent }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledWith(expect.objectContaining({ metadata: mockContent, data: {} })); + }); + + it('keeps passing empty data for regular ECML, so its preview loads exactly as before (negative)', () => { + const body = '{"theme":{"id":"theme","stage":[]}}'; + const ed = makeEd({ isDynamicAssess: false, content: { ...mockContent, mimeType: 'application/vnd.ekstep.ecml-archive', body } }); + const { container } = render(); + const iframe = container.querySelector('iframe')!; + const initializePreview = vi.fn(); + (iframe.contentWindow as unknown as { initializePreview: typeof initializePreview }).initializePreview = initializePreview; + fireEvent.load(iframe); + expect(initializePreview).toHaveBeenCalledWith(expect.objectContaining({ data: {} })); + }); +}); + +describe('rendererData', () => { + it('parses a JSON-string body and passes an object body through (positive)', () => { + expect(rendererData('{"theme":{}}')).toEqual({ theme: {} }); + expect(rendererData({ theme: {} })).toEqual({ theme: {} }); + }); + + it('falls back to {} with no body, and keeps a non-JSON (XML) body as-is (negative)', () => { + expect(rendererData(undefined)).toEqual({}); + expect(rendererData('')).toEqual({}); + expect(rendererData('')).toBe(''); + }); }); diff --git a/src/components/EditorPreview.tsx b/src/components/EditorPreview.tsx index 5e48f3e..803c98b 100644 --- a/src/components/EditorPreview.tsx +++ b/src/components/EditorPreview.tsx @@ -4,6 +4,7 @@ import type { ContentData, EditorContext, RawTranscript } from '../types'; import { getMimeTypeLabel, t } from '../i18n/i18n'; import { FileIcon } from '../icons'; import { isVideoMimeType } from '../constants'; +import { ecmlBodyForUser } from '../dynamicAssessDraw'; interface PlayerTranscript { language: string; @@ -32,10 +33,19 @@ function mapRawTranscripts(raw: RawTranscript[]): PlayerTranscript[] { })); } +/** The ECML renderer reads the lesson from `data` (as the portal's EcmlPlayerService passes metadata.body); the API returns the body JSON-stringified. */ +export function rendererData(body: unknown): unknown { + if (body && typeof body === 'object') return body; + if (typeof body === 'string' && body.trim()) { + try { return JSON.parse(body); } catch { return body; } + } + return {}; +} + /** Preview via the legacy ekstep content renderer (all mimeTypes through its coreplugins), loaded in an iframe and driven via its global `initializePreview()`. */ const RendererPreview: React.FC<{ - content: ContentData; context: EditorContext; previewUrl: string; previewConfig: Record; -}> = ({ content, context, previewUrl, previewConfig }) => { + content: ContentData; context: EditorContext; previewUrl: string; previewConfig: Record; isDynamicAssess?: boolean; +}> = ({ content, context, previewUrl, previewConfig, isDynamicAssess = false }) => { const iframeRef = useRef(null); const src = `${previewUrl}${previewUrl.includes('?') ? '&' : '?'}webview=true`; @@ -44,6 +54,13 @@ const RendererPreview: React.FC<{ | (Window & { initializePreview?: (cfg: unknown) => void }) | null; if (!win || typeof win.initializePreview !== 'function') return; + const rawBody = (content as Record).body; + // Only Dynamic Assess renders from its generated body (the user's own draw, never the whole pool); other content keeps the renderer's own loading. + const data = isDynamicAssess ? ecmlBodyForUser(rendererData(rawBody), content.identifier, context.user?.id) : {}; + // metadata.body carries the same draw, like the portal's ecmlForLearner, so the full pool never reaches the renderer. + const metadata = isDynamicAssess && rawBody + ? { ...content, body: typeof rawBody === 'string' && data && typeof data === 'object' ? JSON.stringify(data) : data } + : content; win.initializePreview({ context: { mode: 'edit', @@ -57,8 +74,8 @@ const RendererPreview: React.FC<{ partner: [], }, config: previewConfig, - metadata: content, - data: {}, + metadata, + data, }); }; @@ -104,8 +121,10 @@ const EditorPreview: React.FC<{ ed: EditorController; context: EditorContext }>
) : ( ', () => { expect(screen.queryByRole('button', { name: 'View transcript' })).not.toBeInTheDocument(); }); }); + +describe('
— Regenerate (Dynamic Assess)', () => { + it('sits next to Save for the creator once questions exist and re-rolls on click (positive)', () => { + const refreshBody = vi.fn(); + const ed = makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: true, hasGeneratedBody: true, refreshBody }); + render(
); + fireEvent.click(screen.getByRole('button', { name: /Regenerate/ })); + expect(refreshBody).toHaveBeenCalled(); + }); + + it('explains a disabled Send for review / Publish with a hover hint (positive)', () => { + const creator = makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: true, hasGeneratedBody: false }); + const { container, unmount } = render(
); + expect(screen.getByRole('button', { name: /Send for review/i })).toBeDisabled(); + expect(container.querySelector('.ce-disabled-hint')).toHaveAttribute('data-tooltip', 'Generate questions before sending for review'); + unmount(); + const reviewer = makeEd({ view: 'player', content: mockContent, mode: 'review', isDynamicAssess: true, hasGeneratedBody: true, dynamicAssessStale: true }); + const { container: c2 } = render(
); + expect(screen.getByRole('button', { name: /Publish/ })).toBeDisabled(); + expect(c2.querySelector('.ce-disabled-hint')).toHaveAttribute('data-tooltip', 'Settings changed — generate questions again first'); + }); + + it('adds no hint wrapper for ordinary content (negative)', () => { + const { container } = render(
); + expect(container.querySelector('.ce-disabled-hint')).toBeNull(); + }); + + it('is hidden for reviewers, before any questions exist, and for ordinary content (negative)', () => { + const cases = [ + makeEd({ view: 'player', content: mockContent, mode: 'review', isDynamicAssess: true, hasGeneratedBody: true }), + makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: true, hasGeneratedBody: false }), + makeEd({ view: 'player', content: mockContent, mode: 'edit', isDynamicAssess: false, hasGeneratedBody: true }), + ]; + for (const ed of cases) { + const { unmount } = render(
); + expect(screen.queryByRole('button', { name: /Regenerate/ })).not.toBeInTheDocument(); + unmount(); + } + }); +}); diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 85a1f40..a0a9f25 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -2,18 +2,29 @@ import React from 'react'; import type { EditorController } from '../useEditor'; import { t } from '../i18n/i18n'; import { - ImageIcon, PencilIcon, SaveIcon, CloseIcon, SendIcon, UserPlusIcon, CheckIcon, CommentIcon, CaptionsIcon, + ImageIcon, PencilIcon, SaveIcon, CloseIcon, SendIcon, UserPlusIcon, CheckIcon, CommentIcon, CaptionsIcon, RefreshIcon, } from '../icons'; import { STATUS } from '../constants'; +/** Hover hint for a disabled button: a disabled button is faded and gets no hover tooltip itself, so the hint sits on a wrapper. */ +const DisabledHint: React.FC<{ hint?: string; children: React.ReactNode }> = ({ hint, children }) => ( + hint ? {children} : <>{children} +); + const Header: React.FC<{ ed: EditorController }> = ({ ed }) => { - const { content, lang, mode, setDrawer, saveDraft, close, busy, busyAction, setReviewErrors, setReviewSubmitMode, headerLogo, hasReviewComments, hasTranscripts } = ed; + const { + content, lang, mode, setDrawer, saveDraft, close, busy, busyAction, setReviewErrors, setReviewSubmitMode, + headerLogo, hasReviewComments, hasTranscripts, isDynamicAssess, hasGeneratedBody, dynamicAssessStale, + dynamicAssessRefreshing, refreshBody, + } = ed; const savingDraft = busyAction === 'save-draft'; const hasContent = !!content?.identifier && ed.view === 'player'; const isDraft = (content?.status ?? STATUS.DRAFT) === STATUS.DRAFT; const title = content?.name || t(lang, 'UNTITLED'); const canEdit = mode === 'edit'; const isReviewer = mode === 'review'; + const dynamicAssessBlocked = isDynamicAssess && (!hasGeneratedBody || dynamicAssessStale); + const dynamicAssessBlockedTip = dynamicAssessStale ? 'DYNAMIC_ASSESS_STALE_TIP' : 'DYNAMIC_ASSESS_GENERATE_FIRST'; return (
@@ -99,7 +110,20 @@ const Header: React.FC<{ ed: EditorController }> = ({ ed }) => { {savingDraft ? : } )} - + + {/* Dynamic Assess re-roll with unchanged settings; a settings change already regenerates on Save. */} + {canEdit && !isReviewer && isDynamicAssess && hasGeneratedBody && ( + + )} +
{isReviewer ? ( @@ -107,27 +131,31 @@ const Header: React.FC<{ ed: EditorController }> = ({ ed }) => { - + + + ) : ( canEdit && ( - + + + ) )} diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 5cd2eed..7fc577a 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -12,12 +12,12 @@ describe('', () => { expect(screen.getByText('Description')).toBeInTheDocument(); }); - it('saves metadata with the trimmed name (positive)', () => { + it('saves metadata with the trimmed name (positive)', async () => { const saveMetadata = vi.fn(); const ed = makeEd({ drawer: 'metadata', content: mockContent, saveMetadata }); render(); - fireEvent.click(screen.getByRole('button', { name: /Save changes/ })); - expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' })); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' }))); }); it('blocks save and toasts when the title is empty (negative)', () => { @@ -25,7 +25,7 @@ describe('', () => { const showToast = vi.fn(); const ed = makeEd({ drawer: 'metadata', content: { ...mockContent, name: '' }, saveMetadata, showToast }); render(); - fireEvent.click(screen.getByRole('button', { name: /Save changes/ })); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); expect(showToast).toHaveBeenCalledWith('Title is required.', 'error'); expect(saveMetadata).not.toHaveBeenCalled(); }); @@ -53,11 +53,355 @@ describe('', () => { expect(screen.getByRole('option', { name: 'Geometry' })).toBeInTheDocument(); }); - it('routes to save-and-submit in review-submit mode', () => { + it('routes to save-and-submit in review-submit mode', async () => { const saveMetadataAndSubmit = vi.fn(); const ed = makeEd({ drawer: 'metadata', content: mockContent, reviewSubmitMode: true, saveMetadataAndSubmit }); render(); fireEvent.click(screen.getByRole('button', { name: /Save & Submit/ })); - expect(saveMetadataAndSubmit).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' })); + await waitFor(() => expect(saveMetadataAndSubmit).toHaveBeenCalledWith(expect.objectContaining({ name: 'Sample content' }))); + }); + + it('keeps a skill field on a non-Dynamic form as an ordinary field (negative)', async () => { + const service = mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'text', label: 'Skill', required: false, visible: true, editable: true }, + ]), + }); + render(); + expect(await screen.findByText('Skill')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Select Skill/ })).toBeNull(); + expect(screen.queryByText('Framework')).toBeNull(); + }); + + describe('difficultyTarget (Dynamic Assess)', () => { + const service = () => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + }); + + it('renders three E/M/D number inputs and saves the entered counts as the API-expected JSON string', async () => { + const saveMetadata = vi.fn(); + // Seeded in the API's real wire format: a JSON string, not an object. + const ed = makeEd({ + drawer: 'metadata', service: service(), saveMetadata, + content: { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1,"M":0,"D":0}' }, + }); + render(); + expect(await screen.findByText('Difficulty Target')).toBeInTheDocument(); + const easyInput = screen.getByDisplayValue('1'); + fireEvent.change(easyInput, { target: { value: '3' } }); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith( + expect.objectContaining({ difficultyTarget: '{"E":3,"M":0,"D":0}' }), + )); + }); + + it('gives each count input an accessible name inside a labelled group (positive)', async () => { + const ed = makeEd({ + drawer: 'metadata', service: service(), + content: { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1,"M":2,"D":3}' }, + }); + render(); + expect(await screen.findByRole('group', { name: /Difficulty Target/ })).toBeInTheDocument(); + expect(screen.getByRole('spinbutton', { name: 'Easy' })).toHaveValue(1); + expect(screen.getByRole('spinbutton', { name: 'Medium' })).toHaveValue(2); + expect(screen.getByRole('spinbutton', { name: 'Difficult' })).toHaveValue(3); + }); + + it('blocks submit-for-review when every bucket is zero (negative)', async () => { + const saveMetadataAndSubmit = vi.fn(); + const setReviewErrors = vi.fn(); + const ed = makeEd({ + drawer: 'metadata', service: service(), reviewSubmitMode: true, saveMetadataAndSubmit, setReviewErrors, + content: { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: { E: 0, M: 0, D: 0 } }, + }); + render(); + await screen.findByText('Difficulty Target'); + fireEvent.click(screen.getByRole('button', { name: /Save & Submit/ })); + expect(setReviewErrors).toHaveBeenCalledWith(['Difficulty Target']); + expect(saveMetadataAndSubmit).not.toHaveBeenCalled(); + }); + }); + + describe('pool sufficiency check (Dynamic Assess)', () => { + const serviceWithSkill = (over: Record = {}) => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'skill', name: 'Skill', index: 1, terms: [{ code: 'physics', name: 'physics' }] }, + ]), + ...over, + }); + const baseContent = { + ...mockContent, primaryCategory: 'Dynamic Course Assessment', + difficultyTarget: '{"E":2,"M":0,"D":0}', + }; + + /** Selects "physics" through the UI (baseContent has no saved skill). */ + async function selectPhysicsSkill() { + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + fireEvent.click(await screen.findByText('physics')); + } + + it('blocks save and shows the per-level shortfall when the pool is insufficient (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const service = serviceWithSkill({ + searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 0, M: 0, D: 0 } }), + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith( + expect.stringContaining('Easy: requested 2 needs 6, available 0'), 'error', + )); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('allows save when the pool covers the requested counts (negative)', async () => { + const saveMetadata = vi.fn(); + const service = serviceWithSkill({ + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + }); + + it('blocks save when the pool has the requested count but not requested x multiplier (negative)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const service = serviceWithSkill({ + // 5 Easy items exist but only floor(5/3)=1 can be drawn per the job's multiplier rule. + searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 5, M: 0, D: 0 } }), + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith( + expect.stringContaining('Easy: requested 2 needs 6, available 3'), 'error', + )); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('blocks save, translated, when one skill has fewer than minCriteria x multiplier Live questions (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const service = serviceWithSkill({ + searchSkillPoolCounts: vi.fn().mockResolvedValue({ physics: 5 }), + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith( + 'Each skill needs at least 6 Live questions. Too few for: physics', 'error', + )); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('shows and keeps the saved skill when the form loads after the drawer opens (positive)', async () => { + const saveMetadata = vi.fn(); + const service = serviceWithSkill({ + }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content: { ...baseContent, skill: ['physics'] } }); + render(); + await screen.findByText('Difficulty Target'); + expect(await screen.findByText('physics')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ skill: ['physics'] }))); + }); + + it('blocks a skill the job could not give its own minimum at the chosen levels, which would otherwise stay stale forever (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + // All of physics' questions are Difficult, but only Easy is requested. + const service = serviceWithSkill({ searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 0, M: 0, D: 30 } }) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalled()); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('blocks a target too small for the number of skills, like the job does (positive)', async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + const content = { ...baseContent, difficultyTarget: '{"E":1,"M":0,"D":0}' }; + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: serviceWithSkill(), saveMetadata, showToast, content }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith(expect.stringContaining('must add up to at least 2'), 'error')); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('saves only once when Save & Generate is clicked twice during the pool check (negative)', async () => { + const saveMetadata = vi.fn(); + let release: () => void = () => {}; + const slow = vi.fn(() => new Promise((resolve) => { release = () => resolve({ physics: { E: 9, M: 9, D: 9 } }); })); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: serviceWithSkill({ searchAssessmentItemBucketCounts: slow }), saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + const button = screen.getByRole('button', { name: /Save & Generate/ }); + fireEvent.click(button); + fireEvent.click(button); + release(); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledTimes(1)); + expect(slow).toHaveBeenCalledTimes(1); + }); + + it('disables Save while questions are generating, so a save cannot skip its own generation (positive)', async () => { + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, dynamicAssessRefreshing: true, drawer: 'metadata', service: serviceWithSkill(), saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + const button = screen.getByRole('button', { name: /Save/ }); + expect(button).toBeDisabled(); + fireEvent.click(button); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('refuses Save & Submit with changed settings instead of submitting stale questions (positive)', async () => { + const saveMetadataAndSubmit = vi.fn(); + const showToast = vi.fn(); + const searchAssessmentItemBucketCounts = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', reviewSubmitMode: true, service: serviceWithSkill({ searchAssessmentItemBucketCounts }), saveMetadataAndSubmit, showToast, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith(expect.stringContaining('use Save & Generate'), 'error')); + expect(saveMetadataAndSubmit).not.toHaveBeenCalled(); + expect(searchAssessmentItemBucketCounts).not.toHaveBeenCalled(); + }); + + it('labels the button Save & Generate only when this save will generate (positive)', async () => { + const service = serviceWithSkill(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + expect(screen.getByRole('button', { name: /Save changes/ })).toBeInTheDocument(); + await selectPhysicsSkill(); + expect(await screen.findByRole('button', { name: /Save & Generate/ })).toBeInTheDocument(); + }); + + it('skips the pool searches for a save that will not generate (negative)', async () => { + const searchAssessmentItemBucketCounts = vi.fn(); + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: serviceWithSkill({ searchAssessmentItemBucketCounts }), saveMetadata, content: baseContent }); + render(); + await screen.findByText('Difficulty Target'); + fireEvent.click(screen.getByRole('button', { name: /Save changes/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + expect(searchAssessmentItemBucketCounts).not.toHaveBeenCalled(); + }); + }); + + describe('skill binds to the framework\'s deepest category (Dynamic Assess)', () => { + // Deepest category is 'topic' and there is no category coded 'skill', like a non-USF framework. + const nonUsfService = (over: Record = {}) => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }, { code: 't2', name: 'Geometry' }] }, + { code: 'subject', name: 'Subject', index: 1, terms: [{ code: 's1', name: 'Maths' }] }, + ]), + ...over, + }); + const content = { ...mockContent, primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":2,"M":0,"D":0}' }; + + it('offers the deepest category\'s terms and checks the pool on that category (positive)', async () => { + const saveMetadata = vi.fn(); + const pool = vi.fn().mockResolvedValue({ Algebra: { E: 9, M: 9, D: 9 } }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService({ searchAssessmentItemBucketCounts: pool }), saveMetadata, content }); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + expect(await screen.findByText('Algebra')).toBeInTheDocument(); + expect(screen.getByText('Geometry')).toBeInTheDocument(); + expect(screen.queryByText('Maths')).not.toBeInTheDocument(); + fireEvent.click(screen.getByText('Algebra')); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ skill: ['Algebra'] }))); + expect(pool).toHaveBeenCalledWith(['Algebra'], expect.anything(), 'topic'); + }); + + it('lets the author switch framework, reloading skill options from the new framework\'s deepest category (positive)', async () => { + const saveMetadata = vi.fn(); + const readFramework = vi.fn(async (fw: string) => (fw === 'USF' + ? [{ code: 'skill', name: 'Skill', index: 3, terms: [{ code: 'ph', name: 'Physics' }] }] + : [{ code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }] }])); + const service = nonUsfService({ + readFramework, + searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }, { identifier: 'USF', name: 'Universal Skills' }]), + }); + const ed = makeEd({ drawer: 'metadata', service, saveMetadata, isDynamicAssess: true, content: { ...content, framework: 'BMGS' } }); + render(); + + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(picker.value).toBe('BMGS')); + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + fireEvent.click(await screen.findByText('Algebra')); + fireEvent.mouseDown(document.body); // close the skill dropdown, as clicking elsewhere does + + fireEvent.change(picker, { target: { value: 'USF' } }); + await waitFor(() => expect(readFramework).toHaveBeenCalledWith('USF')); + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); // previous pick was cleared + fireEvent.click(await screen.findByText('Physics')); + expect(screen.queryByText('Algebra')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ framework: 'USF', skill: ['Physics'] }))); + }); + + it('reloads the categories when the author picks the placeholder and then the same framework again (positive)', async () => { + const readFramework = vi.fn().mockResolvedValue([{ code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }] }]); + const service = nonUsfService({ readFramework, searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }]) }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(picker.value).toBe('BMGS')); + const callsBefore = readFramework.mock.calls.length; + fireEvent.change(picker, { target: { value: '' } }); + fireEvent.change(picker, { target: { value: 'BMGS' } }); + await waitFor(() => expect(readFramework.mock.calls.length).toBeGreaterThan(callsBefore)); + fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + expect(await screen.findByText('Algebra')).toBeInTheDocument(); + }); + + it('keeps skill disabled until a framework is chosen (negative)', async () => { + const service = nonUsfService({ readFramework: vi.fn().mockResolvedValue([]) }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, framework: '', content: { ...content, framework: undefined } }); + render(); + const skill = await screen.findByRole('button', { name: /Select a framework first/ }); + expect(skill).toBeDisabled(); + }); + + it('does not fall back to a free-text box when no category is literally named skill (negative)', async () => { + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), content }); + render(); + // Before this change the field rendered as a plain text input, with no "Select Skill" dropdown. + expect(await screen.findByRole('button', { name: /Select Skill/ })).toBeInTheDocument(); + }); }); }); diff --git a/src/components/MetadataDrawer.tsx b/src/components/MetadataDrawer.tsx index 34453f5..2a63488 100644 --- a/src/components/MetadataDrawer.tsx +++ b/src/components/MetadataDrawer.tsx @@ -1,23 +1,76 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; +import React, { useEffect, useId, useMemo, useRef, useState } from 'react'; import Drawer from './Drawer'; import type { EditorController } from '../useEditor'; import type { FormField, FrameworkCategory } from '../types'; -import { t } from '../i18n/i18n'; -import { cascadedOptions } from '../taxonomy'; +import { t, tf } from '../i18n/i18n'; +import { cascadedOptions, deepestCategoryCode } from '../taxonomy'; import { PencilIcon, ChevronDown, ImageIcon, CheckIcon } from '../icons'; +import { type DifficultyTarget, toDifficultyTarget, serializeDifficultyTarget } from '../difficultyTarget'; +import { needsGeneration } from '../dynamicAssessDraw'; +import { planPool } from '../poolPlan'; +import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from '../constants'; /** * Multi-value field? Driven by the form definition, not a hardcoded list — a field * is an array if the form marks it multiselect (or dataType 'list'), so any custom * taxonomy category the framework returns is handled dynamically. */ -function isMultiField(f: FormField): boolean { +function isMultiField(f: FormField, dynamicAssess = false): boolean { + if (dynamicAssess && isSkillField(f)) return true; const it = (f.inputType ?? '').toLowerCase(); if (it.includes('multi')) return true; const dt = (f.dataType ?? '').toLowerCase(); return dt === 'list'; } +/** difficultyTarget is matched by code: the form definition has no inputType for three named number fields. */ +function isDifficultyTargetField(f: FormField): boolean { + return f.code?.toLowerCase() === 'difficultytarget'; +} + +/** Dynamic Assess skill is always a list bound to the framework's deepest category, matching question-set editor-v2's isSkillField. */ +function isSkillField(f: FormField): boolean { + return f.code?.toLowerCase() === 'skill'; +} + + +const DifficultyTargetInput: React.FC<{ + lang: string; label: string; required?: boolean; disabled?: boolean; + value: DifficultyTarget; onChange: (v: DifficultyTarget) => void; +}> = ({ lang, label, required, disabled, value, onChange }) => { + const rows: Array<{ key: keyof DifficultyTarget; text: string }> = [ + { key: 'E', text: t(lang, 'DIFFICULTY_EASY') }, + { key: 'M', text: t(lang, 'DIFFICULTY_MEDIUM') }, + { key: 'D', text: t(lang, 'DIFFICULTY_DIFFICULT') }, + ]; + const labelId = useId(); + return ( +
+ +
+ {rows.map(({ key, text }) => ( +
+ + { + const n = e.target.value === '' ? 0 : Math.max(0, Math.floor(Number(e.target.value)) || 0); + onChange({ ...value, [key]: n }); + }} + /> +
+ ))} +
+
+ ); +}; + /** Fallback field set when form/read returns nothing (keeps the drawer usable). */ const FALLBACK_FIELDS: FormField[] = [ { code: 'appicon', inputType: 'file', label: 'Thumbnail', index: 1, visible: true, editable: true }, @@ -110,6 +163,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const [values, setValues] = useState>({}); /* Multi-value taxonomy fields (medium, gradeLevel, subject) — real arrays. */ const [multiVals, setMultiVals] = useState>({}); + /* Dynamic Assess difficultyTarget fields — object-shaped {E,M,D}, keyed by code. */ + const [diffTargets, setDiffTargets] = useState>({}); const [appIcon, setAppIcon] = useState(); const [categories, setCategories] = useState([]); const [formFields, setFormFields] = useState([]); @@ -117,14 +172,32 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const loadedFormKey = useRef(null); /** Content id already seeded this open-session — prevents an async form load re-seeding over edits. */ const seededRef = useRef(null); + /** Separate seed guard for difficultyTarget: it only appears once the async form loads, after seededRef has already fired. */ + const diffSeededRef = useRef(null); + /* Dynamic Assess: author-chosen framework; skill options come from its deepest category. */ + const [selectedFw, setSelectedFw] = useState(''); + // True while the pool searches run before a generating save, so a second click can't save twice. + const [checking, setChecking] = useState(false); + const [fwOptions, setFwOptions] = useState>([]); + const contentChannel = (content as Record | null)?.channel as string | undefined; + + useEffect(() => { + if (open) setSelectedFw(String(content?.framework || framework || '')); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, content?.identifier]); + + useEffect(() => { + if (!open || !ed.isDynamicAssess) return; + service.searchFrameworks(contentChannel ?? ed.context.channel).then(setFwOptions).catch(() => setFwOptions([])); + }, [open, ed.isDynamicAssess, service, contentChannel, ed.context.channel]); /* Framework categories for taxonomy cascade. */ useEffect(() => { - const fw = content?.framework || framework; + const fw = selectedFw || content?.framework || framework; if (!open || !fw || loadedFw.current === fw) return; loadedFw.current = fw; service.readFramework(fw).then(setCategories).catch(() => setCategories([])); - }, [open, content, framework, service]); + }, [open, content, framework, service, selectedFw]); /* Form/read field definitions — save form for Edit Details, review form for * Submit-for-review. Keyed on subtype+action so switching mode refetches even @@ -157,6 +230,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { () => [...categories].sort((a, b) => (a.index ?? 0) - (b.index ?? 0)).map((c) => c.code), [categories], ); + const skillCategoryCode = useMemo(() => deepestCategoryCode(categories), [categories]); const setVal = (code: string, v: string) => setValues((s) => ({ ...s, [code]: v })); const setMulti = (code: string, v: string[]) => setMultiVals((s) => ({ ...s, [code]: v })); @@ -177,8 +251,9 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { for (const f of fields) { if (f.code === 'name' || f.code === 'description') continue; if (f.code === 'appicon' || f.code === 'appIcon') continue; + if (isDifficultyTargetField(f)) continue; // seeded separately below — see diffSeededRef const cv = (content as Record)[f.code]; - if (isMultiField(f)) { + if (isMultiField(f, ed.isDynamicAssess)) { multi[f.code] = Array.isArray(cv) ? cv.map(String) : cv != null && cv !== '' ? [String(cv)] : []; } else { vals[f.code] = cv != null ? String(cv) : ''; @@ -189,6 +264,27 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setAppIcon(content.appIcon); }, [open, content, fields]); + /* Seeds difficultyTarget and skill once they appear (form-only fields, absent from FALLBACK_FIELDS); safe since neither is rendered before then. */ + useEffect(() => { + if (!open) { diffSeededRef.current = null; return; } + if (!content) return; + const dtFields = fields.filter(isDifficultyTargetField); + if (dtFields.length === 0) return; + if (diffSeededRef.current === content.identifier) return; + diffSeededRef.current = content.identifier; + const diff: Record = {}; + for (const f of dtFields) { + diff[f.code] = toDifficultyTarget((content as Record)[f.code]); + } + setDiffTargets((s) => ({ ...s, ...diff })); + const skill: Record = {}; + for (const f of ed.isDynamicAssess ? fields.filter(isSkillField) : []) { + const cv = (content as Record)[f.code]; + skill[f.code] = Array.isArray(cv) ? cv.map(String) : cv != null && cv !== '' ? [String(cv)] : []; + } + setMultiVals((s) => ({ ...s, ...skill })); + }, [open, content, fields]); + const appIconField = fields.find((f) => f.code === 'appicon' || f.code === 'appIcon'); const hasAppIcon = !!appIconField; const appIconLabel = appIconField?.label ?? appIconField?.name ?? t(lang, 'THUMBNAIL'); @@ -211,6 +307,16 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { } }; + /** A new framework means different category terms, so clear skill and every category value picked under the old one. */ + const onFrameworkChange = (fw: string) => { + const codes = [...categories.map((c) => c.code), 'skill']; + setSelectedFw(fw); + setCategories([]); + loadedFw.current = null; // otherwise re-picking the original framework (or the placeholder) never reloads its categories + setMultiVals((s) => ({ ...s, ...Object.fromEntries(codes.map((c) => [c, []])) })); + setValues((s) => ({ ...s, ...Object.fromEntries(codes.filter((c) => c in s).map((c) => [c, ''])) })); + }; + /** Labels of required, editable, visible fields left empty (any inputType). */ const missingRequired = (): string[] => { const miss: string[] = []; @@ -219,30 +325,29 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const code = f.code; let empty: boolean; if (code === 'appicon' || code === 'appIcon') empty = !appIcon; - else if (isMultiField(f)) empty = (multiVals[code] ?? []).length === 0; + else if (isDifficultyTargetField(f)) { + const dt = diffTargets[code] ?? {}; + empty = (dt.E ?? 0) + (dt.M ?? 0) + (dt.D ?? 0) <= 0; + } + else if (isMultiField(f, ed.isDynamicAssess)) empty = (multiVals[code] ?? []).length === 0; else empty = !((values[code] ?? '').trim()); if (empty) miss.push(f.label ?? f.name ?? code); } return miss; }; - const onSave = () => { - const nameField = fields.find((f) => f.code === 'name'); - if (nameField?.required !== false && !(values.name ?? '').trim()) { - showToast(t(lang, 'ERROR_TITLE_REQUIRED'), 'error'); - return; - } - // On the submit-for-review path, enforce every required field the form marks (not just name). - if (reviewSubmitMode) { - const miss = missingRequired(); - if (miss.length) { setReviewErrors(miss); return; } - } + /** The fields this save would write; the Save label and onSave both read it, so they never disagree. */ + const buildOut = (): Record => { const out: Record = {}; for (const f of fields) { if (f.editable === false) continue; const code = f.code === 'appIcon' ? 'appIcon' : f.code; if (code === 'appicon' || code === 'appIcon') continue; // handled below - if (isMultiField(f)) { + if (isDifficultyTargetField(f)) { + out[f.code] = serializeDifficultyTarget(diffTargets[f.code] ?? { E: 0, M: 0, D: 0 }); + continue; + } + if (isMultiField(f, ed.isDynamicAssess)) { const arr = multiVals[f.code] ?? []; out[f.code] = arr.length ? arr : undefined; continue; @@ -252,7 +357,84 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { out[f.code] = raw || undefined; } if (appIcon) out.appIcon = appIcon; + if (ed.isDynamicAssess && selectedFw) out.framework = selectedFw; out.name = (values.name ?? '').trim(); + return out; + }; + + /** Blocks the save unless the job could generate these settings (its own allocation rules) and knowlg-service would accept every skill; returns true to proceed. */ + const checkPoolSufficiency = async (candidate: Record): Promise => { + const target = toDifficultyTarget(candidate.difficultyTarget); + const skillValues = Array.isArray(candidate.skill) ? candidate.skill.map(String) : []; + const m = DYNAMIC_ASSESS_POOL_MULTIPLIER; + let buckets: Record>; + let skillCounts: Record; + try { + const channel = (content as Record | null)?.channel as string | undefined; + [buckets, skillCounts] = await Promise.all([ + service.searchAssessmentItemBucketCounts(skillValues, channel ?? ed.context.channel, skillCategoryCode ?? 'skill'), + service.searchSkillPoolCounts(skillValues, skillCategoryCode ?? 'skill'), + ]); + } catch { + showToast(t(lang, 'ERROR_POOL_CHECK_FAILED'), 'error'); + return false; + } + const plan = planPool(skillValues, target, (s, l) => buckets[s]?.[l] ?? 0, DYNAMIC_ASSESS_MIN_CRITERIA, m); + if (plan.infeasible) { + showToast(tf(lang, 'ERROR_TOO_MANY_SKILLS', { count: skillValues.length, needed: skillValues.length * DYNAMIC_ASSESS_MIN_CRITERIA, min: DYNAMIC_ASSESS_MIN_CRITERIA }), 'error'); + return false; + } + if (plan.uncovered.length) { + const levelKey = { E: 'DIFFICULTY_EASY', M: 'DIFFICULTY_MEDIUM', D: 'DIFFICULTY_DIFFICULT' } as const; + const lines = plan.uncovered.map(({ level, covered, target: requested }) => + tf(lang, 'ERROR_POOL_SHORTFALL', { level: t(lang, levelKey[level]), requested, needed: requested * m, available: covered * m })); + showToast(`${t(lang, 'ERROR_POOL_INSUFFICIENT')}: ${lines.join('; ')}`, 'error'); + return false; + } + // A skill that can't get its own minimum would be left out of the pool, and the settings would then never match the questions. + if (plan.shortSkills.length) { + showToast(tf(lang, 'ERROR_SKILL_LEVELS_SHORT', { skills: plan.shortSkills.join(', ') }), 'error'); + return false; + } + // Same per-skill floor knowlg-service enforces at Generate, so it fails here, translated, instead of after a successful save. + const perSkill = DYNAMIC_ASSESS_MIN_CRITERIA * m; + const shortSkills = skillValues.filter((s) => (skillCounts[s] ?? 0) < perSkill); + if (shortSkills.length) { + showToast(tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: perSkill, skills: shortSkills.join(', ') }), 'error'); + return false; + } + return true; + }; + + const onSave = async () => { + if (checking || busy) return; // a second click during the pool searches would save and generate twice + if (ed.dynamicAssessRefreshing) return; // a save now would skip generating, since only one generation runs at a time + const nameField = fields.find((f) => f.code === 'name'); + if (nameField?.required !== false && !(values.name ?? '').trim()) { + showToast(t(lang, 'ERROR_TITLE_REQUIRED'), 'error'); + return; + } + // On the submit-for-review path, enforce every required field the form marks (not just name). + if (reviewSubmitMode) { + const miss = missingRequired(); + if (miss.length) { setReviewErrors(miss); return; } + } + const out = buildOut(); + const generates = needsGeneration({ ...(content ?? {}), ...out }); + // Submitting can't also generate, so changed settings must be saved (and generated) first. + if (reviewSubmitMode && generates) { + showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_SUBMIT_STALE'), 'error'); + return; + } + if (generates) { + setChecking(true); + try { + // The pool is only checked when this save will generate, so other edits cost no extra searches. + if (!(await checkPoolSufficiency({ ...(content ?? {}), ...out }))) return; + } finally { + setChecking(false); + } + } setReviewErrors([]); if (reviewSubmitMode) saveMetadataAndSubmit(out); else saveMetadata(out); @@ -270,10 +452,62 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (code === 'appicon' || code === 'appIcon') return null; // rendered in the top block + if (isDifficultyTargetField(f)) { + return ( + setDiffTargets((s) => ({ ...s, [code]: v }))} + /> + ); + } + + if (ed.isDynamicAssess && isSkillField(f)) { + // Current framework stays selectable even if it isn't in the system-default search results. + const fwList = selectedFw && !fwOptions.some((o) => o.identifier === selectedFw) + ? [{ identifier: selectedFw, name: selectedFw }, ...fwOptions] + : fwOptions; + return ( + + {ed.isDynamicAssess && ( +
+ +
+ + +
+
+ )} + setMulti(code, vals)} + /> +
+ ); + } + if (taxoCodes.has(code)) { const options = cascadedOptions(categories, code, selectedTaxo); // Multi vs single is decided by the form definition, not the field name. - if (isMultiField(f)) { + if (isMultiField(f, ed.isDynamicAssess)) { return ( = ({ ed }) => { ); }; - const taxoFields = fields.filter((f) => taxoCodes.has(f.code)); + // Live label: tells the author when Save will also generate questions. + const saveGenerates = ed.isDynamicAssess && open && needsGeneration({ ...(content ?? {}), ...buildOut() }); + + // Skill always renders with the other fields (under its framework picker), even when a framework names a category 'skill'. + const taxoFields = fields.filter((f) => taxoCodes.has(f.code) && !(ed.isDynamicAssess && isSkillField(f))); const nonTaxoFields = fields.filter( - (f) => !taxoCodes.has(f.code) && f.code !== 'appicon' && f.code !== 'appIcon', + (f) => (!taxoCodes.has(f.code) || (ed.isDynamicAssess && isSkillField(f))) && f.code !== 'appicon' && f.code !== 'appIcon', ); return ( @@ -354,10 +592,10 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { - } diff --git a/src/constants.ts b/src/constants.ts index c5abe11..3812250 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -2,6 +2,12 @@ export const TELEMETRY_VERSION = '3.0'; +/** Dynamic Assess: each difficulty needs requested x this many Live questions; must match the backend's dynamicassess.multiplier. */ +export const DYNAMIC_ASSESS_POOL_MULTIPLIER = 3; + +/** Dynamic Assess: each selected skill must contribute at least this many questions; must match the backend's dynamicassess.minCriteria. */ +export const DYNAMIC_ASSESS_MIN_CRITERIA = 2; + /** Default content category options shown in the upload content-type picker. * Mirrors portal editorConfig.DEFAULT_PRIMARY_CATEGORIES (subset relevant to upload). */ export const DEFAULT_PRIMARY_CATEGORIES = [ diff --git a/src/difficultyTarget.ts b/src/difficultyTarget.ts new file mode 100644 index 0000000..ce29c3e --- /dev/null +++ b/src/difficultyTarget.ts @@ -0,0 +1,25 @@ +/** Dynamic Assess's difficultyTarget: Easy/Medium/Difficult question counts. */ +export interface DifficultyTarget { E?: number; M?: number; D?: number } + +export function toDifficultyTarget(v: unknown): DifficultyTarget { + // The API returns difficultyTarget JSON-stringified (the OCD declares it a string), so parse strings first. + let obj: unknown = v; + if (typeof v === 'string' && v.trim()) { + try { obj = JSON.parse(v); } catch { obj = undefined; } + } + if (obj && typeof obj === 'object') { + const o = obj as Record; + return { E: Number(o.E) || 0, M: Number(o.M) || 0, D: Number(o.D) || 0 }; + } + return { E: 0, M: 0, D: 0 }; +} + +/** Writes the string type the OCD declares rather than relying on the backend accepting either shape. */ +export function serializeDifficultyTarget(v: DifficultyTarget): string { + return JSON.stringify({ E: v.E ?? 0, M: v.M ?? 0, D: v.D ?? 0 }); +} + +export function difficultyTargetTotal(v: unknown): number { + const t = toDifficultyTarget(v); + return (t.E ?? 0) + (t.M ?? 0) + (t.D ?? 0); +} diff --git a/src/dynamicAssessDraw.test.ts b/src/dynamicAssessDraw.test.ts new file mode 100644 index 0000000..19169f7 --- /dev/null +++ b/src/dynamicAssessDraw.test.ts @@ -0,0 +1,88 @@ +import { describe, it, expect } from 'vitest'; +import { ecmlBodyForUser, pickForLearner, isGenerationStale } from './dynamicAssessDraw'; + +const levels: Record = { a1: 'EASY', a2: 'EASY', a3: 'EASY', b1: 'MEDIUM', b2: 'MEDIUM', b3: 'MEDIUM' }; +const body = (dynamic: boolean) => ({ + theme: { stage: [{ 'org.ekstep.questionset': [{ + config: { __cdata: JSON.stringify({ total_items: 6, ...(dynamic ? { dynamic_assess: { target: { E: 1, M: 1, D: 0 }, levels } } : {}) }) }, + data: { __cdata: JSON.stringify(Object.keys(levels).map((id) => ({ identifier: id, max_score: 1 }))) }, + 'org.ekstep.question': Object.keys(levels).map((id) => ({ id })), + }] }] }, +}); +const quizOf = (b: any) => b.theme.stage[0]['org.ekstep.questionset'][0]; + +describe('ecmlBodyForUser', () => { + it("previews only the user's draw per level, matching the portal's seed (positive)", () => { + const out = ecmlBodyForUser(body(true), 'do_c', 'u1') as any; + const kept = quizOf(out)['org.ekstep.question'].map((q: any) => q.id); + expect(kept).toHaveLength(2); + expect(kept.filter((id: string) => levels[id] === 'MEDIUM')).toEqual(pickForLearner(['b1', 'b2', 'b3'], 1, 'u1:do_c:MEDIUM')); + expect(JSON.parse(quizOf(out).config.__cdata).total_items).toBe(2); + }); + + it('does not mutate the original body', () => { + const original = body(true); + ecmlBodyForUser(original, 'do_c', 'u1'); + expect(quizOf(original)['org.ekstep.question']).toHaveLength(6); + }); + + it('returns bodies without the dynamic block, and non-objects, unchanged (negative)', () => { + const plain = body(false); + expect(ecmlBodyForUser(plain, 'do_c', 'u1')).toBe(plain); + expect(ecmlBodyForUser({}, 'do_c', 'u1')).toEqual({}); + }); +}); + +describe('isGenerationStale', () => { + const generated = (block: Record) => JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: block }) } } }] }, + }); + + it('flags a difficulty target changed after generation (positive)', () => { + expect(isGenerationStale(generated({ target: { E: 3, M: 3, D: 3 } }), { E: 3, M: 2, D: 3 }, ['Physics'])).toBe(true); + }); + + it('flags added, removed or swapped skills when the job recorded them (positive)', () => { + const body = generated({ skills: ['Physics'], target: { E: 1, M: 1, D: 1 } }); + expect(isGenerationStale(body, { E: 1, M: 1, D: 1 }, ['Chemistry'])).toBe(true); + expect(isGenerationStale(body, { E: 1, M: 1, D: 1 }, ['Physics', 'Chemistry'])).toBe(true); + expect(isGenerationStale(body, { E: 1, M: 1, D: 1 }, [])).toBe(true); + }); + + it('is not stale when settings match, ignoring skill order (negative)', () => { + const body = generated({ skills: ['Physics', 'Chemistry'], target: { E: 1, M: 1, D: 0 } }); + expect(isGenerationStale(body, { E: 1, M: 1, D: 0 }, ['Chemistry', 'Physics'])).toBe(false); + }); + + it('skips the skill check for questions generated before the job recorded skills (negative)', () => { + expect(isGenerationStale(generated({ target: { E: 1, M: 1, D: 1 } }), { E: 1, M: 1, D: 1 }, ['Anything'])).toBe(false); + }); + + it('is never stale without a generated quiz (negative)', () => { + expect(isGenerationStale(undefined, { E: 1 }, ['Physics'])).toBe(false); + expect(isGenerationStale(JSON.stringify(body(false)), { E: 9 }, ['Physics'])).toBe(false); + }); +}); + +describe('ecmlBodyForUser — fail closed and parity', () => { + const withTarget = (target: unknown) => ({ + theme: { stage: [{ 'org.ekstep.questionset': [{ + config: { __cdata: JSON.stringify({ dynamic_assess: { target, levels } }) }, + data: { __cdata: JSON.stringify(Object.keys(levels).map((id) => ({ identifier: id, max_score: 1 }))) }, + 'org.ekstep.question': Object.keys(levels).map((id) => ({ id })), + }] }] }, + }); + + it('draws nothing, never the pool, for a zero or unparseable target (positive)', () => { + expect(quizOf(ecmlBodyForUser(withTarget({ E: 0, M: 0, D: 0 }), 'do_c', 'u1'))['org.ekstep.question']).toEqual([]); + expect(quizOf(ecmlBodyForUser(withTarget('nope'), 'do_c', 'u1'))['org.ekstep.question']).toEqual([]); + }); + + it('accepts a JSON-string target like the portal does (positive)', () => { + expect(quizOf(ecmlBodyForUser(withTarget('{"E":1,"M":1,"D":0}'), 'do_c', 'u1'))['org.ekstep.question']).toHaveLength(2); + }); + + it('matches the golden vector shared with the portal and the QuestionSet editor', () => { + expect(pickForLearner(['q1', 'q2', 'q3', 'q4', 'q5', 'q6'], 2, 'user-1:do_123:EASY')).toEqual(['q6', 'q3']); + }); +}); diff --git a/src/dynamicAssessDraw.ts b/src/dynamicAssessDraw.ts new file mode 100644 index 0000000..a87a847 --- /dev/null +++ b/src/dynamicAssessDraw.ts @@ -0,0 +1,121 @@ +// Same seeded draw as the portal's dynamicAssessSubset, so the preview shows the user the exact set they'd play; the full pool is never displayed. + +const LEVELS = [['E', 'EASY'], ['M', 'MEDIUM'], ['D', 'DIFFICULT']] as const; +type AnyRecord = Record; + +function hashSeed(seed: string): number { + let h = 0x811c9dc5; + for (let i = 0; i < seed.length; i++) { + h ^= seed.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +function seededRandom(seed: string): () => number { + let a = hashSeed(seed); + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export function pickForLearner(ids: string[], count: number, seed: string): string[] { + const pool = [...new Set(ids)].sort(); + if (count >= pool.length) return pool; + const rand = seededRandom(seed); + for (let i = pool.length - 1; i > 0; i--) { + const j = Math.floor(rand() * (i + 1)); + const swap = pool[i] as string; + pool[i] = pool[j] as string; + pool[j] = swap; + } + return pool.slice(0, Math.max(0, count)); +} + +function parseBody(body: unknown): AnyRecord | null { + if (body && typeof body === 'object') return body as AnyRecord; + if (typeof body !== 'string' || !body.trim()) return null; + try { return JSON.parse(body); } catch { return null; } +} + +/** The target (and, from newer job builds, skills) the job generated the current questions for; null when there is no generated quiz. */ +export function generatedSettings(body: unknown): { target: AnyRecord; skills?: string[] } | null { + const stages: AnyRecord[] = parseBody(body)?.theme?.stage ?? []; + for (const stage of Array.isArray(stages) ? stages : []) { + for (const quiz of ([] as AnyRecord[]).concat(stage?.['org.ekstep.questionset'] ?? [])) { + let config: AnyRecord; + try { config = JSON.parse(quiz?.config?.__cdata ?? ''); } catch { continue; } + const block = config?.dynamic_assess; + if (block?.target) return { target: block.target, skills: Array.isArray(block.skills) ? block.skills.map(String) : undefined }; + } + } + return null; +} + +/** True when the saved skill or difficultyTarget no longer match what the questions were generated for; skills are only compared when the job recorded them. */ +export function isGenerationStale(body: unknown, savedTarget: { E?: number; M?: number; D?: number }, savedSkills: string[] | undefined): boolean { + const generated = generatedSettings(body); + if (!generated) return false; + if ((['E', 'M', 'D'] as const).some((k) => (Number(generated.target[k]) || 0) !== (savedTarget[k] ?? 0))) return true; + if (!generated.skills) return false; + const saved = new Set((savedSkills ?? []).map(String)); + return saved.size !== new Set(generated.skills).size || generated.skills.some((s) => !saved.has(s)); +} + +function parseTarget(raw: unknown): AnyRecord { + let value = raw; + if (typeof value === 'string') { try { value = JSON.parse(value); } catch { value = undefined; } } + return value && typeof value === 'object' ? (value as AnyRecord) : {}; +} + +/** Save must also generate when Skill + Difficulty Target are usable and there are no questions yet or they were built for other settings; any other save is a plain save. */ +export function needsGeneration(c: { primaryCategory?: string; skill?: unknown; difficultyTarget?: unknown; totalQuestions?: unknown; body?: unknown } | null): boolean { + if (c?.primaryCategory !== 'Dynamic Course Assessment') return false; + const skills = Array.isArray(c.skill) ? c.skill.map(String) : []; + const target = parseTarget(c.difficultyTarget); + const savedTarget = { E: Number(target.E) || 0, M: Number(target.M) || 0, D: Number(target.D) || 0 }; + if (!skills.length || savedTarget.E + savedTarget.M + savedTarget.D <= 0) return false; + return !(Number(c.totalQuestions ?? 0) > 0) || isGenerationStale(c.body, savedTarget, skills); +} + +/** Trims each generated quiz in a parsed ECML body to this user's draw; bodies without the job's dynamic_assess block are returned unchanged. */ +export function ecmlBodyForUser(body: unknown, contentId: string, userId: string | undefined): unknown { + if (!body || typeof body !== 'object') return body; + const stages: AnyRecord[] = Array.isArray((body as AnyRecord).theme?.stage) ? (body as AnyRecord).theme.stage : []; + if (!stages.some((s) => s?.['org.ekstep.questionset'])) return body; + const copy: AnyRecord = structuredClone(body); + let changed = false; + for (const stage of copy.theme.stage as AnyRecord[]) { + const quizzes: AnyRecord[] = ([] as AnyRecord[]).concat(stage?.['org.ekstep.questionset'] ?? []); + for (const quiz of quizzes) { + let config: AnyRecord; + try { config = JSON.parse(quiz?.config?.__cdata ?? ''); } catch { continue; } + const block = config?.dynamic_assess; + const questions: AnyRecord[] = ([] as AnyRecord[]).concat(quiz['org.ekstep.question'] ?? []); + if (!block || questions.length === 0) continue; + // Fails closed like the portal: a missing, zero or unparseable target draws nothing rather than revealing the pool. + const target = parseTarget(block.target); + const levels: AnyRecord = block.levels ?? {}; + const picked = new Set(); + for (const [key, level] of LEVELS) { + const atLevel = questions.map((q) => String(q.id)).filter((id) => String(levels[id] ?? '').toUpperCase() === level); + pickForLearner(atLevel, Number(target[key]) || 0, `${userId || 'anonymous'}:${contentId}:${level}`).forEach((id) => picked.add(id)); + } + const kept = questions.filter((q) => picked.has(String(q.id))); + if (kept.length === questions.length) continue; + let items: AnyRecord[] = []; + try { items = JSON.parse(quiz?.data?.__cdata ?? '[]'); } catch { items = []; } + const keptItems = items.filter((item) => picked.has(String(item.identifier))); + quiz['org.ekstep.question'] = kept; + if (quiz.data) quiz.data.__cdata = JSON.stringify(keptItems); + config.total_items = kept.length; + config.max_score = keptItems.length ? keptItems.reduce((sum, item) => sum + (Number(item.max_score) || 1), 0) : kept.length; + quiz.config.__cdata = JSON.stringify(config); + changed = true; + } + } + return changed ? copy : body; +} diff --git a/src/editor.scss b/src/editor.scss index 579c56f..43e1abe 100644 --- a/src/editor.scss +++ b/src/editor.scss @@ -294,6 +294,35 @@ opacity: 0; } +/* Hint on a wrapper around a disabled button (Dynamic Assess Send for review / Publish); end-aligned so it stays inside the header. */ +.ce-disabled-hint { + position: relative; + display: inline-flex; +} + +.ce-disabled-hint[data-tooltip]::after { + content: attr(data-tooltip); + position: absolute; + top: calc(100% + 8px); + inset-inline-end: 0; + background: var(--ce-ink); + color: #fff; + font-size: 11.5px; + font-weight: 500; + white-space: nowrap; + padding: 5px 9px; + border-radius: 6px; + box-shadow: 0 4px 12px rgba(15, 23, 42, 0.2); + opacity: 0; + pointer-events: none; + transition: opacity 0.15s ease; + z-index: 400; +} + +.ce-disabled-hint[data-tooltip]:hover::after { + opacity: 1; +} + .ce-icon-btn:hover { background: var(--ce-bg); color: var(--ce-primary); @@ -1023,6 +1052,90 @@ animation: ce-overlay-fade 0.2s ease; } +.ce-stale-banner { + display: flex; + align-items: center; + gap: 14px; + width: 100%; + max-width: 960px; + margin: 18px auto 0; + padding: 12px 14px 12px 16px; + border-radius: 14px; + border: 1px solid #f0c96b; + background: #fffbeb; + color: #7a4f05; + text-align: start; + box-shadow: 0 4px 6px rgba(15, 23, 42, 0.04); +} + +.ce-stale-banner-ic { + flex: none; + width: 34px; + height: 34px; + border-radius: 50%; + display: grid; + place-items: center; + background: #fdecc8; + color: #c98a1c; +} + +.ce-stale-banner-tx { + flex: 1; + min-width: 0; +} + +.ce-stale-banner-title { + margin: 0; + font-size: 14px; + font-weight: 700; + color: #6b4404; +} + +.ce-stale-banner-sub { + margin: 2px 0 0; + font-size: 13px; + line-height: 1.45; +} + +.ce-generating-overlay { + position: absolute; + inset: 0; + z-index: 200; + display: flex; + align-items: center; + justify-content: center; + background: rgba(15, 23, 42, 0.45); + animation: ce-overlay-fade 0.2s ease; +} + +.ce-generating-card { + background: var(--ce-white); + border-radius: 18px; + padding: 36px 44px; + max-width: 380px; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + box-shadow: 0 16px 48px rgba(15, 23, 42, 0.2); + animation: ce-modal-in 0.22s ease; +} + +.ce-generating-title { + font-size: 18px; + font-weight: 700; + color: var(--ce-ink); + margin: 0; +} + +.ce-generating-sub { + font-size: 13px; + line-height: 1.5; + color: var(--ce-slate-500); + margin: 0; +} + .ce-upload-success-card { background: var(--ce-white); border-radius: 18px; diff --git a/src/i18n/i18n.test.ts b/src/i18n/i18n.test.ts index d25969d..a8d491d 100644 --- a/src/i18n/i18n.test.ts +++ b/src/i18n/i18n.test.ts @@ -1,6 +1,12 @@ import { describe, it, expect } from 'vitest'; import { t, tf, getDir, getMimeTypeLabel, getCategoryLabel } from './i18n'; import { MIME_H5P } from '../constants'; +import { TRANSLATIONS_EN } from './translations.en'; +import { TRANSLATIONS_AR } from './translations.ar'; +import { TRANSLATIONS_FR } from './translations.fr'; +import { TRANSLATIONS_HI } from './translations.hi'; +import { TRANSLATIONS_PT } from './translations.pt'; +import { TRANSLATIONS_TA } from './translations.ta'; describe('i18n', () => { it('t returns the key itself when missing (negative)', () => { @@ -19,6 +25,21 @@ describe('i18n', () => { it('getCategoryLabel falls back to the raw category when unknown', () => { expect(getCategoryLabel('en', 'Totally Custom Category')).toBe('Totally Custom Category'); }); + it('translates every Dynamic Assess key in every language instead of falling back to English (positive)', () => { + const tables = { ar: TRANSLATIONS_AR, fr: TRANSLATIONS_FR, hi: TRANSLATIONS_HI, pt: TRANSLATIONS_PT, ta: TRANSLATIONS_TA }; + const daKeys = Object.keys(TRANSLATIONS_EN).filter((k) => /DYNAMIC_ASSESS|POOL|^DIFFICULTY_|GENERATE|SKILL/.test(k)); + expect(daKeys.length).toBeGreaterThan(0); + for (const [lang, table] of Object.entries(tables)) { + for (const key of daKeys) expect(table[key], `${lang}.${key}`).toBeTruthy(); + } + }); + it('fills every placeholder of the pool shortfall message in every language (positive)', () => { + for (const lang of ['en', 'ar', 'fr', 'hi', 'pt', 'ta']) { + const msg = tf(lang, 'ERROR_POOL_SHORTFALL', { level: 'L', requested: 2, needed: 6, available: 4 }); + expect(msg, lang).not.toMatch(/\{\w+\}/); + expect(msg, lang).toContain('6'); + } + }); it('getDir defaults to ltr for latin languages', () => { expect(getDir('en')).toBe('ltr'); }); diff --git a/src/i18n/translations.ar.ts b/src/i18n/translations.ar.ts index 35e4034..ee097d7 100644 --- a/src/i18n/translations.ar.ts +++ b/src/i18n/translations.ar.ts @@ -205,4 +205,37 @@ export const TRANSLATIONS_AR: Record = { TRANSCRIPTS_LOAD_ERROR_TITLE: 'تعذّر تحميل النصوص', NO_TRANSCRIPTS_TITLE: 'لا توجد نصوص بعد', NO_TRANSCRIPTS_SUB: 'بمجرد نشر هذا الفيديو، يمكن الموافقة على نصه أو تعديله أو رفضه هنا.', + + /* Dynamic Assess */ + TOAST_DYNAMIC_ASSESS_REFRESH_DONE: 'تم إنشاء الأسئلة', + TOAST_DYNAMIC_ASSESS_PENDING: 'لم تظهر الأسئلة بعد. قد يكون الإنشاء لا يزال جاريًا، أو ربما فشل (مثلًا بسبب قلة الأسئلة لإحدى المهارات). أعد فتح هذا المحتوى بعد لحظات، أو تحقّق من المجموعة وحاول مرة أخرى.', + SAVE_AND_GENERATE: 'حفظ وإنشاء', + REGENERATE_QUESTIONS: 'إعادة الإنشاء', + REGENERATE_QUESTIONS_HINT: 'اختر مجموعة عشوائية جديدة من الأسئلة لنفس المهارة وهدف الصعوبة', + DYNAMIC_ASSESS_GENERATING_TITLE: 'جارٍ إنشاء الأسئلة', + DYNAMIC_ASSESS_GENERATING_SUB: 'يتم اختيار الأسئلة من المجموعة وفق المهارات والصعوبة المحددة. يستغرق ذلك عادةً بضع ثوانٍ.', + DYNAMIC_ASSESS_GENERATE_FIRST: 'أنشئ الأسئلة قبل الإرسال للمراجعة', + DYNAMIC_ASSESS_EMPTY_TITLE: 'لم يتم إنشاء أي أسئلة بعد', + DYNAMIC_ASSESS_EMPTY_SUB: 'افتح تعديل التفاصيل، وحدّد المهارة وهدف الصعوبة، ثم احفظ لإنشاء الأسئلة.', + DYNAMIC_ASSESS_FRAMEWORK: 'الإطار', + DYNAMIC_ASSESS_SELECT_FRAMEWORK: 'اختر الإطار', + DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'اختر إطارًا أولاً', + DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'لم يتم إنشاء أي أسئلة لهذا المحتوى بعد.', + ERROR_DYNAMIC_ASSESS_INPUTS: 'حدّد المهارة وهدف الصعوبة قبل إنشاء الأسئلة.', + ERROR_POOL_INSUFFICIENT: 'لا توجد أسئلة كافية للمهارات المحددة', + ERROR_POOL_CHECK_FAILED: 'تعذّر التحقق من توفر الأسئلة. يرجى المحاولة مرة أخرى.', + ERROR_POOL_SHORTFALL: '{level}: المطلوب {requested} يحتاج {needed}، المتاح {available}', + ERROR_SKILL_POOL_TOO_SMALL: 'تحتاج كل مهارة إلى {needed} أسئلة منشورة على الأقل. عددها قليل جدًا لـ: {skills}', + ERROR_DYNAMIC_ASSESS_SUBMIT_STALE: 'تغيّرت المهارة أو هدف الصعوبة. أغلق هذا، واستخدم حفظ وإنشاء في تعديل التفاصيل لإنشاء الأسئلة، ثم أرسل للمراجعة.', + ERROR_TOO_MANY_SKILLS: 'مع {count} مهارات، يجب أن يكون مجموع هدف الصعوبة {needed} على الأقل (تحصل كل مهارة على {min} أسئلة على الأقل). ارفع الهدف أو أزل مهارة.', + ERROR_SKILL_LEVELS_SHORT: 'لا توجد أسئلة كافية في مستويات الصعوبة المحددة لـ: {skills}. يجب أن توفّر كل مهارة سؤالين على الأقل في هذه المستويات.', + DIFFICULTY_EASY: 'سهل', + DIFFICULTY_MEDIUM: 'متوسط', + DIFFICULTY_DIFFICULT: 'صعب', + DYNAMIC_ASSESS_STALE_TITLE: 'تغيّرت الإعدادات منذ إنشاء الأسئلة', + DYNAMIC_ASSESS_STALE_SUB: 'الأسئلة لا تطابق المهارة وهدف الصعوبة الحاليين. انقر على إعادة الإنشاء لتحديثها.', + DYNAMIC_ASSESS_STALE_SUB_READONLY: 'لم تعد المهارة أو هدف الصعوبة يطابقان الأسئلة المُنشأة. اطلب تغييرات ليتمكن المنشئ من إعادة إنشائها.', + DYNAMIC_ASSESS_STALE_TIP: 'تغيّرت الإعدادات — أعد إنشاء الأسئلة أولاً', + ERROR_DYNAMIC_ASSESS_STALE: 'تغيّرت المهارة أو هدف الصعوبة منذ إنشاء الأسئلة. أعد إنشاءها ثم أرسل للمراجعة.', + ERROR_DYNAMIC_ASSESS_STALE_REVIEW: 'الأسئلة لا تطابق المهارة أو هدف الصعوبة الحاليين. اطلب تغييرات ليتمكن المنشئ من إعادة إنشائها.', }; diff --git a/src/i18n/translations.en.ts b/src/i18n/translations.en.ts index 29a25ae..e94e503 100644 --- a/src/i18n/translations.en.ts +++ b/src/i18n/translations.en.ts @@ -207,6 +207,39 @@ export const TRANSLATIONS_EN: Record = { TOAST_REJECTED: 'Changes requested — sent back to creator', TOAST_COLLAB_SAVED: 'Collaborators updated', TOAST_CLOSED: 'Editor closed — changes saved', + TOAST_DYNAMIC_ASSESS_REFRESH_DONE: 'Questions generated', + TOAST_DYNAMIC_ASSESS_PENDING: 'Questions haven\'t appeared yet. Generation may still be in progress, or it may have failed (for example, too few questions for a skill). Reopen this content in a moment, or check the pool and try again.', + + /* Dynamic Assess */ + SAVE_AND_GENERATE: 'Save & Generate', + REGENERATE_QUESTIONS: 'Regenerate', + REGENERATE_QUESTIONS_HINT: 'Pick a new random set of questions for the same Skill and Difficulty Target', + DYNAMIC_ASSESS_GENERATING_TITLE: 'Generating questions', + DYNAMIC_ASSESS_GENERATING_SUB: 'Picking questions from the pool for the selected skills and difficulty. This usually takes a few seconds.', + DYNAMIC_ASSESS_GENERATE_FIRST: 'Generate questions before sending for review', + DYNAMIC_ASSESS_EMPTY_TITLE: 'No questions generated yet', + DYNAMIC_ASSESS_EMPTY_SUB: 'Open Edit details, set Skill and Difficulty Target, and save to generate the questions.', + DYNAMIC_ASSESS_FRAMEWORK: 'Framework', + DYNAMIC_ASSESS_SELECT_FRAMEWORK: 'Select framework', + DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'Select a framework first', + DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'No questions have been generated for this content yet.', + ERROR_DYNAMIC_ASSESS_INPUTS: 'Set Skill and Difficulty Target before generating questions.', + ERROR_POOL_INSUFFICIENT: 'Not enough questions available for the selected skill(s)', + ERROR_POOL_CHECK_FAILED: 'Could not verify question availability. Please try again.', + ERROR_POOL_SHORTFALL: '{level}: requested {requested} needs {needed}, available {available}', + ERROR_SKILL_POOL_TOO_SMALL: 'Each skill needs at least {needed} Live questions. Too few for: {skills}', + ERROR_DYNAMIC_ASSESS_SUBMIT_STALE: 'Skill or Difficulty Target changed. Close this, use Save & Generate in Edit details to create the questions, then send for review.', + ERROR_TOO_MANY_SKILLS: 'With {count} skills, the Difficulty Target must add up to at least {needed} (each skill gets at least {min} questions). Raise the target or remove a skill.', + ERROR_SKILL_LEVELS_SHORT: 'Not enough questions at the selected difficulty levels for: {skills}. Each skill needs at least 2 questions it can supply at those levels.', + DIFFICULTY_EASY: 'Easy', + DIFFICULTY_MEDIUM: 'Medium', + DIFFICULTY_DIFFICULT: 'Difficult', + DYNAMIC_ASSESS_STALE_TITLE: 'Settings changed since the questions were generated', + DYNAMIC_ASSESS_STALE_SUB: 'The questions don\'t match the current Skill and Difficulty Target. Click Regenerate to update them.', + DYNAMIC_ASSESS_STALE_SUB_READONLY: 'Skill or Difficulty Target no longer matches the generated questions. Request changes so the creator can regenerate them.', + DYNAMIC_ASSESS_STALE_TIP: 'Settings changed — generate questions again first', + ERROR_DYNAMIC_ASSESS_STALE: 'Skill or Difficulty Target changed since the questions were generated. Generate them again, then send for review.', + ERROR_DYNAMIC_ASSESS_STALE_REVIEW: 'The questions don’t match the current Skill or Difficulty Target. Request changes so the creator can regenerate them.', /* Errors */ ERROR_GENERIC: 'Something went wrong. Please try again.', diff --git a/src/i18n/translations.fr.ts b/src/i18n/translations.fr.ts index b4e48d2..3b2a109 100644 --- a/src/i18n/translations.fr.ts +++ b/src/i18n/translations.fr.ts @@ -205,4 +205,37 @@ export const TRANSLATIONS_FR: Record = { TRANSCRIPTS_LOAD_ERROR_TITLE: 'Impossible de charger les transcriptions', NO_TRANSCRIPTS_TITLE: 'Aucune transcription pour le moment', NO_TRANSCRIPTS_SUB: 'Une fois cette vidéo publiée, sa transcription pourra être approuvée, modifiée ou rejetée ici.', + + /* Dynamic Assess */ + TOAST_DYNAMIC_ASSESS_REFRESH_DONE: 'Questions générées', + TOAST_DYNAMIC_ASSESS_PENDING: 'Les questions n’apparaissent pas encore. La génération est peut-être toujours en cours, ou elle a échoué (par exemple, trop peu de questions pour une compétence). Rouvrez ce contenu dans un instant, ou vérifiez le pool et réessayez.', + SAVE_AND_GENERATE: 'Enregistrer et générer', + REGENERATE_QUESTIONS: 'Régénérer', + REGENERATE_QUESTIONS_HINT: 'Choisir un nouvel ensemble aléatoire de questions pour la même compétence et le même objectif de difficulté', + DYNAMIC_ASSESS_GENERATING_TITLE: 'Génération des questions', + DYNAMIC_ASSESS_GENERATING_SUB: 'Sélection des questions du pool selon les compétences et la difficulté choisies. Cela prend généralement quelques secondes.', + DYNAMIC_ASSESS_GENERATE_FIRST: 'Générez les questions avant l’envoi en révision', + DYNAMIC_ASSESS_EMPTY_TITLE: 'Aucune question générée pour le moment', + DYNAMIC_ASSESS_EMPTY_SUB: 'Ouvrez Modifier les détails, définissez la compétence et l’objectif de difficulté, puis enregistrez pour générer les questions.', + DYNAMIC_ASSESS_FRAMEWORK: 'Cadre', + DYNAMIC_ASSESS_SELECT_FRAMEWORK: 'Sélectionner un cadre', + DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'Sélectionnez d’abord un cadre', + DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'Aucune question n’a encore été générée pour ce contenu.', + ERROR_DYNAMIC_ASSESS_INPUTS: 'Définissez la compétence et l’objectif de difficulté avant de générer les questions.', + ERROR_POOL_INSUFFICIENT: 'Pas assez de questions disponibles pour la ou les compétences sélectionnées', + ERROR_POOL_CHECK_FAILED: 'Impossible de vérifier la disponibilité des questions. Veuillez réessayer.', + ERROR_POOL_SHORTFALL: '{level} : {requested} demandées, {needed} nécessaires, {available} disponibles', + ERROR_SKILL_POOL_TOO_SMALL: 'Chaque compétence doit avoir au moins {needed} questions publiées. Trop peu pour : {skills}', + ERROR_DYNAMIC_ASSESS_SUBMIT_STALE: 'La compétence ou l’objectif de difficulté a changé. Fermez ceci, utilisez Enregistrer et générer dans Modifier les détails pour créer les questions, puis envoyez en révision.', + ERROR_TOO_MANY_SKILLS: 'Avec {count} compétences, l’objectif de difficulté doit totaliser au moins {needed} (chaque compétence reçoit au moins {min} questions). Augmentez l’objectif ou retirez une compétence.', + ERROR_SKILL_LEVELS_SHORT: 'Pas assez de questions aux niveaux de difficulté choisis pour : {skills}. Chaque compétence doit pouvoir fournir au moins 2 questions à ces niveaux.', + DIFFICULTY_EASY: 'Facile', + DIFFICULTY_MEDIUM: 'Moyen', + DIFFICULTY_DIFFICULT: 'Difficile', + DYNAMIC_ASSESS_STALE_TITLE: 'Paramètres modifiés depuis la génération des questions', + DYNAMIC_ASSESS_STALE_SUB: 'Les questions ne correspondent pas à la compétence et à l’objectif de difficulté actuels. Cliquez sur Régénérer pour les mettre à jour.', + DYNAMIC_ASSESS_STALE_SUB_READONLY: 'La compétence ou l’objectif de difficulté ne correspond plus aux questions générées. Demandez des modifications pour que le créateur les régénère.', + DYNAMIC_ASSESS_STALE_TIP: 'Paramètres modifiés — générez d’abord les questions à nouveau', + ERROR_DYNAMIC_ASSESS_STALE: 'La compétence ou l’objectif de difficulté a changé depuis la génération des questions. Générez-les à nouveau, puis envoyez en révision.', + ERROR_DYNAMIC_ASSESS_STALE_REVIEW: 'Les questions ne correspondent pas à la compétence ou à l’objectif de difficulté actuels. Demandez des modifications pour que le créateur les régénère.', }; diff --git a/src/i18n/translations.hi.ts b/src/i18n/translations.hi.ts index 2ddeb7d..b2e10d1 100644 --- a/src/i18n/translations.hi.ts +++ b/src/i18n/translations.hi.ts @@ -205,4 +205,37 @@ export const TRANSLATIONS_HI: Record = { TRANSCRIPTS_LOAD_ERROR_TITLE: 'ट्रांसक्रिप्ट लोड नहीं हो सकीं', NO_TRANSCRIPTS_TITLE: 'अभी तक कोई ट्रांसक्रिप्ट नहीं', NO_TRANSCRIPTS_SUB: 'इस वीडियो के प्रकाशित होने के बाद, इसकी ट्रांसक्रिप्ट को यहां स्वीकृत, संशोधित या अस्वीकृत किया जा सकता है।', + + /* Dynamic Assess */ + TOAST_DYNAMIC_ASSESS_REFRESH_DONE: 'प्रश्न तैयार हो गए', + TOAST_DYNAMIC_ASSESS_PENDING: 'प्रश्न अभी तक दिखाई नहीं दिए। प्रश्न तैयार होना अभी जारी हो सकता है, या यह विफल हो गया हो सकता है (उदाहरण के लिए, किसी कौशल के लिए बहुत कम प्रश्न)। कुछ देर बाद यह सामग्री फिर से खोलें, या प्रश्न-संग्रह जांचकर फिर से प्रयास करें।', + SAVE_AND_GENERATE: 'सहेजें और तैयार करें', + REGENERATE_QUESTIONS: 'फिर से तैयार करें', + REGENERATE_QUESTIONS_HINT: 'उसी कौशल और कठिनाई लक्ष्य के लिए प्रश्नों का नया यादृच्छिक सेट चुनें', + DYNAMIC_ASSESS_GENERATING_TITLE: 'प्रश्न तैयार हो रहे हैं', + DYNAMIC_ASSESS_GENERATING_SUB: 'चुने गए कौशल और कठिनाई के अनुसार प्रश्न-संग्रह से प्रश्न चुने जा रहे हैं। इसमें आमतौर पर कुछ सेकंड लगते हैं।', + DYNAMIC_ASSESS_GENERATE_FIRST: 'समीक्षा के लिए भेजने से पहले प्रश्न तैयार करें', + DYNAMIC_ASSESS_EMPTY_TITLE: 'अभी तक कोई प्रश्न तैयार नहीं हुआ', + DYNAMIC_ASSESS_EMPTY_SUB: 'विवरण संपादित करें खोलें, कौशल और कठिनाई लक्ष्य सेट करें, और प्रश्न तैयार करने के लिए सहेजें।', + DYNAMIC_ASSESS_FRAMEWORK: 'फ्रेमवर्क', + DYNAMIC_ASSESS_SELECT_FRAMEWORK: 'फ्रेमवर्क चुनें', + DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'पहले फ्रेमवर्क चुनें', + DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'इस सामग्री के लिए अभी तक कोई प्रश्न तैयार नहीं किया गया है।', + ERROR_DYNAMIC_ASSESS_INPUTS: 'प्रश्न तैयार करने से पहले कौशल और कठिनाई लक्ष्य सेट करें।', + ERROR_POOL_INSUFFICIENT: 'चुने गए कौशल के लिए पर्याप्त प्रश्न उपलब्ध नहीं हैं', + ERROR_POOL_CHECK_FAILED: 'प्रश्नों की उपलब्धता की जांच नहीं हो सकी। कृपया फिर से प्रयास करें।', + ERROR_POOL_SHORTFALL: '{level}: अनुरोधित {requested}, आवश्यक {needed}, उपलब्ध {available}', + ERROR_SKILL_POOL_TOO_SMALL: 'प्रत्येक कौशल के लिए कम से कम {needed} प्रकाशित प्रश्न आवश्यक हैं। इनके लिए बहुत कम हैं: {skills}', + ERROR_DYNAMIC_ASSESS_SUBMIT_STALE: 'कौशल या कठिनाई लक्ष्य बदला गया है। इसे बंद करें, विवरण संपादित करें में सहेजें और तैयार करें से प्रश्न बनाएं, फिर समीक्षा के लिए भेजें।', + ERROR_TOO_MANY_SKILLS: '{count} कौशलों के साथ, कठिनाई लक्ष्य का योग कम से कम {needed} होना चाहिए (प्रत्येक कौशल को कम से कम {min} प्रश्न मिलते हैं)। लक्ष्य बढ़ाएं या कोई कौशल हटाएं।', + ERROR_SKILL_LEVELS_SHORT: 'चुने गए कठिनाई स्तरों पर इनके लिए पर्याप्त प्रश्न नहीं हैं: {skills}। प्रत्येक कौशल को इन स्तरों पर कम से कम 2 प्रश्न देने होंगे।', + DIFFICULTY_EASY: 'आसान', + DIFFICULTY_MEDIUM: 'मध्यम', + DIFFICULTY_DIFFICULT: 'कठिन', + DYNAMIC_ASSESS_STALE_TITLE: 'प्रश्न तैयार होने के बाद सेटिंग्स बदली गई हैं', + DYNAMIC_ASSESS_STALE_SUB: 'प्रश्न वर्तमान कौशल और कठिनाई लक्ष्य से मेल नहीं खाते। उन्हें अपडेट करने के लिए फिर से तैयार करें पर क्लिक करें।', + DYNAMIC_ASSESS_STALE_SUB_READONLY: 'कौशल या कठिनाई लक्ष्य अब तैयार किए गए प्रश्नों से मेल नहीं खाता। परिवर्तन का अनुरोध करें ताकि निर्माता उन्हें फिर से तैयार कर सके।', + DYNAMIC_ASSESS_STALE_TIP: 'सेटिंग्स बदली गई हैं — पहले प्रश्न फिर से तैयार करें', + ERROR_DYNAMIC_ASSESS_STALE: 'प्रश्न तैयार होने के बाद कौशल या कठिनाई लक्ष्य बदला गया है। उन्हें फिर से तैयार करें, फिर समीक्षा के लिए भेजें।', + ERROR_DYNAMIC_ASSESS_STALE_REVIEW: 'प्रश्न वर्तमान कौशल या कठिनाई लक्ष्य से मेल नहीं खाते। परिवर्तन का अनुरोध करें ताकि निर्माता उन्हें फिर से तैयार कर सके।', }; diff --git a/src/i18n/translations.pt.ts b/src/i18n/translations.pt.ts index f0f4844..d92b9bb 100644 --- a/src/i18n/translations.pt.ts +++ b/src/i18n/translations.pt.ts @@ -205,4 +205,37 @@ export const TRANSLATIONS_PT: Record = { TRANSCRIPTS_LOAD_ERROR_TITLE: 'Não foi possível carregar as transcrições', NO_TRANSCRIPTS_TITLE: 'Ainda não há transcrições', NO_TRANSCRIPTS_SUB: 'Assim que este vídeo for publicado, sua transcrição poderá ser aprovada, modificada ou rejeitada aqui.', + + /* Dynamic Assess */ + TOAST_DYNAMIC_ASSESS_REFRESH_DONE: 'Questões geradas', + TOAST_DYNAMIC_ASSESS_PENDING: 'As questões ainda não apareceram. A geração pode ainda estar em andamento ou pode ter falhado (por exemplo, poucas questões para uma habilidade). Reabra este conteúdo em instantes ou verifique o banco e tente novamente.', + SAVE_AND_GENERATE: 'Salvar e gerar', + REGENERATE_QUESTIONS: 'Gerar novamente', + REGENERATE_QUESTIONS_HINT: 'Escolher um novo conjunto aleatório de questões para a mesma Habilidade e Meta de dificuldade', + DYNAMIC_ASSESS_GENERATING_TITLE: 'Gerando questões', + DYNAMIC_ASSESS_GENERATING_SUB: 'Selecionando questões do banco para as habilidades e a dificuldade escolhidas. Isso geralmente leva alguns segundos.', + DYNAMIC_ASSESS_GENERATE_FIRST: 'Gere as questões antes de enviar para revisão', + DYNAMIC_ASSESS_EMPTY_TITLE: 'Nenhuma questão gerada ainda', + DYNAMIC_ASSESS_EMPTY_SUB: 'Abra Editar detalhes, defina a Habilidade e a Meta de dificuldade e salve para gerar as questões.', + DYNAMIC_ASSESS_FRAMEWORK: 'Estrutura', + DYNAMIC_ASSESS_SELECT_FRAMEWORK: 'Selecionar estrutura', + DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'Selecione uma estrutura primeiro', + DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'Nenhuma questão foi gerada para este conteúdo ainda.', + ERROR_DYNAMIC_ASSESS_INPUTS: 'Defina a Habilidade e a Meta de dificuldade antes de gerar as questões.', + ERROR_POOL_INSUFFICIENT: 'Não há questões suficientes disponíveis para a(s) habilidade(s) selecionada(s)', + ERROR_POOL_CHECK_FAILED: 'Não foi possível verificar a disponibilidade de questões. Tente novamente.', + ERROR_POOL_SHORTFALL: '{level}: solicitadas {requested}, necessárias {needed}, disponíveis {available}', + ERROR_SKILL_POOL_TOO_SMALL: 'Cada habilidade precisa de pelo menos {needed} questões publicadas. Poucas para: {skills}', + ERROR_DYNAMIC_ASSESS_SUBMIT_STALE: 'A Habilidade ou a Meta de dificuldade mudou. Feche isto, use Salvar e gerar em Editar detalhes para criar as questões e depois envie para revisão.', + ERROR_TOO_MANY_SKILLS: 'Com {count} habilidades, a Meta de dificuldade deve somar pelo menos {needed} (cada habilidade recebe pelo menos {min} questões). Aumente a meta ou remova uma habilidade.', + ERROR_SKILL_LEVELS_SHORT: 'Não há questões suficientes nos níveis de dificuldade escolhidos para: {skills}. Cada habilidade precisa fornecer pelo menos 2 questões nesses níveis.', + DIFFICULTY_EASY: 'Fácil', + DIFFICULTY_MEDIUM: 'Médio', + DIFFICULTY_DIFFICULT: 'Difícil', + DYNAMIC_ASSESS_STALE_TITLE: 'Configurações alteradas desde que as questões foram geradas', + DYNAMIC_ASSESS_STALE_SUB: 'As questões não correspondem à Habilidade e à Meta de dificuldade atuais. Clique em Gerar novamente para atualizá-las.', + DYNAMIC_ASSESS_STALE_SUB_READONLY: 'A Habilidade ou a Meta de dificuldade não corresponde mais às questões geradas. Solicite alterações para que o criador as gere novamente.', + DYNAMIC_ASSESS_STALE_TIP: 'Configurações alteradas — gere as questões novamente primeiro', + ERROR_DYNAMIC_ASSESS_STALE: 'A Habilidade ou a Meta de dificuldade mudou desde que as questões foram geradas. Gere-as novamente e depois envie para revisão.', + ERROR_DYNAMIC_ASSESS_STALE_REVIEW: 'As questões não correspondem à Habilidade ou à Meta de dificuldade atuais. Solicite alterações para que o criador as gere novamente.', }; diff --git a/src/i18n/translations.ta.ts b/src/i18n/translations.ta.ts index afa0aef..b6509e9 100644 --- a/src/i18n/translations.ta.ts +++ b/src/i18n/translations.ta.ts @@ -205,4 +205,37 @@ export const TRANSLATIONS_TA: Record = { TRANSCRIPTS_LOAD_ERROR_TITLE: 'டிரான்ஸ்கிரிப்ட்களை ஏற்ற முடியவில்லை', NO_TRANSCRIPTS_TITLE: 'இதுவரை டிரான்ஸ்கிரிப்ட் இல்லை', NO_TRANSCRIPTS_SUB: 'இந்த வீடியோ வெளியிடப்பட்டவுடன், அதன் டிரான்ஸ்கிரிப்ட்டை இங்கே அங்கீகரிக்கவோ, மாற்றியமைக்கவோ அல்லது நிராகரிக்கவோ முடியும்.', + + /* Dynamic Assess */ + TOAST_DYNAMIC_ASSESS_REFRESH_DONE: 'கேள்விகள் உருவாக்கப்பட்டன', + TOAST_DYNAMIC_ASSESS_PENDING: 'கேள்விகள் இன்னும் தோன்றவில்லை. உருவாக்கம் இன்னும் நடந்துகொண்டிருக்கலாம், அல்லது தோல்வியடைந்திருக்கலாம் (எ.கா., ஒரு திறனுக்குப் போதுமான கேள்விகள் இல்லை). சிறிது நேரம் கழித்து இந்த உள்ளடக்கத்தை மீண்டும் திறக்கவும், அல்லது கேள்வித் தொகுப்பைச் சரிபார்த்து மீண்டும் முயற்சிக்கவும்.', + SAVE_AND_GENERATE: 'சேமித்து உருவாக்கு', + REGENERATE_QUESTIONS: 'மீண்டும் உருவாக்கு', + REGENERATE_QUESTIONS_HINT: 'அதே திறன் மற்றும் கடினத்தன்மை இலக்குக்கு புதிய சீரற்ற கேள்வித் தொகுப்பைத் தேர்ந்தெடு', + DYNAMIC_ASSESS_GENERATING_TITLE: 'கேள்விகள் உருவாக்கப்படுகின்றன', + DYNAMIC_ASSESS_GENERATING_SUB: 'தேர்ந்தெடுத்த திறன்கள் மற்றும் கடினத்தன்மைக்கேற்ப கேள்வித் தொகுப்பிலிருந்து கேள்விகள் தேர்ந்தெடுக்கப்படுகின்றன. இதற்கு பொதுவாக சில விநாடிகள் ஆகும்.', + DYNAMIC_ASSESS_GENERATE_FIRST: 'மதிப்பாய்வுக்கு அனுப்பும் முன் கேள்விகளை உருவாக்கவும்', + DYNAMIC_ASSESS_EMPTY_TITLE: 'இதுவரை கேள்விகள் எதுவும் உருவாக்கப்படவில்லை', + DYNAMIC_ASSESS_EMPTY_SUB: 'விவரங்களைத் திருத்து என்பதைத் திறந்து, திறன் மற்றும் கடினத்தன்மை இலக்கை அமைத்து, கேள்விகளை உருவாக்கச் சேமிக்கவும்.', + DYNAMIC_ASSESS_FRAMEWORK: 'கட்டமைப்பு', + DYNAMIC_ASSESS_SELECT_FRAMEWORK: 'கட்டமைப்பைத் தேர்ந்தெடு', + DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'முதலில் ஒரு கட்டமைப்பைத் தேர்ந்தெடுக்கவும்', + DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'இந்த உள்ளடக்கத்திற்கு இதுவரை கேள்விகள் எதுவும் உருவாக்கப்படவில்லை.', + ERROR_DYNAMIC_ASSESS_INPUTS: 'கேள்விகளை உருவாக்கும் முன் திறன் மற்றும் கடினத்தன்மை இலக்கை அமைக்கவும்.', + ERROR_POOL_INSUFFICIENT: 'தேர்ந்தெடுத்த திறன்களுக்குப் போதுமான கேள்விகள் இல்லை', + ERROR_POOL_CHECK_FAILED: 'கேள்விகள் கிடைப்பதைச் சரிபார்க்க முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', + ERROR_POOL_SHORTFALL: '{level}: கோரியது {requested}, தேவை {needed}, கிடைப்பது {available}', + ERROR_SKILL_POOL_TOO_SMALL: 'ஒவ்வொரு திறனுக்கும் குறைந்தது {needed} வெளியிடப்பட்ட கேள்விகள் தேவை. இவற்றுக்குப் போதுமானவை இல்லை: {skills}', + ERROR_DYNAMIC_ASSESS_SUBMIT_STALE: 'திறன் அல்லது கடினத்தன்மை இலக்கு மாற்றப்பட்டது. இதை மூடி, விவரங்களைத் திருத்து என்பதில் சேமித்து உருவாக்கு மூலம் கேள்விகளை உருவாக்கி, பின்னர் மதிப்பாய்வுக்கு அனுப்பவும்.', + ERROR_TOO_MANY_SKILLS: '{count} திறன்களுடன், கடினத்தன்மை இலக்கின் கூட்டுத்தொகை குறைந்தது {needed} ஆக இருக்க வேண்டும் (ஒவ்வொரு திறனுக்கும் குறைந்தது {min} கேள்விகள்). இலக்கை அதிகரிக்கவும் அல்லது ஒரு திறனை நீக்கவும்.', + ERROR_SKILL_LEVELS_SHORT: 'தேர்ந்தெடுத்த கடினத்தன்மை நிலைகளில் இவற்றுக்குப் போதுமான கேள்விகள் இல்லை: {skills}. ஒவ்வொரு திறனும் அந்த நிலைகளில் குறைந்தது 2 கேள்விகளை வழங்க வேண்டும்.', + DIFFICULTY_EASY: 'எளிது', + DIFFICULTY_MEDIUM: 'நடுத்தரம்', + DIFFICULTY_DIFFICULT: 'கடினம்', + DYNAMIC_ASSESS_STALE_TITLE: 'கேள்விகள் உருவாக்கப்பட்ட பிறகு அமைப்புகள் மாற்றப்பட்டுள்ளன', + DYNAMIC_ASSESS_STALE_SUB: 'கேள்விகள் தற்போதைய திறன் மற்றும் கடினத்தன்மை இலக்குடன் பொருந்தவில்லை. அவற்றைப் புதுப்பிக்க மீண்டும் உருவாக்கு என்பதைக் கிளிக் செய்யவும்.', + DYNAMIC_ASSESS_STALE_SUB_READONLY: 'திறன் அல்லது கடினத்தன்மை இலக்கு உருவாக்கப்பட்ட கேள்விகளுடன் இனி பொருந்தவில்லை. உருவாக்குநர் அவற்றை மீண்டும் உருவாக்க மாற்றங்களைக் கோரவும்.', + DYNAMIC_ASSESS_STALE_TIP: 'அமைப்புகள் மாற்றப்பட்டன — முதலில் கேள்விகளை மீண்டும் உருவாக்கவும்', + ERROR_DYNAMIC_ASSESS_STALE: 'கேள்விகள் உருவாக்கப்பட்ட பிறகு திறன் அல்லது கடினத்தன்மை இலக்கு மாற்றப்பட்டுள்ளது. அவற்றை மீண்டும் உருவாக்கி, பின்னர் மதிப்பாய்வுக்கு அனுப்பவும்.', + ERROR_DYNAMIC_ASSESS_STALE_REVIEW: 'கேள்விகள் தற்போதைய திறன் அல்லது கடினத்தன்மை இலக்குடன் பொருந்தவில்லை. உருவாக்குநர் அவற்றை மீண்டும் உருவாக்க மாற்றங்களைக் கோரவும்.', }; diff --git a/src/icons.tsx b/src/icons.tsx index 6937258..35e17d0 100644 --- a/src/icons.tsx +++ b/src/icons.tsx @@ -31,6 +31,12 @@ export const CloseIcon: React.FC

= ({ size = 13, className }) => ( export const SendIcon: React.FC

= ({ size = 13, className }) => ( ); +export const RefreshIcon: React.FC

= ({ size = 13, className }) => ( + + + + +); export const PencilIcon: React.FC

= ({ size = 12, className }) => ( @@ -54,6 +60,9 @@ export const ImageIcon: React.FC

= ({ size = 16, className }) => ( export const CheckIcon: React.FC

= ({ size = 15, className }) => ( ); +export const InfoIcon: React.FC

= ({ size = 16, className }) => ( + +); export const VideoIcon: React.FC

= ({ size = 16, className }) => ( ); diff --git a/src/poolPlan.test.ts b/src/poolPlan.test.ts new file mode 100644 index 0000000..1002dcf --- /dev/null +++ b/src/poolPlan.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect } from 'vitest'; +import { planPool } from './poolPlan'; + +const counts = (table: Record>>) => (s: string, l: 'E' | 'M' | 'D') => table[s]?.[l] ?? 0; + +describe('planPool (mirrors the job allocation)', () => { + it('accepts settings the job can fill (negative)', () => { + expect(planPool(['Physics'], { E: 2, M: 2, D: 2 }, counts({ Physics: { E: 10, M: 10, D: 10 } }), 2, 3)) + .toEqual({ infeasible: false, uncovered: [], shortSkills: [] }); + }); + + it('flags minCriteria x skills above the target total as infeasible (positive)', () => { + expect(planPool(['A', 'B', 'C', 'D'], { E: 1, M: 1, D: 1 }, counts({}), 2, 3).infeasible).toBe(true); + }); + + it('counts each skill bucket as floor(count / multiplier), not the union of skills (positive)', () => { + // 4 + 5 Easy items = 9 >= 3 x 3 in total, but the job can only draw 1 + 1 = 2 learners' worth. + const plan = planPool(['A', 'B'], { E: 4, M: 0, D: 0 }, counts({ A: { E: 4 }, B: { E: 5 } }), 2, 3); + expect(plan.uncovered).toEqual([{ level: 'E', covered: 2, target: 4 }]); + }); + + it('reports a skill that cannot reserve its own minimum at the requested levels (positive)', () => { + const plan = planPool(['A', 'B'], { E: 4, M: 0, D: 0 }, counts({ A: { E: 30 }, B: { D: 30 } }), 2, 3); + expect(plan.shortSkills).toEqual(['B']); + }); + + it('reserves the most constrained skill first, like the job (negative)', () => { + // B only has Easy; A has every level. B must get its Easy reservation before A takes Easy. + const plan = planPool(['A', 'B'], { E: 2, M: 2, D: 0 }, counts({ A: { E: 30, M: 30, D: 30 }, B: { E: 6 } }), 2, 3); + expect(plan).toEqual({ infeasible: false, uncovered: [], shortSkills: [] }); + }); +}); diff --git a/src/poolPlan.ts b/src/poolPlan.ts new file mode 100644 index 0000000..ba55bd0 --- /dev/null +++ b/src/poolPlan.ts @@ -0,0 +1,78 @@ +/** Mirrors knowlg-publish DynamicAssessHelper.isFeasible / allocate / uncoveredLevels, so the editor only lets through settings the job can actually generate. */ + +export const PLAN_LEVELS = ['E', 'M', 'D'] as const; +export type PlanLevel = typeof PLAN_LEVELS[number]; + +export interface PoolPlan { + /** minCriteria x skills exceeds the E+M+D total (the job's feasibility check). */ + infeasible: boolean; + /** Levels the allocation can't fill: covered is in learner questions (each needs multiplier x in the pool). */ + uncovered: Array<{ level: PlanLevel; covered: number; target: number }>; + /** Skills that can't get their own minCriteria; the job would generate a pool without them. */ + shortSkills: string[]; +} + +export function planPool( + skills: string[], + target: Partial>, + liveCount: (skill: string, level: PlanLevel) => number, + minCriteria: number, + multiplier: number, +): PoolPlan { + const want = (l: PlanLevel) => Math.max(0, Number(target[l]) || 0); + const total = PLAN_LEVELS.reduce((sum, l) => sum + want(l), 0); + if (total <= 0 || skills.length === 0 || minCriteria * skills.length > total) { + return { infeasible: true, uncovered: [], shortSkills: [] }; + } + // A bucket can only supply count / multiplier, so every selection has multiplier x its size to draw from. + const avail = (s: string, l: PlanLevel) => (multiplier > 0 ? Math.floor(Math.max(0, liveCount(s, l)) / multiplier) : liveCount(s, l)); + const remaining: Record = { E: want('E'), M: want('M'), D: want('D') }; + const allocated = new Map(); + const key = (s: string, l: PlanLevel) => `${s}\u0000${l}`; + const got = (s: string, l: PlanLevel) => allocated.get(key(s, l)) ?? 0; + const add = (s: string, l: PlanLevel, n: number) => allocated.set(key(s, l), got(s, l) + n); + const shortSkills: string[] = []; + + // Step 1: reserve minCriteria per skill, most-constrained first (stable, like Scala's sortBy). + const ordered = skills + .map((s, i) => ({ s, i, feasible: PLAN_LEVELS.filter((l) => avail(s, l) > 0).length })) + .sort((a, b) => a.feasible - b.feasible || a.i - b.i) + .map((x) => x.s); + for (const s of ordered) { + let toReserve = minCriteria; + for (const l of PLAN_LEVELS) { + if (toReserve > 0 && remaining[l] > 0) { + const take = Math.min(toReserve, remaining[l], Math.max(0, avail(s, l) - got(s, l))); + if (take > 0) { add(s, l, take); remaining[l] -= take; toReserve -= take; } + } + } + if (toReserve > 0) shortSkills.push(s); + } + + // Step 2: share the remainder by availability, then give rounding leftovers to any skill with spare. + for (const l of PLAN_LEVELS) { + let remainder = remaining[l]; + if (remainder <= 0) continue; + const spare = (s: string) => Math.max(0, avail(s, l) - got(s, l)); + const totalAvailable = skills.reduce((sum, s) => sum + spare(s), 0); + if (totalAvailable <= 0) continue; + const startingRemainder = remainder; + const spareAtStart = new Map(skills.map((s) => [s, spare(s)])); + for (const s of skills) { + if (remainder <= 0) break; + const share = Math.min(remainder, Math.max(0, Math.round((startingRemainder * (spareAtStart.get(s) ?? 0)) / totalAvailable))); + const capped = Math.min(share, spareAtStart.get(s) ?? 0); + if (capped > 0) { add(s, l, capped); remainder -= capped; } + } + for (const s of skills) { + if (remainder <= 0) break; + const take = Math.min(remainder, spare(s)); + if (take > 0) { add(s, l, take); remainder -= take; } + } + } + + const uncovered = PLAN_LEVELS + .map((l) => ({ level: l, covered: skills.reduce((sum, s) => sum + got(s, l), 0), target: want(l) })) + .filter((x) => x.covered < x.target); + return { infeasible: false, uncovered, shortSkills }; +} diff --git a/src/services/ContentEditorService.test.ts b/src/services/ContentEditorService.test.ts index f58645c..a4b9dd8 100644 --- a/src/services/ContentEditorService.test.ts +++ b/src/services/ContentEditorService.test.ts @@ -22,6 +22,131 @@ describe('normalizeContent', () => { }); }); +describe('ContentEditorService.readFormFields subType resolution', () => { + it('requests the generic "resource" subType for ordinary content categories (negative)', async () => { + const savedFetch = globalThis.fetch; + let capturedBody: Record | undefined; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + capturedBody = JSON.parse(String(init?.body)); + return { ok: true, json: async () => ({ responseCode: 'OK', result: { form: { data: { fields: [] } } } }) }; + }) as unknown as typeof fetch; + try { + await new ContentEditorService().readFormFields('Learning Resource', 'save'); + expect((capturedBody?.request as Record).subType).toBe('resource'); + } finally { + globalThis.fetch = savedFetch; + } + }); + + it('requests its own subType for Dynamic Course Assessment content, not the generic one (positive)', async () => { + const savedFetch = globalThis.fetch; + let capturedBody: Record | undefined; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + capturedBody = JSON.parse(String(init?.body)); + return { ok: true, json: async () => ({ responseCode: 'OK', result: { form: { data: { fields: [] } } } }) }; + }) as unknown as typeof fetch; + try { + await new ContentEditorService().readFormFields('Dynamic Course Assessment', 'save'); + expect((capturedBody?.request as Record).subType).toBe('Dynamic Course Assessment'); + } finally { + globalThis.fetch = savedFetch; + } + }); +}); + +describe('ContentEditorService.refreshContentBody', () => { + it('sends lastPublishedBy under request.content, which the refresh-body API requires (positive)', async () => { + const savedFetch = globalThis.fetch; + let captured: { url?: string; body?: Record } = {}; + globalThis.fetch = (async (url: string, init?: RequestInit) => { + captured = { url, body: JSON.parse(String(init?.body)) }; + return { ok: true, json: async () => ({ responseCode: 'OK', result: {} }) }; + }) as unknown as typeof fetch; + try { + await new ContentEditorService().refreshContentBody('do_1', 'u1'); + expect(captured.url).toContain('content/v3/refresh/body/do_1'); + expect(captured.body).toEqual({ request: { content: { lastPublishedBy: 'u1' } } }); + } finally { + globalThis.fetch = savedFetch; + } + }); +}); + +describe('ContentEditorService.searchSkillPoolCounts', () => { + it('counts Live AssessmentItems per skill with the same filters as knowlg-service (no channel, any level) (positive)', async () => { + const savedFetch = globalThis.fetch; + const filters: Array> = []; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + const f = JSON.parse(String(init?.body)).request.filters; + filters.push(f); + return { ok: true, json: async () => ({ responseCode: 'OK', result: { count: f.skill[0] === 'Azure' ? 2 : 30 } }) }; + }) as unknown as typeof fetch; + try { + expect(await new ContentEditorService().searchSkillPoolCounts(['Physics', 'Azure'])).toEqual({ Physics: 30, Azure: 2 }); + for (const f of filters) { + expect(f).toMatchObject({ status: ['Live'], objectType: 'AssessmentItem' }); + expect(f).not.toHaveProperty('channel'); + expect(f).not.toHaveProperty('qlevel'); + } + } finally { + globalThis.fetch = savedFetch; + } + }); +}); + +describe('ContentEditorService.searchAssessmentItemBucketCounts', () => { + it('counts Live AssessmentItems per skill x level with channel and category, like the job (positive)', async () => { + const savedFetch = globalThis.fetch; + const filters: Array> = []; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + const f = JSON.parse(String(init?.body)).request.filters; + filters.push(f); + const n = { EASY: 4, MEDIUM: 2, DIFFICULT: 1 }[f.qlevel as string] ?? 0; + return { ok: true, json: async () => ({ responseCode: 'OK', result: { count: f.topic[0] === 'A' ? n : n * 10 } }) }; + }) as unknown as typeof fetch; + try { + const counts = await new ContentEditorService().searchAssessmentItemBucketCounts(['A', 'B'], 'ch1', 'topic'); + expect(counts).toEqual({ A: { E: 4, M: 2, D: 1 }, B: { E: 40, M: 20, D: 10 } }); + expect(filters).toHaveLength(6); + for (const f of filters) expect(f).toMatchObject({ status: ['Live'], objectType: 'AssessmentItem', channel: 'ch1' }); + } finally { + globalThis.fetch = savedFetch; + } + }); + + it('makes no calls when no skills are given (negative)', async () => { + const savedFetch = globalThis.fetch; + let called = false; + globalThis.fetch = (async () => { called = true; return { ok: true, json: async () => ({}) }; }) as unknown as typeof fetch; + try { + expect(await new ContentEditorService().searchAssessmentItemBucketCounts([])).toEqual({}); + expect(called).toBe(false); + } finally { + globalThis.fetch = savedFetch; + } + }); +}); +describe('ContentEditorService.readContent body field', () => { + const capture = async (call: (s: ContentEditorService) => Promise) => { + const savedFetch = globalThis.fetch; + let capturedUrl = ''; + globalThis.fetch = (async (url: string) => { + capturedUrl = url; + return { ok: true, json: async () => ({ responseCode: 'OK', result: { content: { identifier: 'do_1' } } }) }; + }) as unknown as typeof fetch; + try { await call(new ContentEditorService()); } finally { globalThis.fetch = savedFetch; } + return new URL(capturedUrl, 'http://x').searchParams.get('fields')?.split(',') ?? []; + }; + + it('does not request body by default, so ordinary content reads what it always did (negative)', async () => { + expect(await capture((s) => s.readContent('do_1'))).not.toContain('body'); + }); + + it('requests body only when asked, for Dynamic Assess (positive)', async () => { + expect(await capture((s) => s.readContent('do_1', 'edit', { withBody: true }))).toContain('body'); + }); +}); + describe('ContentEditorService.readContent caching', () => { it('reads with cache: no-store - this page re-reads its own content right after mutating it (save/publish/reject)', async () => { const savedFetch = globalThis.fetch; diff --git a/src/services/ContentEditorService.ts b/src/services/ContentEditorService.ts index 726c047..3b1ddc0 100644 --- a/src/services/ContentEditorService.ts +++ b/src/services/ContentEditorService.ts @@ -1,6 +1,9 @@ /** ContentEditorService — backend abstraction for the editor; calls go to relative `/action/...` (proxied to knowledge-mw/Kong) by default, overridable via EditorConfig. */ import type { ContentData, EditorContext, EditorConfig, FrameworkCategory, FormField, AssetItem, RawTranscript } from '../types'; +/** Keep in sync with useEditor.ts's DYNAMIC_ASSESS_CATEGORY (not imported: the modules don't otherwise depend on each other). */ +const DYNAMIC_ASSESS_ECML_CATEGORY = 'Dynamic Course Assessment'; + const DEFAULT_ENDPOINTS = { /* Versions verified against the portal's ContentService, the old generic editor, and the backend proxy; all hit /action → knowledge-mw. */ create: 'content/v3/create', @@ -28,6 +31,8 @@ const DEFAULT_ENDPOINTS = { transcriptReject: 'content/v4/enrichment/object/reject', /* v1, not v3 - only v1+enrich=all via the /portal/* proxy route is confirmed to return enrichment.transcripts (see readTranscripts()'s own comment). */ transcriptsRead: 'content/v1/read', + /* Dynamic Assess — triggers the knowlg-publish job's pool-based question selection. */ + refreshBody: 'content/v3/refresh/body', } as const; export type EndpointMap = Partial; @@ -36,7 +41,9 @@ const READ_FIELDS = [ 'name', 'description', 'mimeType', 'contentType', 'primaryCategory', 'resourceType', 'status', 'artifactUrl', 'streamingUrl', 'downloadUrl', 'appIcon', 'posterImage', 'framework', 'board', 'medium', 'gradeLevel', 'subject', 'keywords', 'collaborators', - 'createdBy', 'creator', 'versionKey', 'pkgVersion', 'rejectReasons', 'rejectComment', + 'createdBy', 'creator', 'versionKey', 'pkgVersion', 'rejectReasons', 'rejectComment', 'channel', + /* Dynamic Assess fields (absent on other content); the knowlg-publish job sets totalQuestions and lastUpdatedOn. */ + 'skill', 'difficultyTarget', 'totalQuestions', 'lastUpdatedOn', ].join(','); function toArray(val: unknown): string[] | undefined { @@ -64,6 +71,7 @@ export function normalizeContent(raw: Record): ContentData { collaborators: toArray(raw.collaborators), rejectReasons: toArray(raw.rejectReasons), board: typeof raw.board === 'string' ? raw.board : toArray(raw.board)?.[0], + skill: toArray(raw.skill), } as ContentData; } @@ -173,8 +181,10 @@ export class ContentEditorService { /** GET content/v3/read/{id}?mode=edit — no-store, since this page re-reads its own content right after * mutating it; also sends Cache-Control: no-cache so an intermediary gateway cache (e.g. Kong's * proxy-cache plugin, which honors this request header) doesn't serve a pre-mutation response. */ - async readContent(contentId: string, mode = 'edit'): Promise { - const path = `${this.ep.read}/${encodeURIComponent(contentId)}?mode=${mode}&fields=${READ_FIELDS}`; + async readContent(contentId: string, mode = 'edit', opts: { withBody?: boolean } = {}): Promise { + // body is opt-in (only Dynamic Assess needs it), so other content reads exactly the fields it always did. + const fields = opts.withBody ? `${READ_FIELDS},body` : READ_FIELDS; + const path = `${this.ep.read}/${encodeURIComponent(contentId)}?mode=${mode}&fields=${fields}`; const result = await this.request<{ content: Record }>('GET', path, undefined, { cache: 'no-store', headers: { 'Cache-Control': 'no-cache' }, @@ -201,6 +211,13 @@ export class ContentEditorService { }); } + /** POST content/v3/refresh/body/{id}: queues pool-based question selection; the API rejects a blank lastPublishedBy, same body shape as publish. */ + async refreshContentBody(contentId: string, lastPublishedBy: string): Promise { + return this.request('POST', `${this.ep.refreshBody}/${encodeURIComponent(contentId)}`, { + request: { content: { lastPublishedBy } }, + }); + } + /** POST content/v4/enrichment/object/create/{id} — kicks off async transcript generation. */ async createTranscript(contentId: string): Promise<{ identifier?: string; transcriptId?: string; message?: string }> { return this.request('POST', `${this.ep.transcriptCreate}/${encodeURIComponent(contentId)}`, { @@ -327,7 +344,7 @@ export class ContentEditorService { /** Fetches form field definitions for a content type + action, mirroring the old generic editor's payload, and returns them sorted by `index`. */ async readFormFields( - _subtype: string, + subtype: string, action: 'save' | 'review' | 'publish', opts: { framework?: string; rootOrgId?: string } = {}, ): Promise { @@ -335,9 +352,8 @@ export class ContentEditorService { const result = await this.request('POST', this.ep.form, { request: { type: 'content', - // Form config is keyed on a fixed subType ('resource'), not the content's - // primaryCategory — matches the old generic editor's form/read call. - subType: 'resource', + // Fixed 'resource' subType like the old editor, except Dynamic Assess, whose fields live on a form under its own category. + subType: subtype === DYNAMIC_ASSESS_ECML_CATEGORY ? subtype : 'resource', action, framework: opts.framework ?? '*', rootOrgId: opts.rootOrgId ?? '*', @@ -432,6 +448,51 @@ export class ContentEditorService { }); } + /** Live AssessmentItem counts per skill x level, the availability the job allocates from (same channel + category filters). */ + async searchAssessmentItemBucketCounts( + skills: string[], + channel?: string, + categoryField = 'skill', + ): Promise>> { + const levels = [['E', 'EASY'], ['M', 'MEDIUM'], ['D', 'DIFFICULT']] as const; + const pairs = skills.flatMap((skill) => levels.map(([key, qlevel]) => ({ skill, key, qlevel }))); + // limit 1: `count` reflects the total matches regardless of limit. + const results = await Promise.all(pairs.map(({ skill, qlevel }) => { + const filters: Record = { status: ['Live'], objectType: 'AssessmentItem', [categoryField]: [skill], qlevel }; + if (channel) filters.channel = channel; + return this.request<{ count?: number }>('POST', this.ep.compositeSearch, { request: { filters, fields: ['identifier'], limit: 1 } }); + })); + const out: Record> = {}; + pairs.forEach(({ skill, key }, i) => { + out[skill] = out[skill] ?? { E: 0, M: 0, D: 0 }; + out[skill][key] = Number(results[i]?.count ?? 0) || 0; + }); + return out; + } + + /** Live AssessmentItems per skill, with the same filters knowlg-service uses to reject a refresh (no channel, any level). */ + async searchSkillPoolCounts(skills: string[], categoryField = 'skill'): Promise> { + const results = await Promise.all(skills.map((skill) => this.request<{ count?: number }>( + 'POST', + this.ep.compositeSearch, + { request: { filters: { status: ['Live'], objectType: 'AssessmentItem', [categoryField]: [skill] }, fields: ['identifier'], limit: 1 } }, + ))); + return Object.fromEntries(skills.map((skill, i) => [skill, Number(results[i]?.count ?? 0) || 0])); + } + + /** Live system-default frameworks for the Framework picker, channel-scoped via X-Channel-Id, same as question-set editor-v2's searchFrameworks. */ + async searchFrameworks(channel?: string): Promise> { + const result = await this.request<{ Framework?: Array> }>( + 'POST', + this.ep.compositeSearch, + { request: { filters: { objectType: 'Framework', status: ['Live'], systemDefault: 'Yes' } } }, + channel ? { headers: { 'X-Channel-Id': channel } } : undefined, + ); + return (result?.Framework ?? []) + .map((f) => ({ identifier: String(f.identifier ?? ''), name: String(f.name ?? f.identifier ?? '') })) + .filter((f) => f.identifier); + } + /** Creates an image Asset record then uploads the file to it (asset/v1/create → asset/v1/upload/{id}), returning the artifact URL. */ async uploadImageAsset(file: File, context: EditorContext): Promise { const created = await this.request<{ identifier?: string; node_id?: string }>( diff --git a/src/taxonomy.test.ts b/src/taxonomy.test.ts index 1ec00b6..336d25a 100644 --- a/src/taxonomy.test.ts +++ b/src/taxonomy.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { cascadedOptions, categoryTerms } from './taxonomy'; +import { cascadedOptions, categoryTerms, deepestCategoryCode } from './taxonomy'; import type { FrameworkCategory } from './types'; const categories: FrameworkCategory[] = [ @@ -55,3 +55,18 @@ describe('taxonomy', () => { expect(categoryTerms(categories, 'board').map((o) => o.name)).toEqual(['CBSE', 'ICSE']); }); }); + +describe('deepestCategoryCode', () => { + it('picks the highest-index category regardless of array order or name (positive)', () => { + const cats = [ + { code: 'topic', name: 'Topic', index: 3, terms: [] }, + { code: 'board', name: 'Board', index: 1, terms: [] }, + { code: 'subject', name: 'Subject', index: 2, terms: [] }, + ] as FrameworkCategory[]; + expect(deepestCategoryCode(cats)).toBe('topic'); + }); + + it('is undefined before the framework has loaded (negative)', () => { + expect(deepestCategoryCode([])).toBeUndefined(); + }); +}); diff --git a/src/taxonomy.ts b/src/taxonomy.ts index bf18760..7db3470 100644 --- a/src/taxonomy.ts +++ b/src/taxonomy.ts @@ -6,6 +6,12 @@ export interface TermOption { name: string; } +/** Highest-index category code, same as the knowlg-publish job's resolveCategoryCode; undefined until categories load. */ +export function deepestCategoryCode(categories: FrameworkCategory[]): string | undefined { + if (!categories.length) return undefined; + return categories.reduce((a, b) => ((b.index ?? 0) > (a.index ?? 0) ? b : a)).code; +} + /** All option names for a category. */ export function categoryTerms(categories: FrameworkCategory[], code: string): TermOption[] { const cat = categories.find((c) => c.code === code); diff --git a/src/test/mockEd.ts b/src/test/mockEd.ts index 3089905..da6ca20 100644 --- a/src/test/mockEd.ts +++ b/src/test/mockEd.ts @@ -29,6 +29,9 @@ export function mockService(over: Record = {}): ContentEditorSe return { searchUsers: vi.fn().mockResolvedValue([]), searchImageAssets: vi.fn().mockResolvedValue([]), + searchAssessmentItemBucketCounts: vi.fn().mockImplementation(async (skills: string[]) => Object.fromEntries(skills.map((s) => [s, { E: 100, M: 100, D: 100 }]))), + searchSkillPoolCounts: vi.fn().mockImplementation(async (skills: string[]) => Object.fromEntries(skills.map((s) => [s, 100]))), + searchFrameworks: vi.fn().mockResolvedValue([]), uploadImageAsset: vi.fn().mockResolvedValue('https://cdn/img.png'), readForm: vi.fn().mockResolvedValue([]), readFormFields: vi.fn().mockResolvedValue([]), diff --git a/src/types.ts b/src/types.ts index 585e9ad..a0f3023 100644 --- a/src/types.ts +++ b/src/types.ts @@ -82,6 +82,9 @@ export interface ContentData { pkgVersion?: number; rejectReasons?: string[]; rejectComment?: string; + /** Dynamic Assess custom fields (Dynamic Course Assessment category only). */ + skill?: string[]; + difficultyTarget?: { E?: number; M?: number; D?: number }; /** Any extra fields returned by content read. */ [key: string]: unknown; } diff --git a/src/useEditor.test.ts b/src/useEditor.test.ts index bb21e1c..18f1c4e 100644 --- a/src/useEditor.test.ts +++ b/src/useEditor.test.ts @@ -236,3 +236,317 @@ describe('useEditor — transcript generation on upload', () => { expect(service.createTranscript).not.toHaveBeenCalled(); }); }); + +describe('Dynamic Assess content view gating', () => { + it('lands on the player view with no artifactUrl, unlike ordinary content (positive)', async () => { + const service = svc(); + const result = await mountWithContent(service, videoContent({ + identifier: 'do_dynamic_assess_1', + mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', + artifactUrl: undefined, + })); + expect(result.current.view).toBe('player'); + }); + + it('ordinary content with no artifactUrl still lands on the upload view (negative)', async () => { + const service = svc(); + const result = await mountWithContent(service, videoContent({ artifactUrl: undefined })); + expect(result.current.view).toBe('upload'); + }); + + it('auto-opens the metadata drawer on load in edit mode (positive)', async () => { + const service = svc(); + const result = await mountWithContent(service, videoContent({ + identifier: 'do_dynamic_assess_2', + mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', + status: 'Draft', + artifactUrl: undefined, + })); + await waitFor(() => expect(result.current.drawer).toBe('metadata')); + }); + + it('reads the body (generated questions) for Dynamic Assess content (positive)', async () => { + const service = svc(); + await mountWithContent(service, videoContent({ identifier: 'do_da_body', primaryCategory: 'Dynamic Course Assessment', artifactUrl: undefined })); + expect(service.readContent).toHaveBeenCalledWith('do_da_body', 'edit', { withBody: true }); + }); + + it('never reads the body for ordinary content (negative)', async () => { + const service = svc(); + await mountWithContent(service, videoContent({ artifactUrl: 'https://cdn/video.mp4' })); + for (const call of (service.readContent as ReturnType).mock.calls) expect(call[2]).toBeUndefined(); + }); + + it('does not auto-open the metadata drawer for ordinary content (negative)', async () => { + const service = svc(); + const result = await mountWithContent(service, videoContent({ artifactUrl: 'https://cdn/video.mp4' })); + expect(result.current.drawer).toBeNull(); + }); +}); + +describe('useEditor — Dynamic Assess refreshBody polling', () => { + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_1', mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', status: 'Draft', + totalQuestions: 3, lastUpdatedOn: 't0', + skill: ['Physics'], difficultyTarget: '{"E":1,"M":1,"D":1}', ...over, + } as Partial); + + it('blocks Generate with a clear message when Skill is not saved, instead of a misleading wait (positive)', async () => { + const refreshContentBody = vi.fn(); + const service = svc({ refreshContentBody }); + const result = await mountWithContent(service, daContent({ skill: [] })); + await act(async () => { await result.current.refreshBody(); }); + expect(refreshContentBody).not.toHaveBeenCalled(); + expect(result.current.toast?.msg).toBe('Set Skill and Difficulty Target before generating questions.'); + expect(result.current.dynamicAssessRefreshing).toBe(false); + }); + + it('blocks Generate when every difficulty count is zero (negative)', async () => { + const refreshContentBody = vi.fn(); + const service = svc({ refreshContentBody }); + const result = await mountWithContent(service, daContent({ difficultyTarget: '{"E":0,"M":0,"D":0}' })); + await act(async () => { await result.current.refreshBody(); }); + expect(refreshContentBody).not.toHaveBeenCalled(); + }); + + it('detects a regenerate that keeps the same count via lastUpdatedOn, without needing a publish (positive)', async () => { + const refreshContentBody = vi.fn().mockResolvedValue({}); + const service = svc({ refreshContentBody }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + const readContent = service.readContent as ReturnType; + readContent + .mockResolvedValueOnce(daContent()) // baseline + .mockResolvedValueOnce(daContent()) // poll 1: job not done + .mockResolvedValue(daContent({ lastUpdatedOn: 't1' })); // poll 2: job wrote + + await act(async () => { await result.current.refreshBody(); }); + expect(refreshContentBody).toHaveBeenCalledWith('do_da_1', 'u1'); // logged-in user as lastPublishedBy + expect(result.current.dynamicAssessRefreshing).toBe(true); + + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(result.current.dynamicAssessRefreshing).toBe(true); + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + expect(result.current.toast?.msg).toBe('Questions generated'); + expect(result.current.content?.pkgVersion ?? 0).toBe(0); // still an unpublished Draft + } finally { + vi.useRealTimers(); + } + }); + + it('says generation is still in progress, not done, when nothing changes before the poll limit (negative)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + await act(async () => { await result.current.refreshBody(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000 * 21); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + expect(result.current.toast?.msg).toMatch(/haven't appeared yet/); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('useEditor — Dynamic Assess refreshBody timeout', () => { + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_t', mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', status: 'Draft', + totalQuestions: 0, lastUpdatedOn: 't0', + skill: ['Physics'], difficultyTarget: '{"E":1,"M":1,"D":1}', ...over, + } as Partial); + + it('shows what the server has after the poll limit, even when the job wrote before the baseline read (positive)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + // The job finished before the baseline read, so no poll ever sees a change. + (service.readContent as ReturnType).mockResolvedValue(daContent({ totalQuestions: 3, lastUpdatedOn: 't1' })); + await act(async () => { await result.current.refreshBody(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000 * 21); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + expect(result.current.content?.totalQuestions).toBe(3); + expect(result.current.hasGeneratedBody).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it('still says pending, and clears the loader, when the last read fails (negative)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + (service.readContent as ReturnType).mockRejectedValue(new Error('down')); + await act(async () => { await result.current.refreshBody(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000 * 21); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + expect(result.current.toast?.msg).toMatch(/haven't appeared yet/); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('useEditor — Save also generates when needed', () => { + const generatedBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 1, M: 0, D: 0 } } }) } } }] }, + }); + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_2', mimeType: 'application/vnd.ekstep.ecml-archive', primaryCategory: 'Dynamic Course Assessment', ...over, + } as Partial); + + it('generates right after the first save that has Skill and Difficulty Target (positive)', async () => { + const refreshContentBody = vi.fn().mockResolvedValue({}); + const result = await mountWithContent(svc({ refreshContentBody }), daContent({ totalQuestions: 0 } as Partial)); + await act(async () => { await result.current.saveMetadata({ skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}' }); }); + await waitFor(() => expect(refreshContentBody).toHaveBeenCalledWith('do_da_2', 'u1')); + expect(result.current.dynamicAssessRefreshing).toBe(true); + }); + + it('regenerates when a save changes the Skill of already-generated questions (positive)', async () => { + const refreshContentBody = vi.fn().mockResolvedValue({}); + const content = daContent({ totalQuestions: 3, skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}', body: generatedBody } as Partial); + const result = await mountWithContent(svc({ refreshContentBody }), content); + await act(async () => { await result.current.saveMetadata({ skill: ['Physics', 'Chemistry'] }); }); + await waitFor(() => expect(refreshContentBody).toHaveBeenCalled()); + }); + + it('is a plain save, with no generate call, for a spelling fix (negative)', async () => { + const refreshContentBody = vi.fn(); + const content = daContent({ totalQuestions: 3, skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}', body: generatedBody } as Partial); + const result = await mountWithContent(svc({ refreshContentBody }), content); + await act(async () => { await result.current.saveMetadata({ name: 'Fixed typo' }); }); + expect(refreshContentBody).not.toHaveBeenCalled(); + expect(result.current.toast?.msg).toBe('Details saved — content updated'); + }); + + it('keeps the generic toast for other content (negative)', async () => { + const result = await mountWithContent(svc(), videoContent()); + await act(async () => { await result.current.saveMetadata({ name: 'Renamed' }); }); + expect(result.current.toast?.msg).toBe('Details saved — content updated'); + }); +}); + +describe('useEditor — Dynamic Assess settings changed after generation', () => { + const generatedBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 3, M: 3, D: 3 } } }) } } }] }, + }); + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_s', mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', status: 'Draft', totalQuestions: 9, + skill: ['Physics'], difficultyTarget: '{"E":3,"M":3,"D":3}', body: generatedBody, ...over, + } as Partial); + + it('blocks Send for Review when the target was changed without regenerating (positive)', async () => { + const service = svc(); + const result = await mountWithContent(service, daContent({ difficultyTarget: '{"E":3,"M":2,"D":3}' } as Partial)); + expect(result.current.dynamicAssessStale).toBe(true); + await act(async () => { await result.current.sendForReview(); }); + expect(service.sendForReview).not.toHaveBeenCalled(); + expect(result.current.toast?.msg).toMatch(/changed since the questions were generated/); + }); + + it('saves but does not submit when the review drawer itself changes the skill (positive)', async () => { + const service = svc(); + const result = await mountWithContent(service, daContent()); + expect(result.current.dynamicAssessStale).toBe(false); + await act(async () => { await result.current.saveMetadataAndSubmit({ skill: ['Chemistry'] }); }); + expect(service.updateContent).toHaveBeenCalled(); + expect(service.sendForReview).not.toHaveBeenCalled(); + expect(result.current.dynamicAssessStale).toBe(true); + }); + + it('blocks Publish for a reviewer when settings do not match the questions (positive)', async () => { + const publishContent = vi.fn().mockResolvedValue({}); + const service = svc({ publishContent }); + const result = await mountWithContent(service, daContent({ skill: ['Chemistry'] })); + await act(async () => { await result.current.publish(); }); + expect(publishContent).not.toHaveBeenCalled(); + expect(result.current.toast?.msg).toMatch(/Request changes/); + }); + + it('submits normally when the settings still match the generated questions (negative)', async () => { + const service = svc(); + const result = await mountWithContent(service, daContent()); + await act(async () => { await result.current.sendForReview(); }); + expect(service.sendForReview).toHaveBeenCalledWith('do_da_s'); + }); + + it('never flags ordinary content, whatever its fields say (negative)', async () => { + const service = svc(); + const result = await mountWithContent(service, daContent({ primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1}' } as Partial)); + expect(result.current.dynamicAssessStale).toBe(false); + await act(async () => { await result.current.sendForReview(); }); + expect(service.sendForReview).toHaveBeenCalled(); + }); +}); + +describe('useEditor — Dynamic Assess Generate edge cases', () => { + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_g', mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', status: 'Live', + totalQuestions: 6, lastUpdatedOn: 't0', + skill: ['Physics'], difficultyTarget: '{"E":2,"M":2,"D":2}', ...over, + } as Partial); + + it('ignores the edit-copy write the API makes for Live content and waits for the job (positive)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + (service.readContent as ReturnType) + .mockResolvedValueOnce(daContent({ lastUpdatedOn: 't-img' })) // baseline, after the API created the .img copy + .mockResolvedValueOnce(daContent({ lastUpdatedOn: 't-img' })) // poll 1: job not done + .mockResolvedValue(daContent({ lastUpdatedOn: 't-job' })); // poll 2: job wrote + await act(async () => { await result.current.refreshBody(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(result.current.dynamicAssessRefreshing).toBe(true); + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + + it('stops polling when the editor unmounts mid-generation (negative)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + (service.readContent as ReturnType).mockResolvedValue(daContent()); + const { result, unmount } = renderHook(() => useEditor({ context: mockContext, contentId: 'do_da_g', service })); + await waitFor(() => expect(result.current.content?.identifier).toBe('do_da_g')); + vi.useFakeTimers(); + try { + await act(async () => { await result.current.refreshBody(); }); + unmount(); + const callsAtUnmount = (service.readContent as ReturnType).mock.calls.length; + await vi.advanceTimersByTimeAsync(3000 * 5); + expect((service.readContent as ReturnType).mock.calls.length).toBe(callsAtUnmount); + } finally { + vi.useRealTimers(); + } + }); + + it('refuses Send for Review before any questions are generated, whatever the caller (positive)', async () => { + const service = svc(); + const result = await mountWithContent(service, daContent({ status: 'Draft', totalQuestions: 0 })); + await act(async () => { await result.current.sendForReview(); }); + expect(service.sendForReview).not.toHaveBeenCalled(); + expect(result.current.toast?.msg).toBe('Generate questions before sending for review'); + }); + + it('translates the knowlg-service per-skill rejection instead of showing its English text (positive)', async () => { + const rejection = Object.assign(new Error('Fewer than 6 Live questions found for skill(s): Azure'), { code: 'ERR_SKILL_INSUFFICIENT_POOL' }); + const service = svc({ refreshContentBody: vi.fn().mockRejectedValue(rejection) }); + const result = await mountWithContent(service, daContent({ status: 'Draft' })); + await act(async () => { await result.current.refreshBody(); }); + expect(result.current.toast?.msg).toBe('Each skill needs at least 6 Live questions. Too few for: Azure'); + expect(result.current.dynamicAssessRefreshing).toBe(false); + }); +}); diff --git a/src/useEditor.ts b/src/useEditor.ts index 535a4d6..d16d270 100644 --- a/src/useEditor.ts +++ b/src/useEditor.ts @@ -5,6 +5,8 @@ import type { EditorMode, EditorView, RawTranscript, UploadProgress, } from './types'; import { ContentEditorService } from './services/ContentEditorService'; +import { difficultyTargetTotal, toDifficultyTarget } from './difficultyTarget'; +import { isGenerationStale, needsGeneration } from './dynamicAssessDraw'; import { UploadService, detectFileMime, detectUrlMime } from './services/UploadService'; import { TelemetryService } from './telemetry/TelemetryService'; import type { TelemetryEvent } from './telemetry/telemetry.types'; @@ -38,6 +40,37 @@ const TRANSCRIPT_POLL_MS = 20000; /** ~5 minutes of active (non-hidden) polling - generation is expected to finish well within this. */ const TRANSCRIPT_POLL_MAX_ATTEMPTS = 15; +/** refresh-body polling: faster and shorter than transcript polling since the job write is quicker. */ +const DYNAMIC_ASSESS_POLL_MS = 3000; +const DYNAMIC_ASSESS_POLL_MAX_ATTEMPTS = 20; + +const DYNAMIC_ASSESS_CATEGORY = 'Dynamic Course Assessment'; + +/** Dynamic Assess has no uploaded artifact (the job generates its body), so it counts as usable and skips the upload view. */ +function hasUsableContent(content: { artifactUrl?: string; primaryCategory?: string } | null): boolean { + return !!content?.artifactUrl || content?.primaryCategory === DYNAMIC_ASSESS_CATEGORY; +} + +/** Dynamic Assess content whose saved skill/difficultyTarget differ from what its questions were generated for. */ +function isStaleGeneration(c: ContentData | null): boolean { + return c?.primaryCategory === DYNAMIC_ASSESS_CATEGORY && Number(c.totalQuestions ?? 0) > 0 + && isGenerationStale(c.body, toDifficultyTarget(c.difficultyTarget), c.skill); +} + +/** Translates knowlg-service's per-skill pool rejection; its message is English-only ("Fewer than 6 Live questions found for skill(s): A, B"). */ +function skillPoolErrorMessage(err: unknown, lang: string): string | null { + const e = err as { code?: string; message?: string }; + if (e?.code !== 'ERR_SKILL_INSUFFICIENT_POOL') return null; + const match = /Fewer than (\d+).*skill\(s\):\s*(.+)$/.exec(e.message ?? ''); + if (!match) return e.message ?? null; + return tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: match[1] ?? '', skills: match[2] ?? '' }); +} + +/** Dynamic Assess content the job hasn't generated questions for yet. */ +function lacksGeneratedQuestions(c: ContentData | null): boolean { + return c?.primaryCategory === DYNAMIC_ASSESS_CATEGORY && !(Number(c.totalQuestions ?? 0) > 0); +} + function resolveMode(status: string | undefined, roles: string[] = []): EditorMode { const s = (status || STATUS.DRAFT).toLowerCase().trim(); const isReviewer = roles.some((r) => REVIEWER_ROLES.includes(r)); @@ -124,6 +157,10 @@ export function useEditor(opts: UseEditorOptions) { const uploadingRef = useRef(false); /** False once the hook unmounts — stops late async work touching a torn-down instance. */ const mountedRef = useRef(true); + const refreshPollRef = useRef | null>(null); + // Lets saveMetadata (declared above refreshBody) start generation with the just-saved content. + const generateRef = useRef<(c?: ContentData) => Promise>(async () => {}); + const generatingRef = useRef(false); const toastTimer = useRef | null>(null); const mode: EditorMode = resolveMode(content?.status, context.user?.roles); @@ -150,6 +187,7 @@ export function useEditor(opts: UseEditorOptions) { mountedRef.current = true; return () => { mountedRef.current = false; + if (refreshPollRef.current) clearInterval(refreshPollRef.current); if (lockedIdRef.current) { service.retireLock(lockedIdRef.current).catch(() => {}); lockedRef.current = false; @@ -168,11 +206,17 @@ export function useEditor(opts: UseEditorOptions) { setBusy(true); service .readContent(initialId) + // Only Dynamic Assess needs its body (generated questions), so only it pays for a second read that includes it. + .then((c) => (c.primaryCategory === DYNAMIC_ASSESS_CATEGORY ? service.readContent(initialId, 'edit', { withBody: true }) : c)) .then((c) => { if (!mountedRef.current) return; // editor torn down mid-load telemetry.current?.setObject(c.identifier); setContent(c); - setView(c.artifactUrl ? 'player' : 'upload'); + setView(hasUsableContent(c) ? 'player' : 'upload'); + // Dynamic Assess opens on the metadata form, since there's nothing to preview until questions are generated. + if (c.primaryCategory === DYNAMIC_ASSESS_CATEGORY && resolveMode(c.status, context.user?.roles) === 'edit') { + openDrawer('metadata'); + } // Lock the content when opened for editing (creator on a draft), mirroring the old editor. if (resolveMode(c.status, context.user?.roles) === 'edit' && !lockedRef.current) { service.createLock(c.identifier, context, c) @@ -304,7 +348,7 @@ export function useEditor(opts: UseEditorOptions) { telemetry.current?.error(String((err as Error)?.message ?? err)); emit(EDITOR_EVENTS.ERROR, { phase: 'upload', message: String((err as Error)?.message) }); showToast(t(lang, 'ERROR_UPLOAD'), 'error'); - setView(content?.artifactUrl ? 'player' : 'upload'); + setView(hasUsableContent(content) ? 'player' : 'upload'); } finally { uploadingRef.current = false; setBusy(false); @@ -355,7 +399,7 @@ export function useEditor(opts: UseEditorOptions) { setView('upload'); } else { showToast(t(lang, 'ERROR_UPLOAD'), 'error'); - setView(content?.artifactUrl ? 'player' : 'upload'); + setView(hasUsableContent(content) ? 'player' : 'upload'); } } finally { uploadingRef.current = false; @@ -373,7 +417,7 @@ export function useEditor(opts: UseEditorOptions) { setBusy(false); setBusyAction(null); setProgress(null); - setView(content?.artifactUrl ? 'player' : 'upload'); + setView(hasUsableContent(content) ? 'player' : 'upload'); telemetry.current?.interact('click', 'cancelUpload', 'upload'); }, [content]); @@ -385,11 +429,14 @@ export function useEditor(opts: UseEditorOptions) { setBusyAction('save-metadata'); try { const res = await service.updateContent(content.identifier, fields, content.versionKey); + const merged = { ...content, ...fields, versionKey: res?.versionKey ?? content.versionKey } as ContentData; setContent((c) => (c ? { ...c, ...fields, versionKey: res?.versionKey ?? c.versionKey } : c)); setDrawer(null); telemetry.current?.interact('modify', 'metadata', 'save'); emit(EDITOR_EVENTS.SAVED, { id: content.identifier }); - showToast(t(lang, 'TOAST_DETAILS_SAVED')); + // Dynamic Assess generates as part of Save, only when Skill/Target need it; generation shows its own loader and toast. + if (needsGeneration(merged)) void generateRef.current(merged); + else showToast(t(lang, 'TOAST_DETAILS_SAVED')); } catch (err) { telemetry.current?.error(String((err as Error)?.message ?? err), 'edit'); showToast(String((err as Error)?.message ?? t(lang, 'ERROR_GENERIC')), 'error'); @@ -492,6 +539,8 @@ export function useEditor(opts: UseEditorOptions) { const sendForReview = useCallback(async () => { if (!content?.identifier) return; + if (isStaleGeneration(content)) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_STALE'), 'error'); return; } + if (lacksGeneratedQuestions(content)) { showToast(t(lang, 'DYNAMIC_ASSESS_GENERATE_FIRST'), 'error'); return; } setBusy(true); setBusyAction('save-submit'); try { @@ -534,6 +583,13 @@ export function useEditor(opts: UseEditorOptions) { setBusyAction(null); return; } + // Settings changed in the review drawer itself would otherwise submit questions built for the old ones. + if (isStaleGeneration(merged) || lacksGeneratedQuestions(merged)) { + showToast(t(lang, lacksGeneratedQuestions(merged) ? 'DYNAMIC_ASSESS_GENERATE_FIRST' : 'ERROR_DYNAMIC_ASSESS_STALE'), 'error'); + setBusy(false); + setBusyAction(null); + return; + } // Re-validate the just-saved content (pass `merged` — `content` in closure is pre-save). const errs = await validateForReviewAsync(merged); if (errs.length) { @@ -569,6 +625,8 @@ export function useEditor(opts: UseEditorOptions) { /* ---- Reviewer actions ---- */ const publish = useCallback(async () => { if (!content?.identifier) return; + if (isStaleGeneration(content)) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_STALE_REVIEW'), 'error'); return; } + if (lacksGeneratedQuestions(content)) { showToast(t(lang, 'DYNAMIC_ASSESS_GENERATE_FIRST'), 'error'); return; } setBusy(true); setBusyAction('publish'); try { @@ -662,6 +720,84 @@ export function useEditor(opts: UseEditorOptions) { /** True when content was rejected and has reviewer suggestions to show. */ const hasReviewComments = !!(content?.rejectReasons?.length || content?.rejectComment); + /* Dynamic Assess: totalQuestions (set by the job) means questions exist; pkgVersion only moves on publish, and Drafts aren't published. */ + const isDynamicAssess = content?.primaryCategory === DYNAMIC_ASSESS_CATEGORY; + const hasGeneratedBody = Number(content?.totalQuestions ?? 0) > 0; + const dynamicAssessStale = isDynamicAssess && hasGeneratedBody && isStaleGeneration(content); + const [dynamicAssessRefreshing, setDynamicAssessRefreshing] = useState(false); + + const refreshBody = useCallback(async (override?: ContentData) => { + // Save passes the just-saved content, since this callback's `content` is from before the save. + const current = override ?? content; + if (!current?.identifier || generatingRef.current) return; // one generation at a time + + // Without saved inputs the job fails silently, which would show up ~60s later as a misleading "still in progress". + const skills = Array.isArray(current.skill) ? current.skill : []; + if (!skills.length || difficultyTargetTotal(current.difficultyTarget) <= 0) { + showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_INPUTS'), 'error'); + return; + } + const id = current.identifier; + // lastUpdatedOn changes on every job write even when the count doesn't. + const snapshot = (c: ContentData | null) => `${String(c?.totalQuestions ?? '')}|${String(c?.lastUpdatedOn ?? '')}`; + setDynamicAssessRefreshing(true); + generatingRef.current = true; + let baseline: string; + try { + await service.refreshContentBody(id, context.user?.id ?? ''); + telemetry.current?.interact('click', 'dynamicAssessRefreshButton', 'refresh-body'); + // Baseline only after the API returns: for Live content it first writes the edit copy, which also bumps lastUpdatedOn. + baseline = snapshot(await service.readContent(id).catch(() => current)); + } catch (err) { + showToast(skillPoolErrorMessage(err, lang) ?? String((err as Error)?.message ?? t(lang, 'ERROR_GENERIC')), 'error'); + setDynamicAssessRefreshing(false); + generatingRef.current = false; + return; + } + // The job writes asynchronously: poll until it lands, bounded like the transcripts poll below. + let attempts = 0; + let done = false; + const poll = () => { + service.readContent(id, 'edit', { withBody: true }).then((updated) => { + if (!mountedRef.current || done) return; + if (snapshot(updated) !== baseline) { + done = true; + generatingRef.current = false; + setContent(updated); + setDynamicAssessRefreshing(false); + showToast(t(lang, 'TOAST_DYNAMIC_ASSESS_REFRESH_DONE')); + } + }).catch(() => {}); + }; + if (refreshPollRef.current) clearInterval(refreshPollRef.current); + const interval = setInterval(() => { + if (done || !mountedRef.current) { clearInterval(interval); return; } + // A hidden tab doesn't poll, so it mustn't use up attempts either. + if (typeof document !== 'undefined' && document.hidden) return; + attempts += 1; + if (attempts > DYNAMIC_ASSESS_POLL_MAX_ATTEMPTS) { + clearInterval(interval); + done = true; // a late in-flight response must not report "done" after "still pending" + // One last read so the editor shows what the server has, even when the job wrote before the baseline read. + service.readContent(id, 'edit', { withBody: true }) + .then((updated) => { + if (!mountedRef.current) return; + setContent(updated); + showToast(t(lang, snapshot(updated) !== baseline ? 'TOAST_DYNAMIC_ASSESS_REFRESH_DONE' : 'TOAST_DYNAMIC_ASSESS_PENDING')); + }) + .catch(() => { if (mountedRef.current) showToast(t(lang, 'TOAST_DYNAMIC_ASSESS_PENDING')); }) + .finally(() => { + generatingRef.current = false; + if (mountedRef.current) setDynamicAssessRefreshing(false); + }); + return; + } + poll(); + }, DYNAMIC_ASSESS_POLL_MS); + refreshPollRef.current = interval; + }, [content, service, lang, showToast, context.user?.id]); + generateRef.current = refreshBody; + /* ---- Transcripts: single fetch owner for the raw list (EditorPreview/TranscriptsDrawer read it from here instead of each independently re-fetching the same slow ?enrich=all payload). Gates the header's "View transcript" button and feeds the preview's live @@ -708,12 +844,13 @@ export function useEditor(opts: UseEditorOptions) { userId: context.user?.id, rootOrgId: context.user?.rootOrgId, userRoles: context.user?.roles ?? [], reviewErrors, uploadSuccess, sessionExpired, assetPicker, reviewSubmitMode, hasReviewComments, hasTranscripts, transcripts, transcriptsChecked, + isDynamicAssess, hasGeneratedBody, dynamicAssessRefreshing, dynamicAssessStale, // setters setDrawer: openDrawer, setContentType, setUploadUrl, setUrlError, showToast, setReviewErrors, setReviewSubmitMode, dismissSessionExpiry, openAssetPicker, closeAssetPicker, // actions uploadFile, uploadFromUrl, cancelUpload, saveMetadata, saveMetadataAndSubmit, saveDraft, saveCollaborators, - validateForReview, validateForReviewAsync, sendForReview, publish, requestChanges, close, + validateForReview, validateForReviewAsync, sendForReview, publish, requestChanges, close, refreshBody, uploadAsset: opts.onUploadAsset, // services (for drawers that need search / framework) service, context, From 930e01192a3b34245b4cea5f54da60f5640fe17c Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Tue, 27 Oct 2026 21:01:38 +0530 Subject: [PATCH 2/7] fix(dynamic-assess): store the selected skills in the framework's deepest category field [SBCOSS-1190] --- src/components/MetadataDrawer.test.tsx | 24 +++++----- src/components/MetadataDrawer.tsx | 45 +++++++++++++----- src/dynamicAssessDraw.test.ts | 20 +++++++- src/dynamicAssessDraw.ts | 10 +++- src/services/ContentEditorService.ts | 12 ++--- src/types.ts | 5 +- src/useEditor.test.ts | 41 ++++++++++++++-- src/useEditor.ts | 65 +++++++++++++++++++++----- 8 files changed, 172 insertions(+), 50 deletions(-) diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 7fc577a..6ad23ae 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -217,12 +217,13 @@ describe('', () => { const saveMetadata = vi.fn(); const service = serviceWithSkill({ }); - const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content: { ...baseContent, skill: ['physics'] } }); + // The editor holds the selection read from the framework's skill category as dynamicSkills. + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content: { ...baseContent, dynamicSkills: ['physics'] } }); render(); await screen.findByText('Difficulty Target'); expect(await screen.findByText('physics')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); - await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ skill: ['physics'] }))); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ skill: ['physics'] }), { skillField: 'skill' })); }); it('blocks a skill the job could not give its own minimum at the chosen levels, which would otherwise stay stale forever (positive)', async () => { @@ -315,7 +316,7 @@ describe('', () => { }); }); - describe('skill binds to the framework\'s deepest category (Dynamic Assess)', () => { + describe('skills are selected in the framework\'s deepest category (Dynamic Assess)', () => { // Deepest category is 'topic' and there is no category coded 'skill', like a non-USF framework. const nonUsfService = (over: Record = {}) => mockService({ readFormFields: vi.fn().mockResolvedValue([ @@ -331,18 +332,19 @@ describe('', () => { }); const content = { ...mockContent, primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":2,"M":0,"D":0}' }; - it('offers the deepest category\'s terms and checks the pool on that category (positive)', async () => { + it('offers the deepest category\'s terms under its own name, saves them in that category and checks the pool on it (positive)', async () => { const saveMetadata = vi.fn(); const pool = vi.fn().mockResolvedValue({ Algebra: { E: 9, M: 9, D: 9 } }); const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService({ searchAssessmentItemBucketCounts: pool }), saveMetadata, content }); render(); - fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); expect(await screen.findByText('Algebra')).toBeInTheDocument(); expect(screen.getByText('Geometry')).toBeInTheDocument(); expect(screen.queryByText('Maths')).not.toBeInTheDocument(); fireEvent.click(screen.getByText('Algebra')); fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); - await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ skill: ['Algebra'] }))); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ topic: ['Algebra'] }), { skillField: 'topic' })); + expect(saveMetadata.mock.calls[0][0]).not.toHaveProperty('skill'); expect(pool).toHaveBeenCalledWith(['Algebra'], expect.anything(), 'topic'); }); @@ -360,7 +362,7 @@ describe('', () => { const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; await waitFor(() => expect(picker.value).toBe('BMGS')); - fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); fireEvent.click(await screen.findByText('Algebra')); fireEvent.mouseDown(document.body); // close the skill dropdown, as clicking elsewhere does @@ -371,7 +373,7 @@ describe('', () => { expect(screen.queryByText('Algebra')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); - await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ framework: 'USF', skill: ['Physics'] }))); + await waitFor(() => expect(saveMetadata).toHaveBeenCalledWith(expect.objectContaining({ framework: 'USF', skill: ['Physics'] }), { skillField: 'skill' })); }); it('reloads the categories when the author picks the placeholder and then the same framework again (positive)', async () => { @@ -385,7 +387,7 @@ describe('', () => { fireEvent.change(picker, { target: { value: '' } }); fireEvent.change(picker, { target: { value: 'BMGS' } }); await waitFor(() => expect(readFramework.mock.calls.length).toBeGreaterThan(callsBefore)); - fireEvent.click(await screen.findByRole('button', { name: /Select Skill/ })); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); expect(await screen.findByText('Algebra')).toBeInTheDocument(); }); @@ -400,8 +402,8 @@ describe('', () => { it('does not fall back to a free-text box when no category is literally named skill (negative)', async () => { const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), content }); render(); - // Before this change the field rendered as a plain text input, with no "Select Skill" dropdown. - expect(await screen.findByRole('button', { name: /Select Skill/ })).toBeInTheDocument(); + // The selection is a dropdown of the deepest category, never a plain text input. + expect(await screen.findByRole('button', { name: /Select Topic/ })).toBeInTheDocument(); }); }); }); diff --git a/src/components/MetadataDrawer.tsx b/src/components/MetadataDrawer.tsx index 2a63488..8d0d6df 100644 --- a/src/components/MetadataDrawer.tsx +++ b/src/components/MetadataDrawer.tsx @@ -231,6 +231,17 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { [categories], ); const skillCategoryCode = useMemo(() => deepestCategoryCode(categories), [categories]); + // Dynamic Assess: the selection is the framework's deepest category, so the picker carries that category's name. + const skillCategoryLabel = ed.isDynamicAssess ? categories.find((c) => c.code === skillCategoryCode)?.name : undefined; + /** A form field for the deepest category itself, which the Dynamic skill picker already edits. */ + const isReplacedBySkillPicker = (f: FormField) => ed.isDynamicAssess && !!skillCategoryCode && f.code === skillCategoryCode && !isSkillField(f); + const skillPickerCode = ed.isDynamicAssess ? fields.find(isSkillField)?.code : undefined; + /** Content as this save would leave it, with the picker's terms as the in-memory selection. */ + const withSelection = (out: Record) => ({ + ...(content ?? {}), + ...out, + ...(skillPickerCode ? { dynamicSkills: multiVals[skillPickerCode] ?? [] } : {}), + }); const setVal = (code: string, v: string) => setValues((s) => ({ ...s, [code]: v })); const setMulti = (code: string, v: string[]) => setMultiVals((s) => ({ ...s, [code]: v })); @@ -252,7 +263,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (f.code === 'name' || f.code === 'description') continue; if (f.code === 'appicon' || f.code === 'appIcon') continue; if (isDifficultyTargetField(f)) continue; // seeded separately below — see diffSeededRef - const cv = (content as Record)[f.code]; + // The Dynamic skill picker shows the selection read from the framework's skill field, not a field named "skill". + const cv = ed.isDynamicAssess && isSkillField(f) ? content.dynamicSkills : (content as Record)[f.code]; if (isMultiField(f, ed.isDynamicAssess)) { multi[f.code] = Array.isArray(cv) ? cv.map(String) : cv != null && cv !== '' ? [String(cv)] : []; } else { @@ -279,8 +291,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setDiffTargets((s) => ({ ...s, ...diff })); const skill: Record = {}; for (const f of ed.isDynamicAssess ? fields.filter(isSkillField) : []) { - const cv = (content as Record)[f.code]; - skill[f.code] = Array.isArray(cv) ? cv.map(String) : cv != null && cv !== '' ? [String(cv)] : []; + skill[f.code] = content.dynamicSkills ?? []; } setMultiVals((s) => ({ ...s, ...skill })); }, [open, content, fields]); @@ -322,6 +333,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const miss: string[] = []; for (const f of fields) { if (!f.required || f.editable === false || f.visible === false) continue; + if (isReplacedBySkillPicker(f)) continue; const code = f.code; let empty: boolean; if (code === 'appicon' || code === 'appIcon') empty = !appIcon; @@ -347,6 +359,13 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { out[f.code] = serializeDifficultyTarget(diffTargets[f.code] ?? { E: 0, M: 0, D: 0 }); continue; } + if (isReplacedBySkillPicker(f)) continue; + if (ed.isDynamicAssess && isSkillField(f)) { + // Saved in the framework's deepest category field, where the backend reads the selection; left out until that field is known. + const arr = multiVals[f.code] ?? []; + if (skillCategoryCode) out[skillCategoryCode] = arr.length ? arr : undefined; + continue; + } if (isMultiField(f, ed.isDynamicAssess)) { const arr = multiVals[f.code] ?? []; out[f.code] = arr.length ? arr : undefined; @@ -365,7 +384,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { /** Blocks the save unless the job could generate these settings (its own allocation rules) and knowlg-service would accept every skill; returns true to proceed. */ const checkPoolSufficiency = async (candidate: Record): Promise => { const target = toDifficultyTarget(candidate.difficultyTarget); - const skillValues = Array.isArray(candidate.skill) ? candidate.skill.map(String) : []; + const skillValues = Array.isArray(candidate.dynamicSkills) ? candidate.dynamicSkills.map(String) : []; const m = DYNAMIC_ASSESS_POOL_MULTIPLIER; let buckets: Record>; let skillCounts: Record; @@ -420,7 +439,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (miss.length) { setReviewErrors(miss); return; } } const out = buildOut(); - const generates = needsGeneration({ ...(content ?? {}), ...out }); + const generates = needsGeneration(withSelection(out)); // Submitting can't also generate, so changed settings must be saved (and generated) first. if (reviewSubmitMode && generates) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_SUBMIT_STALE'), 'error'); @@ -430,14 +449,16 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setChecking(true); try { // The pool is only checked when this save will generate, so other edits cost no extra searches. - if (!(await checkPoolSufficiency({ ...(content ?? {}), ...out }))) return; + if (!(await checkPoolSufficiency(withSelection(out)))) return; } finally { setChecking(false); } } setReviewErrors([]); - if (reviewSubmitMode) saveMetadataAndSubmit(out); - else saveMetadata(out); + // Only a Dynamic save names the skill field it wrote; other content keeps the plain call. + const args: [Record, { skillField?: string }?] = ed.isDynamicAssess ? [out, { skillField: skillCategoryCode }] : [out]; + if (reviewSubmitMode) saveMetadataAndSubmit(...args); + else saveMetadata(...args); }; const onClose = () => { setReviewErrors([]); setReviewSubmitMode(false); setDrawer(null); }; @@ -492,8 +513,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => {

)} = ({ ed }) => { }; // Live label: tells the author when Save will also generate questions. - const saveGenerates = ed.isDynamicAssess && open && needsGeneration({ ...(content ?? {}), ...buildOut() }); + const saveGenerates = ed.isDynamicAssess && open && needsGeneration(withSelection(buildOut())); // Skill always renders with the other fields (under its framework picker), even when a framework names a category 'skill'. - const taxoFields = fields.filter((f) => taxoCodes.has(f.code) && !(ed.isDynamicAssess && isSkillField(f))); + const taxoFields = fields.filter((f) => taxoCodes.has(f.code) && !(ed.isDynamicAssess && isSkillField(f)) && !isReplacedBySkillPicker(f)); const nonTaxoFields = fields.filter( (f) => (!taxoCodes.has(f.code) || (ed.isDynamicAssess && isSkillField(f))) && f.code !== 'appicon' && f.code !== 'appIcon', ); diff --git a/src/dynamicAssessDraw.test.ts b/src/dynamicAssessDraw.test.ts index 19169f7..1863996 100644 --- a/src/dynamicAssessDraw.test.ts +++ b/src/dynamicAssessDraw.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { ecmlBodyForUser, pickForLearner, isGenerationStale } from './dynamicAssessDraw'; +import { ecmlBodyForUser, pickForLearner, isGenerationStale, needsGeneration, selectedSkills } from './dynamicAssessDraw'; const levels: Record = { a1: 'EASY', a2: 'EASY', a3: 'EASY', b1: 'MEDIUM', b2: 'MEDIUM', b3: 'MEDIUM' }; const body = (dynamic: boolean) => ({ @@ -86,3 +86,21 @@ describe('ecmlBodyForUser — fail closed and parity', () => { expect(pickForLearner(['q1', 'q2', 'q3', 'q4', 'q5', 'q6'], 2, 'user-1:do_123:EASY')).toEqual(['q6', 'q3']); }); }); + +describe('selectedSkills and needsGeneration (the selection lives in the framework\'s deepest category field)', () => { + it('reads the selection from the named field, deduped (positive)', () => { + expect(selectedSkills({ topic: ['Algebra', 'Algebra', 'Geometry'], skill: ['Ignored'] }, 'topic')).toEqual(['Algebra', 'Geometry']); + expect(selectedSkills({ topic: 'Algebra' }, 'topic')).toEqual(['Algebra']); + }); + + it('is empty when that field is missing (negative)', () => { + expect(selectedSkills({ skill: ['Physics'] }, 'topic')).toEqual([]); + }); + + it('generates from the in-memory selection, never from a field named skill (positive/negative)', () => { + const base = { primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":1,"M":0,"D":0}', totalQuestions: 0 }; + expect(needsGeneration({ ...base, dynamicSkills: ['Algebra'] })).toBe(true); + expect(needsGeneration({ ...base, skill: ['Algebra'] } as never)).toBe(false); + expect(needsGeneration({ ...base, primaryCategory: 'Learning Resource', dynamicSkills: ['Algebra'] })).toBe(false); + }); +}); diff --git a/src/dynamicAssessDraw.ts b/src/dynamicAssessDraw.ts index a87a847..bea50d1 100644 --- a/src/dynamicAssessDraw.ts +++ b/src/dynamicAssessDraw.ts @@ -71,10 +71,16 @@ function parseTarget(raw: unknown): AnyRecord { return value && typeof value === 'object' ? (value as AnyRecord) : {}; } +/** The selected skills: the terms in the framework's deepest category field (`skillField`, e.g. "topic"), the same field the backend reads them from. */ +export function selectedSkills(c: Record, skillField: string): string[] { + const v = c[skillField]; + return [...new Set((Array.isArray(v) ? v : v ? [v] : []).map(String).filter(Boolean))]; +} + /** Save must also generate when Skill + Difficulty Target are usable and there are no questions yet or they were built for other settings; any other save is a plain save. */ -export function needsGeneration(c: { primaryCategory?: string; skill?: unknown; difficultyTarget?: unknown; totalQuestions?: unknown; body?: unknown } | null): boolean { +export function needsGeneration(c: { primaryCategory?: string; dynamicSkills?: unknown; difficultyTarget?: unknown; totalQuestions?: unknown; body?: unknown } | null): boolean { if (c?.primaryCategory !== 'Dynamic Course Assessment') return false; - const skills = Array.isArray(c.skill) ? c.skill.map(String) : []; + const skills = Array.isArray(c.dynamicSkills) ? c.dynamicSkills.map(String) : []; const target = parseTarget(c.difficultyTarget); const savedTarget = { E: Number(target.E) || 0, M: Number(target.M) || 0, D: Number(target.D) || 0 }; if (!skills.length || savedTarget.E + savedTarget.M + savedTarget.D <= 0) return false; diff --git a/src/services/ContentEditorService.ts b/src/services/ContentEditorService.ts index 3b1ddc0..dae12cc 100644 --- a/src/services/ContentEditorService.ts +++ b/src/services/ContentEditorService.ts @@ -42,8 +42,8 @@ const READ_FIELDS = [ 'status', 'artifactUrl', 'streamingUrl', 'downloadUrl', 'appIcon', 'posterImage', 'framework', 'board', 'medium', 'gradeLevel', 'subject', 'keywords', 'collaborators', 'createdBy', 'creator', 'versionKey', 'pkgVersion', 'rejectReasons', 'rejectComment', 'channel', - /* Dynamic Assess fields (absent on other content); the knowlg-publish job sets totalQuestions and lastUpdatedOn. */ - 'skill', 'difficultyTarget', 'totalQuestions', 'lastUpdatedOn', + /* Dynamic Assess fields (absent on other content); the knowlg-publish job sets totalQuestions and lastUpdatedOn. The selected skills' field depends on the framework, so callers add it via extraFields. */ + 'difficultyTarget', 'totalQuestions', 'lastUpdatedOn', ].join(','); function toArray(val: unknown): string[] | undefined { @@ -71,7 +71,6 @@ export function normalizeContent(raw: Record): ContentData { collaborators: toArray(raw.collaborators), rejectReasons: toArray(raw.rejectReasons), board: typeof raw.board === 'string' ? raw.board : toArray(raw.board)?.[0], - skill: toArray(raw.skill), } as ContentData; } @@ -181,9 +180,10 @@ export class ContentEditorService { /** GET content/v3/read/{id}?mode=edit — no-store, since this page re-reads its own content right after * mutating it; also sends Cache-Control: no-cache so an intermediary gateway cache (e.g. Kong's * proxy-cache plugin, which honors this request header) doesn't serve a pre-mutation response. */ - async readContent(contentId: string, mode = 'edit', opts: { withBody?: boolean } = {}): Promise { - // body is opt-in (only Dynamic Assess needs it), so other content reads exactly the fields it always did. - const fields = opts.withBody ? `${READ_FIELDS},body` : READ_FIELDS; + async readContent(contentId: string, mode = 'edit', opts: { withBody?: boolean; extraFields?: string[] } = {}): Promise { + // body and extra fields are opt-in (only Dynamic Assess needs them), so other content reads exactly the fields it always did. + const extra = [...(opts.withBody ? ['body'] : []), ...(opts.extraFields ?? [])].filter((f) => f && !READ_FIELDS.split(',').includes(f)); + const fields = extra.length ? `${READ_FIELDS},${[...new Set(extra)].join(',')}` : READ_FIELDS; const path = `${this.ep.read}/${encodeURIComponent(contentId)}?mode=${mode}&fields=${fields}`; const result = await this.request<{ content: Record }>('GET', path, undefined, { cache: 'no-store', diff --git a/src/types.ts b/src/types.ts index a0f3023..3681e77 100644 --- a/src/types.ts +++ b/src/types.ts @@ -82,8 +82,9 @@ export interface ContentData { pkgVersion?: number; rejectReasons?: string[]; rejectComment?: string; - /** Dynamic Assess custom fields (Dynamic Course Assessment category only). */ - skill?: string[]; + /** Dynamic Assess only, in memory: the selected skills, read from the framework's deepest category field (e.g. "topic"); never sent back as-is. */ + dynamicSkills?: string[]; + /** Dynamic Assess custom field (Dynamic Course Assessment category only). */ difficultyTarget?: { E?: number; M?: number; D?: number }; /** Any extra fields returned by content read. */ [key: string]: unknown; diff --git a/src/useEditor.test.ts b/src/useEditor.test.ts index 18f1c4e..8dbd30c 100644 --- a/src/useEditor.test.ts +++ b/src/useEditor.test.ts @@ -270,7 +270,8 @@ describe('Dynamic Assess content view gating', () => { it('reads the body (generated questions) for Dynamic Assess content (positive)', async () => { const service = svc(); await mountWithContent(service, videoContent({ identifier: 'do_da_body', primaryCategory: 'Dynamic Course Assessment', artifactUrl: undefined })); - expect(service.readContent).toHaveBeenCalledWith('do_da_body', 'edit', { withBody: true }); + // No framework, so the skill field falls back to "skill" like the backend. + expect(service.readContent).toHaveBeenCalledWith('do_da_body', 'edit', { withBody: true, extraFields: ['skill'] }); }); it('never reads the body for ordinary content (negative)', async () => { @@ -406,7 +407,7 @@ describe('useEditor — Save also generates when needed', () => { it('generates right after the first save that has Skill and Difficulty Target (positive)', async () => { const refreshContentBody = vi.fn().mockResolvedValue({}); const result = await mountWithContent(svc({ refreshContentBody }), daContent({ totalQuestions: 0 } as Partial)); - await act(async () => { await result.current.saveMetadata({ skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}' }); }); + await act(async () => { await result.current.saveMetadata({ skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}' }, { skillField: 'skill' }); }); await waitFor(() => expect(refreshContentBody).toHaveBeenCalledWith('do_da_2', 'u1')); expect(result.current.dynamicAssessRefreshing).toBe(true); }); @@ -415,7 +416,7 @@ describe('useEditor — Save also generates when needed', () => { const refreshContentBody = vi.fn().mockResolvedValue({}); const content = daContent({ totalQuestions: 3, skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}', body: generatedBody } as Partial); const result = await mountWithContent(svc({ refreshContentBody }), content); - await act(async () => { await result.current.saveMetadata({ skill: ['Physics', 'Chemistry'] }); }); + await act(async () => { await result.current.saveMetadata({ skill: ['Physics', 'Chemistry'] }, { skillField: 'skill' }); }); await waitFor(() => expect(refreshContentBody).toHaveBeenCalled()); }); @@ -458,7 +459,7 @@ describe('useEditor — Dynamic Assess settings changed after generation', () => const service = svc(); const result = await mountWithContent(service, daContent()); expect(result.current.dynamicAssessStale).toBe(false); - await act(async () => { await result.current.saveMetadataAndSubmit({ skill: ['Chemistry'] }); }); + await act(async () => { await result.current.saveMetadataAndSubmit({ skill: ['Chemistry'] }, { skillField: 'skill' }); }); expect(service.updateContent).toHaveBeenCalled(); expect(service.sendForReview).not.toHaveBeenCalled(); expect(result.current.dynamicAssessStale).toBe(true); @@ -550,3 +551,35 @@ describe('useEditor — Dynamic Assess Generate edge cases', () => { expect(result.current.dynamicAssessRefreshing).toBe(false); }); }); + +describe('useEditor — Dynamic Assess skills live in the framework\'s deepest category', () => { + const bmgs = [{ code: 'board', name: 'Board', index: 1, terms: [] }, { code: 'topic', name: 'Topic', index: 2, terms: [] }]; + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_topic', mimeType: 'application/vnd.ekstep.ecml-archive', primaryCategory: 'Dynamic Course Assessment', + status: 'Draft', framework: 'BMGS', difficultyTarget: '{"E":1,"M":0,"D":0}', ...over, + } as Partial); + + it('reads the selection from the deepest category field, not a field named skill (positive)', async () => { + const service = svc({ readFramework: vi.fn().mockResolvedValue(bmgs) }); + const result = await mountWithContent(service, daContent({ topic: ['Algebra'], skill: ['Stray'] } as Partial)); + expect(service.readContent).toHaveBeenCalledWith('do_da_topic', 'edit', { withBody: true, extraFields: ['topic'] }); + await waitFor(() => expect(result.current.content?.dynamicSkills).toEqual(['Algebra'])); + }); + + it('generates after a save that writes the deepest category, and keeps that field in polled reads (positive)', async () => { + const refreshContentBody = vi.fn().mockResolvedValue({}); + const service = svc({ readFramework: vi.fn().mockResolvedValue(bmgs), refreshContentBody }); + const result = await mountWithContent(service, daContent()); + await act(async () => { await result.current.saveMetadata({ topic: ['Algebra'] }, { skillField: 'topic' }); }); + await waitFor(() => expect(refreshContentBody).toHaveBeenCalledWith('do_da_topic', 'u1')); + expect(result.current.content?.dynamicSkills).toEqual(['Algebra']); + }); + + it('never resolves a framework or reads extra fields for ordinary content (negative)', async () => { + const readFramework = vi.fn().mockResolvedValue(bmgs); + const service = svc({ readFramework }); + await mountWithContent(service, videoContent({ artifactUrl: 'https://cdn/video.mp4', framework: 'BMGS' } as Partial)); + expect(readFramework).not.toHaveBeenCalled(); + for (const call of (service.readContent as ReturnType).mock.calls) expect(call[2]).toBeUndefined(); + }); +}); diff --git a/src/useEditor.ts b/src/useEditor.ts index d16d270..a8354fb 100644 --- a/src/useEditor.ts +++ b/src/useEditor.ts @@ -6,7 +6,8 @@ import type { } from './types'; import { ContentEditorService } from './services/ContentEditorService'; import { difficultyTargetTotal, toDifficultyTarget } from './difficultyTarget'; -import { isGenerationStale, needsGeneration } from './dynamicAssessDraw'; +import { isGenerationStale, needsGeneration, selectedSkills } from './dynamicAssessDraw'; +import { deepestCategoryCode } from './taxonomy'; import { UploadService, detectFileMime, detectUrlMime } from './services/UploadService'; import { TelemetryService } from './telemetry/TelemetryService'; import type { TelemetryEvent } from './telemetry/telemetry.types'; @@ -54,7 +55,7 @@ function hasUsableContent(content: { artifactUrl?: string; primaryCategory?: str /** Dynamic Assess content whose saved skill/difficultyTarget differ from what its questions were generated for. */ function isStaleGeneration(c: ContentData | null): boolean { return c?.primaryCategory === DYNAMIC_ASSESS_CATEGORY && Number(c.totalQuestions ?? 0) > 0 - && isGenerationStale(c.body, toDifficultyTarget(c.difficultyTarget), c.skill); + && isGenerationStale(c.body, toDifficultyTarget(c.difficultyTarget), c.dynamicSkills); } /** Translates knowlg-service's per-skill pool rejection; its message is English-only ("Fewer than 6 Live questions found for skill(s): A, B"). */ @@ -66,6 +67,17 @@ function skillPoolErrorMessage(err: unknown, lang: string): string | null { return tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: match[1] ?? '', skills: match[2] ?? '' }); } +/** Content with its in-memory Dynamic Assess selection read from the framework's skill field. */ +function withDynamicSkills(c: ContentData, skillField: string): ContentData { + return { ...c, dynamicSkills: selectedSkills(c, skillField) }; +} + +/** Content after a metadata save; a Dynamic save that wrote the skill field also moves the in-memory selection to it. */ +function applySavedFields(c: ContentData, fields: Record, skillField: string | undefined, versionKey: string | undefined): ContentData { + const next = { ...c, ...fields, versionKey: versionKey ?? c.versionKey } as ContentData; + return skillField && skillField in fields ? withDynamicSkills(next, skillField) : next; +} + /** Dynamic Assess content the job hasn't generated questions for yet. */ function lacksGeneratedQuestions(c: ContentData | null): boolean { return c?.primaryCategory === DYNAMIC_ASSESS_CATEGORY && !(Number(c.totalQuestions ?? 0) > 0); @@ -161,6 +173,9 @@ export function useEditor(opts: UseEditorOptions) { // Lets saveMetadata (declared above refreshBody) start generation with the just-saved content. const generateRef = useRef<(c?: ContentData) => Promise>(async () => {}); const generatingRef = useRef(false); + /** Dynamic Assess: the field holding the selected skills, i.e. the framework's deepest category (e.g. "topic"), as the backend resolves it. */ + const skillFieldRef = useRef('skill'); + const skillFieldCache = useRef(new Map()); const toastTimer = useRef | null>(null); const mode: EditorMode = resolveMode(content?.status, context.user?.roles); @@ -197,6 +212,21 @@ export function useEditor(opts: UseEditorOptions) { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + /** Dynamic Assess: the framework's deepest category code, where the selected skills are stored; falls back to "skill" like the backend's resolveCategoryCode. */ + const resolveSkillField = async (framework: unknown): Promise => { + const fw = typeof framework === 'string' ? framework : ''; + if (!fw) return 'skill'; + const cached = skillFieldCache.current.get(fw); + if (cached) return cached; + try { + const code = deepestCategoryCode(await service.readFramework(fw)) ?? 'skill'; + skillFieldCache.current.set(fw, code); + return code; + } catch { + return 'skill'; // same fallback as the backend; not cached, so a later read can still resolve it + } + }; + /* ---- Initial load ---- */ useEffect(() => { telemetry.current?.start('content-editor'); @@ -206,8 +236,13 @@ export function useEditor(opts: UseEditorOptions) { setBusy(true); service .readContent(initialId) - // Only Dynamic Assess needs its body (generated questions), so only it pays for a second read that includes it. - .then((c) => (c.primaryCategory === DYNAMIC_ASSESS_CATEGORY ? service.readContent(initialId, 'edit', { withBody: true }) : c)) + // Only Dynamic Assess needs its body (generated questions) and its framework's skill field, so only it pays for a second read with them. + .then(async (c) => { + if (c.primaryCategory !== DYNAMIC_ASSESS_CATEGORY) return c; + const field = await resolveSkillField(c.framework); + skillFieldRef.current = field; + return withDynamicSkills(await service.readContent(initialId, 'edit', { withBody: true, extraFields: [field] }), field); + }) .then((c) => { if (!mountedRef.current) return; // editor torn down mid-load telemetry.current?.setObject(c.identifier); @@ -422,15 +457,17 @@ export function useEditor(opts: UseEditorOptions) { }, [content]); /* ---- Save metadata ---- */ + /** `skillField`: the Dynamic Assess skill field the drawer wrote (its framework's deepest category), so the in-memory selection follows the save. */ const saveMetadata = useCallback( - async (fields: Record) => { + async (fields: Record, opts: { skillField?: string } = {}) => { if (!content?.identifier) return; setBusy(true); setBusyAction('save-metadata'); try { const res = await service.updateContent(content.identifier, fields, content.versionKey); - const merged = { ...content, ...fields, versionKey: res?.versionKey ?? content.versionKey } as ContentData; - setContent((c) => (c ? { ...c, ...fields, versionKey: res?.versionKey ?? c.versionKey } : c)); + if (opts.skillField) skillFieldRef.current = opts.skillField; + const merged = applySavedFields(content, fields, opts.skillField, res?.versionKey); + setContent((c) => (c ? applySavedFields(c, fields, opts.skillField, res?.versionKey) : c)); setDrawer(null); telemetry.current?.interact('modify', 'metadata', 'save'); emit(EDITOR_EVENTS.SAVED, { id: content.identifier }); @@ -565,14 +602,15 @@ export function useEditor(opts: UseEditorOptions) { /** Saves edited metadata, re-validates against the review form, and only submits for review if valid. */ const saveMetadataAndSubmit = useCallback( - async (fields: Record) => { + async (fields: Record, opts: { skillField?: string } = {}) => { if (!content?.identifier) return; setBusy(true); setBusyAction('save-submit'); let merged: ContentData; try { const res = await service.updateContent(content.identifier, fields, content.versionKey); - merged = { ...content, ...fields, versionKey: res?.versionKey ?? content.versionKey } as ContentData; + if (opts.skillField) skillFieldRef.current = opts.skillField; + merged = applySavedFields(content, fields, opts.skillField, res?.versionKey); setContent(merged); telemetry.current?.interact('modify', 'metadata', 'save'); emit(EDITOR_EVENTS.SAVED, { id: content.identifier }); @@ -732,12 +770,15 @@ export function useEditor(opts: UseEditorOptions) { if (!current?.identifier || generatingRef.current) return; // one generation at a time // Without saved inputs the job fails silently, which would show up ~60s later as a misleading "still in progress". - const skills = Array.isArray(current.skill) ? current.skill : []; + const skills = Array.isArray(current.dynamicSkills) ? current.dynamicSkills : []; if (!skills.length || difficultyTargetTotal(current.difficultyTarget) <= 0) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_INPUTS'), 'error'); return; } const id = current.identifier; + // Polled reads must carry the skill field too, or the refreshed content would lose the selection. + const skillField = skillFieldRef.current; + const readGenerated = () => service.readContent(id, 'edit', { withBody: true, extraFields: [skillField] }).then((c) => withDynamicSkills(c, skillField)); // lastUpdatedOn changes on every job write even when the count doesn't. const snapshot = (c: ContentData | null) => `${String(c?.totalQuestions ?? '')}|${String(c?.lastUpdatedOn ?? '')}`; setDynamicAssessRefreshing(true); @@ -758,7 +799,7 @@ export function useEditor(opts: UseEditorOptions) { let attempts = 0; let done = false; const poll = () => { - service.readContent(id, 'edit', { withBody: true }).then((updated) => { + readGenerated().then((updated) => { if (!mountedRef.current || done) return; if (snapshot(updated) !== baseline) { done = true; @@ -779,7 +820,7 @@ export function useEditor(opts: UseEditorOptions) { clearInterval(interval); done = true; // a late in-flight response must not report "done" after "still pending" // One last read so the editor shows what the server has, even when the job wrote before the baseline read. - service.readContent(id, 'edit', { withBody: true }) + readGenerated() .then((updated) => { if (!mountedRef.current) return; setContent(updated); From b6d38e68bbf4f3b929866cb2f1b0e43282d56144 Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Tue, 27 Oct 2026 22:39:54 +0530 Subject: [PATCH 3/7] feat(dynamic-assess): use the content's own minCriteria and multiplier and show the per-skill minimum [SBCOSS-1190] --- src/components/MetadataDrawer.test.tsx | 71 ++++++++++++++++++++++++++ src/components/MetadataDrawer.tsx | 56 ++++++++++++++------ src/constants.ts | 4 +- src/dynamicAssessDraw.test.ts | 16 +++++- src/dynamicAssessDraw.ts | 11 ++++ src/editor.scss | 45 ++++++++++++++++ src/i18n/translations.ar.ts | 5 ++ src/i18n/translations.en.ts | 5 ++ src/i18n/translations.fr.ts | 5 ++ src/i18n/translations.hi.ts | 5 ++ src/i18n/translations.pt.ts | 5 ++ src/i18n/translations.ta.ts | 5 ++ src/services/ContentEditorService.ts | 4 +- src/types.ts | 3 ++ 14 files changed, 220 insertions(+), 20 deletions(-) diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 6ad23ae..767b7bc 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -253,6 +253,32 @@ describe('', () => { expect(saveMetadata).not.toHaveBeenCalled(); }); + it("checks the pool with the content's own multiplier, not the default (positive)", async () => { + const saveMetadata = vi.fn(); + const showToast = vi.fn(); + // 9 Easy items cover 2 at the default x3, but not at this content's x5. + const service = serviceWithSkill({ searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 9, M: 0, D: 0 } }) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: { ...baseContent, multiplier: 5 } }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith(expect.stringContaining('Easy: requested 2 needs 10, available 5'), 'error')); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it("applies the content's own minCriteria to the target and the per-skill floor (positive)", async () => { + const showToast = vi.fn(); + const content = { ...baseContent, difficultyTarget: '{"E":4,"M":0,"D":0}', minCriteria: '4', multiplier: 2 }; + const service = serviceWithSkill({ searchSkillPoolCounts: vi.fn().mockResolvedValue({ physics: 7 }) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, showToast, content }); + render(); + await screen.findByText('Difficulty Target'); + await selectPhysicsSkill(); + fireEvent.click(screen.getByRole('button', { name: /Save & Generate/ })); + await waitFor(() => expect(showToast).toHaveBeenCalledWith('Each skill needs at least 8 Live questions. Too few for: physics', 'error')); + }); + it('saves only once when Save & Generate is clicked twice during the pool check (negative)', async () => { const saveMetadata = vi.fn(); let release: () => void = () => {}; @@ -316,6 +342,51 @@ describe('', () => { }); }); + describe('minimum questions per skill panel (Dynamic Assess)', () => { + const service = () => mockService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'skill', name: 'Skill', index: 1, terms: [{ code: 'physics', name: 'physics' }, { code: 'chemistry', name: 'chemistry' }] }, + ]), + }); + const dynamic = { ...mockContent, primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":1,"M":1,"D":1}', dynamicSkills: ['physics'] }; + + it("shows the content's minimum against the live total and flags it when too low (positive)", async () => { + render(); + expect(await screen.findByText('Minimum questions per skill')).toBeInTheDocument(); + expect(screen.getByText('Total: 3 · Minimum: 4')).toBeInTheDocument(); + expect(screen.getByText('Each selected skill needs at least 4 questions; increase the total to at least 4.')).toBeInTheDocument(); + expect(screen.getByText('Needs adjustment')).toBeInTheDocument(); + fireEvent.change(screen.getByRole('spinbutton', { name: 'Easy' }), { target: { value: '2' } }); + expect(screen.getByText('Total: 4 · Minimum: 4')).toBeInTheDocument(); + expect(screen.queryByText('Needs adjustment')).toBeNull(); + expect(screen.getByText('Each selected skill needs at least 4 questions.')).toBeInTheDocument(); + }); + + it('multiplies the minimum by the number of selected skills, defaulting minCriteria to 2 (positive)', async () => { + render(); + expect(await screen.findByText('Total: 3 · Minimum: 4')).toBeInTheDocument(); + expect(screen.getByText('Needs adjustment')).toBeInTheDocument(); + }); + + it('is hidden until a skill is selected (negative)', async () => { + render(); + await screen.findByText('Difficulty Target'); + expect(screen.queryByText('Minimum questions per skill')).toBeNull(); + }); + + it('is never shown for non-Dynamic content (negative)', async () => { + const content = { ...mockContent, primaryCategory: 'Learning Resource', difficultyTarget: '{"E":1,"M":0,"D":0}', skill: ['physics'] }; + render(); + await screen.findByText('Difficulty Target'); + expect(screen.queryByText('Minimum questions per skill')).toBeNull(); + }); + }); + describe('skills are selected in the framework\'s deepest category (Dynamic Assess)', () => { // Deepest category is 'topic' and there is no category coded 'skill', like a non-USF framework. const nonUsfService = (over: Record = {}) => mockService({ diff --git a/src/components/MetadataDrawer.tsx b/src/components/MetadataDrawer.tsx index 8d0d6df..2ac7b2e 100644 --- a/src/components/MetadataDrawer.tsx +++ b/src/components/MetadataDrawer.tsx @@ -6,9 +6,8 @@ import { t, tf } from '../i18n/i18n'; import { cascadedOptions, deepestCategoryCode } from '../taxonomy'; import { PencilIcon, ChevronDown, ImageIcon, CheckIcon } from '../icons'; import { type DifficultyTarget, toDifficultyTarget, serializeDifficultyTarget } from '../difficultyTarget'; -import { needsGeneration } from '../dynamicAssessDraw'; +import { dynamicAssessSettings, needsGeneration } from '../dynamicAssessDraw'; import { planPool } from '../poolPlan'; -import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from '../constants'; /** * Multi-value field? Driven by the form definition, not a hardcoded list — a field @@ -71,6 +70,25 @@ const DifficultyTargetInput: React.FC<{ ); }; +/** Dynamic Assess: shows the per-skill minimum against the live Difficulty Target, so a too-small total is visible before Save rejects it. */ +export const MinimumPerSkillPanel: React.FC<{ + lang: string; minCriteria: number; skillCount: number; target: DifficultyTarget; +}> = ({ lang, minCriteria, skillCount, target }) => { + const total = (target.E ?? 0) + (target.M ?? 0) + (target.D ?? 0); + const minimum = minCriteria * skillCount; + const short = total < minimum; + return ( +
+

{t(lang, 'MIN_PER_SKILL_TITLE')}

+

{tf(lang, short ? 'MIN_PER_SKILL_SHORT' : 'MIN_PER_SKILL_OK', { min: minCriteria, minimum })}

+
+ {tf(lang, 'MIN_PER_SKILL_TOTALS', { total, minimum })} + {short && {t(lang, 'MIN_PER_SKILL_NEEDS_ADJUSTMENT')}} +
+
+ ); +}; + /** Fallback field set when form/read returns nothing (keeps the drawer usable). */ const FALLBACK_FIELDS: FormField[] = [ { code: 'appicon', inputType: 'file', label: 'Thumbnail', index: 1, visible: true, editable: true }, @@ -236,6 +254,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { /** A form field for the deepest category itself, which the Dynamic skill picker already edits. */ const isReplacedBySkillPicker = (f: FormField) => ed.isDynamicAssess && !!skillCategoryCode && f.code === skillCategoryCode && !isSkillField(f); const skillPickerCode = ed.isDynamicAssess ? fields.find(isSkillField)?.code : undefined; + // This content's own rules (knowlg-service stores them at create), so the panel and pool check match what the job enforces. + const { minCriteria, multiplier } = dynamicAssessSettings(content as Record | null); /** Content as this save would leave it, with the picker's terms as the in-memory selection. */ const withSelection = (out: Record) => ({ ...(content ?? {}), @@ -385,7 +405,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const checkPoolSufficiency = async (candidate: Record): Promise => { const target = toDifficultyTarget(candidate.difficultyTarget); const skillValues = Array.isArray(candidate.dynamicSkills) ? candidate.dynamicSkills.map(String) : []; - const m = DYNAMIC_ASSESS_POOL_MULTIPLIER; + const m = multiplier; let buckets: Record>; let skillCounts: Record; try { @@ -398,9 +418,9 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { showToast(t(lang, 'ERROR_POOL_CHECK_FAILED'), 'error'); return false; } - const plan = planPool(skillValues, target, (s, l) => buckets[s]?.[l] ?? 0, DYNAMIC_ASSESS_MIN_CRITERIA, m); + const plan = planPool(skillValues, target, (s, l) => buckets[s]?.[l] ?? 0, minCriteria, m); if (plan.infeasible) { - showToast(tf(lang, 'ERROR_TOO_MANY_SKILLS', { count: skillValues.length, needed: skillValues.length * DYNAMIC_ASSESS_MIN_CRITERIA, min: DYNAMIC_ASSESS_MIN_CRITERIA }), 'error'); + showToast(tf(lang, 'ERROR_TOO_MANY_SKILLS', { count: skillValues.length, needed: skillValues.length * minCriteria, min: minCriteria }), 'error'); return false; } if (plan.uncovered.length) { @@ -416,7 +436,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { return false; } // Same per-skill floor knowlg-service enforces at Generate, so it fails here, translated, instead of after a successful save. - const perSkill = DYNAMIC_ASSESS_MIN_CRITERIA * m; + const perSkill = minCriteria * m; const shortSkills = skillValues.filter((s) => (skillCounts[s] ?? 0) < perSkill); if (shortSkills.length) { showToast(tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: perSkill, skills: shortSkills.join(', ') }), 'error'); @@ -474,16 +494,22 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (code === 'appicon' || code === 'appIcon') return null; // rendered in the top block if (isDifficultyTargetField(f)) { + const target = diffTargets[code] ?? { E: 0, M: 0, D: 0 }; + const skillCount = skillPickerCode ? (multiVals[skillPickerCode] ?? []).length : 0; return ( - setDiffTargets((s) => ({ ...s, [code]: v }))} - /> + + setDiffTargets((s) => ({ ...s, [code]: v }))} + /> + {ed.isDynamicAssess && skillCount > 0 && ( + + )} + ); } diff --git a/src/constants.ts b/src/constants.ts index 3812250..9382dc6 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -2,10 +2,10 @@ export const TELEMETRY_VERSION = '3.0'; -/** Dynamic Assess: each difficulty needs requested x this many Live questions; must match the backend's dynamicassess.multiplier. */ +/** Dynamic Assess: each difficulty needs requested x this many Live questions; fallback for content without its own multiplier (the backend's dynamicassess.multiplier default). */ export const DYNAMIC_ASSESS_POOL_MULTIPLIER = 3; -/** Dynamic Assess: each selected skill must contribute at least this many questions; must match the backend's dynamicassess.minCriteria. */ +/** Dynamic Assess: each selected skill must contribute at least this many questions; fallback for content without its own minCriteria (the backend's dynamicassess.minCriteria default). */ export const DYNAMIC_ASSESS_MIN_CRITERIA = 2; /** Default content category options shown in the upload content-type picker. diff --git a/src/dynamicAssessDraw.test.ts b/src/dynamicAssessDraw.test.ts index 1863996..fb8a113 100644 --- a/src/dynamicAssessDraw.test.ts +++ b/src/dynamicAssessDraw.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { ecmlBodyForUser, pickForLearner, isGenerationStale, needsGeneration, selectedSkills } from './dynamicAssessDraw'; +import { ecmlBodyForUser, pickForLearner, isGenerationStale, needsGeneration, selectedSkills, dynamicAssessSettings } from './dynamicAssessDraw'; const levels: Record = { a1: 'EASY', a2: 'EASY', a3: 'EASY', b1: 'MEDIUM', b2: 'MEDIUM', b3: 'MEDIUM' }; const body = (dynamic: boolean) => ({ @@ -104,3 +104,17 @@ describe('selectedSkills and needsGeneration (the selection lives in the framewo expect(needsGeneration({ ...base, primaryCategory: 'Learning Resource', dynamicSkills: ['Algebra'] })).toBe(false); }); }); + +describe('dynamicAssessSettings', () => { + it("reads the content's own minCriteria and multiplier, as numbers or numeric strings (positive)", () => { + expect(dynamicAssessSettings({ minCriteria: 4, multiplier: '5' })).toEqual({ minCriteria: 4, multiplier: 5 }); + expect(dynamicAssessSettings({ minCriteria: '0', multiplier: 2.0 })).toEqual({ minCriteria: 0, multiplier: 2 }); + }); + + it('falls back to the defaults for older content or unusable values (negative)', () => { + expect(dynamicAssessSettings(null)).toEqual({ minCriteria: 2, multiplier: 3 }); + expect(dynamicAssessSettings({})).toEqual({ minCriteria: 2, multiplier: 3 }); + expect(dynamicAssessSettings({ minCriteria: -1, multiplier: 0 })).toEqual({ minCriteria: 2, multiplier: 3 }); + expect(dynamicAssessSettings({ minCriteria: 'abc', multiplier: '' })).toEqual({ minCriteria: 2, multiplier: 3 }); + }); +}); diff --git a/src/dynamicAssessDraw.ts b/src/dynamicAssessDraw.ts index bea50d1..3c32ba8 100644 --- a/src/dynamicAssessDraw.ts +++ b/src/dynamicAssessDraw.ts @@ -1,5 +1,7 @@ // Same seeded draw as the portal's dynamicAssessSubset, so the preview shows the user the exact set they'd play; the full pool is never displayed. +import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from './constants'; + const LEVELS = [['E', 'EASY'], ['M', 'MEDIUM'], ['D', 'DIFFICULT']] as const; type AnyRecord = Record; @@ -71,6 +73,15 @@ function parseTarget(raw: unknown): AnyRecord { return value && typeof value === 'object' ? (value as AnyRecord) : {}; } +/** The content's own minCriteria/multiplier (stored at create by knowlg-service), or the defaults for content created before they were, or holding unusable values; mirrors the publish job's nodeSetting. */ +export function dynamicAssessSettings(c: Record | null | undefined): { minCriteria: number; multiplier: number } { + const read = (v: unknown, min: number, fallback: number) => { + const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN; + return Number.isFinite(n) && Math.trunc(n) >= min ? Math.trunc(n) : fallback; + }; + return { minCriteria: read(c?.minCriteria, 0, DYNAMIC_ASSESS_MIN_CRITERIA), multiplier: read(c?.multiplier, 1, DYNAMIC_ASSESS_POOL_MULTIPLIER) }; +} + /** The selected skills: the terms in the framework's deepest category field (`skillField`, e.g. "topic"), the same field the backend reads them from. */ export function selectedSkills(c: Record, skillField: string): string[] { const v = c[skillField]; diff --git a/src/editor.scss b/src/editor.scss index 43e1abe..e8e5265 100644 --- a/src/editor.scss +++ b/src/editor.scss @@ -1097,6 +1097,51 @@ line-height: 1.45; } +// Dynamic Assess per-skill minimum, under the Difficulty Target inputs; amber like the stale banner only while the total is too low. +.ce-min-skill { + margin-bottom: 14px; + padding: 10px 12px; + border-radius: 10px; + border: 1px solid var(--ce-border); + background: var(--ce-bg); + color: var(--ce-ink); + font-size: 13px; +} + +.ce-min-skill--short { + border-color: #f0c96b; + background: #fffbeb; + color: #7a4f05; +} + +.ce-min-skill-title { + margin: 0; + font-weight: 700; +} + +.ce-min-skill-sub { + margin: 2px 0 0; + line-height: 1.45; +} + +.ce-min-skill-foot { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 8px; + font-size: 12px; +} + +.ce-min-skill-badge { + padding: 2px 8px; + border-radius: 999px; + background: #fee2e2; + color: var(--ce-danger); + font-weight: 600; + white-space: nowrap; +} + .ce-generating-overlay { position: absolute; inset: 0; diff --git a/src/i18n/translations.ar.ts b/src/i18n/translations.ar.ts index ee097d7..5cfc1ff 100644 --- a/src/i18n/translations.ar.ts +++ b/src/i18n/translations.ar.ts @@ -232,6 +232,11 @@ export const TRANSLATIONS_AR: Record = { DIFFICULTY_EASY: 'سهل', DIFFICULTY_MEDIUM: 'متوسط', DIFFICULTY_DIFFICULT: 'صعب', + MIN_PER_SKILL_TITLE: 'الحد الأدنى من الأسئلة لكل مهارة', + MIN_PER_SKILL_SHORT: 'تحتاج كل مهارة محددة إلى {min} أسئلة على الأقل؛ ارفع المجموع إلى {minimum} على الأقل.', + MIN_PER_SKILL_OK: 'تحتاج كل مهارة محددة إلى {min} أسئلة على الأقل.', + MIN_PER_SKILL_TOTALS: 'المجموع: {total} · الحد الأدنى: {minimum}', + MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'يحتاج إلى تعديل', DYNAMIC_ASSESS_STALE_TITLE: 'تغيّرت الإعدادات منذ إنشاء الأسئلة', DYNAMIC_ASSESS_STALE_SUB: 'الأسئلة لا تطابق المهارة وهدف الصعوبة الحاليين. انقر على إعادة الإنشاء لتحديثها.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'لم تعد المهارة أو هدف الصعوبة يطابقان الأسئلة المُنشأة. اطلب تغييرات ليتمكن المنشئ من إعادة إنشائها.', diff --git a/src/i18n/translations.en.ts b/src/i18n/translations.en.ts index e94e503..524b257 100644 --- a/src/i18n/translations.en.ts +++ b/src/i18n/translations.en.ts @@ -234,6 +234,11 @@ export const TRANSLATIONS_EN: Record = { DIFFICULTY_EASY: 'Easy', DIFFICULTY_MEDIUM: 'Medium', DIFFICULTY_DIFFICULT: 'Difficult', + MIN_PER_SKILL_TITLE: 'Minimum questions per skill', + MIN_PER_SKILL_SHORT: 'Each selected skill needs at least {min} questions; increase the total to at least {minimum}.', + MIN_PER_SKILL_OK: 'Each selected skill needs at least {min} questions.', + MIN_PER_SKILL_TOTALS: 'Total: {total} · Minimum: {minimum}', + MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'Needs adjustment', DYNAMIC_ASSESS_STALE_TITLE: 'Settings changed since the questions were generated', DYNAMIC_ASSESS_STALE_SUB: 'The questions don\'t match the current Skill and Difficulty Target. Click Regenerate to update them.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'Skill or Difficulty Target no longer matches the generated questions. Request changes so the creator can regenerate them.', diff --git a/src/i18n/translations.fr.ts b/src/i18n/translations.fr.ts index 3b2a109..aeda0f0 100644 --- a/src/i18n/translations.fr.ts +++ b/src/i18n/translations.fr.ts @@ -232,6 +232,11 @@ export const TRANSLATIONS_FR: Record = { DIFFICULTY_EASY: 'Facile', DIFFICULTY_MEDIUM: 'Moyen', DIFFICULTY_DIFFICULT: 'Difficile', + MIN_PER_SKILL_TITLE: 'Nombre minimum de questions par compétence', + MIN_PER_SKILL_SHORT: 'Chaque compétence sélectionnée nécessite au moins {min} questions ; augmentez le total à au moins {minimum}.', + MIN_PER_SKILL_OK: 'Chaque compétence sélectionnée nécessite au moins {min} questions.', + MIN_PER_SKILL_TOTALS: 'Total : {total} · Minimum : {minimum}', + MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'À ajuster', DYNAMIC_ASSESS_STALE_TITLE: 'Paramètres modifiés depuis la génération des questions', DYNAMIC_ASSESS_STALE_SUB: 'Les questions ne correspondent pas à la compétence et à l’objectif de difficulté actuels. Cliquez sur Régénérer pour les mettre à jour.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'La compétence ou l’objectif de difficulté ne correspond plus aux questions générées. Demandez des modifications pour que le créateur les régénère.', diff --git a/src/i18n/translations.hi.ts b/src/i18n/translations.hi.ts index b2e10d1..f2361ab 100644 --- a/src/i18n/translations.hi.ts +++ b/src/i18n/translations.hi.ts @@ -232,6 +232,11 @@ export const TRANSLATIONS_HI: Record = { DIFFICULTY_EASY: 'आसान', DIFFICULTY_MEDIUM: 'मध्यम', DIFFICULTY_DIFFICULT: 'कठिन', + MIN_PER_SKILL_TITLE: 'प्रति कौशल न्यूनतम प्रश्न', + MIN_PER_SKILL_SHORT: 'प्रत्येक चयनित कौशल के लिए कम से कम {min} प्रश्न चाहिए; कुल को कम से कम {minimum} तक बढ़ाएं।', + MIN_PER_SKILL_OK: 'प्रत्येक चयनित कौशल के लिए कम से कम {min} प्रश्न चाहिए।', + MIN_PER_SKILL_TOTALS: 'कुल: {total} · न्यूनतम: {minimum}', + MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'समायोजन आवश्यक', DYNAMIC_ASSESS_STALE_TITLE: 'प्रश्न तैयार होने के बाद सेटिंग्स बदली गई हैं', DYNAMIC_ASSESS_STALE_SUB: 'प्रश्न वर्तमान कौशल और कठिनाई लक्ष्य से मेल नहीं खाते। उन्हें अपडेट करने के लिए फिर से तैयार करें पर क्लिक करें।', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'कौशल या कठिनाई लक्ष्य अब तैयार किए गए प्रश्नों से मेल नहीं खाता। परिवर्तन का अनुरोध करें ताकि निर्माता उन्हें फिर से तैयार कर सके।', diff --git a/src/i18n/translations.pt.ts b/src/i18n/translations.pt.ts index d92b9bb..dbec994 100644 --- a/src/i18n/translations.pt.ts +++ b/src/i18n/translations.pt.ts @@ -232,6 +232,11 @@ export const TRANSLATIONS_PT: Record = { DIFFICULTY_EASY: 'Fácil', DIFFICULTY_MEDIUM: 'Médio', DIFFICULTY_DIFFICULT: 'Difícil', + MIN_PER_SKILL_TITLE: 'Mínimo de questões por habilidade', + MIN_PER_SKILL_SHORT: 'Cada habilidade selecionada precisa de pelo menos {min} questões; aumente o total para pelo menos {minimum}.', + MIN_PER_SKILL_OK: 'Cada habilidade selecionada precisa de pelo menos {min} questões.', + MIN_PER_SKILL_TOTALS: 'Total: {total} · Mínimo: {minimum}', + MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'Precisa de ajuste', DYNAMIC_ASSESS_STALE_TITLE: 'Configurações alteradas desde que as questões foram geradas', DYNAMIC_ASSESS_STALE_SUB: 'As questões não correspondem à Habilidade e à Meta de dificuldade atuais. Clique em Gerar novamente para atualizá-las.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'A Habilidade ou a Meta de dificuldade não corresponde mais às questões geradas. Solicite alterações para que o criador as gere novamente.', diff --git a/src/i18n/translations.ta.ts b/src/i18n/translations.ta.ts index b6509e9..a3ae671 100644 --- a/src/i18n/translations.ta.ts +++ b/src/i18n/translations.ta.ts @@ -232,6 +232,11 @@ export const TRANSLATIONS_TA: Record = { DIFFICULTY_EASY: 'எளிது', DIFFICULTY_MEDIUM: 'நடுத்தரம்', DIFFICULTY_DIFFICULT: 'கடினம்', + MIN_PER_SKILL_TITLE: 'ஒரு திறனுக்கான குறைந்தபட்ச கேள்விகள்', + MIN_PER_SKILL_SHORT: 'தேர்ந்தெடுக்கப்பட்ட ஒவ்வொரு திறனுக்கும் குறைந்தது {min} கேள்விகள் தேவை; மொத்தத்தை குறைந்தது {minimum} ஆக அதிகரிக்கவும்.', + MIN_PER_SKILL_OK: 'தேர்ந்தெடுக்கப்பட்ட ஒவ்வொரு திறனுக்கும் குறைந்தது {min} கேள்விகள் தேவை.', + MIN_PER_SKILL_TOTALS: 'மொத்தம்: {total} · குறைந்தபட்சம்: {minimum}', + MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'சரிசெய்தல் தேவை', DYNAMIC_ASSESS_STALE_TITLE: 'கேள்விகள் உருவாக்கப்பட்ட பிறகு அமைப்புகள் மாற்றப்பட்டுள்ளன', DYNAMIC_ASSESS_STALE_SUB: 'கேள்விகள் தற்போதைய திறன் மற்றும் கடினத்தன்மை இலக்குடன் பொருந்தவில்லை. அவற்றைப் புதுப்பிக்க மீண்டும் உருவாக்கு என்பதைக் கிளிக் செய்யவும்.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'திறன் அல்லது கடினத்தன்மை இலக்கு உருவாக்கப்பட்ட கேள்விகளுடன் இனி பொருந்தவில்லை. உருவாக்குநர் அவற்றை மீண்டும் உருவாக்க மாற்றங்களைக் கோரவும்.', diff --git a/src/services/ContentEditorService.ts b/src/services/ContentEditorService.ts index dae12cc..412ce39 100644 --- a/src/services/ContentEditorService.ts +++ b/src/services/ContentEditorService.ts @@ -42,8 +42,8 @@ const READ_FIELDS = [ 'status', 'artifactUrl', 'streamingUrl', 'downloadUrl', 'appIcon', 'posterImage', 'framework', 'board', 'medium', 'gradeLevel', 'subject', 'keywords', 'collaborators', 'createdBy', 'creator', 'versionKey', 'pkgVersion', 'rejectReasons', 'rejectComment', 'channel', - /* Dynamic Assess fields (absent on other content); the knowlg-publish job sets totalQuestions and lastUpdatedOn. The selected skills' field depends on the framework, so callers add it via extraFields. */ - 'difficultyTarget', 'totalQuestions', 'lastUpdatedOn', + /* Dynamic Assess fields (absent on other content); the knowlg-publish job sets totalQuestions and lastUpdatedOn, knowlg-service sets minCriteria and multiplier at create. The selected skills' field depends on the framework, so callers add it via extraFields. */ + 'difficultyTarget', 'totalQuestions', 'lastUpdatedOn', 'minCriteria', 'multiplier', ].join(','); function toArray(val: unknown): string[] | undefined { diff --git a/src/types.ts b/src/types.ts index 3681e77..95ff22b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -86,6 +86,9 @@ export interface ContentData { dynamicSkills?: string[]; /** Dynamic Assess custom field (Dynamic Course Assessment category only). */ difficultyTarget?: { E?: number; M?: number; D?: number }; + /** Dynamic Assess only, set by knowlg-service at create; read through dynamicAssessSettings, which falls back for older content. */ + minCriteria?: number; + multiplier?: number; /** Any extra fields returned by content read. */ [key: string]: unknown; } From 051b567ecab8d886706575821bee12f8a399c316 Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Tue, 27 Oct 2026 22:55:30 +0530 Subject: [PATCH 4/7] chore(dynamic-assess): default the multiplier to 2 [SBCOSS-1190] --- src/components/MetadataDrawer.test.tsx | 12 ++++++------ src/constants.ts | 2 +- src/dynamicAssessDraw.test.ts | 9 +++++---- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 767b7bc..94f733c 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -161,7 +161,7 @@ describe('', () => { await selectPhysicsSkill(); fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); await waitFor(() => expect(showToast).toHaveBeenCalledWith( - expect.stringContaining('Easy: requested 2 needs 6, available 0'), 'error', + expect.stringContaining('Easy: requested 2 needs 4, available 0'), 'error', )); expect(saveMetadata).not.toHaveBeenCalled(); }); @@ -182,8 +182,8 @@ describe('', () => { const saveMetadata = vi.fn(); const showToast = vi.fn(); const service = serviceWithSkill({ - // 5 Easy items exist but only floor(5/3)=1 can be drawn per the job's multiplier rule. - searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 5, M: 0, D: 0 } }), + // 3 Easy items exist but only floor(3/2)=1 can be drawn per the job's multiplier rule. + searchAssessmentItemBucketCounts: vi.fn().mockResolvedValue({ physics: { E: 3, M: 0, D: 0 } }), }); const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); render(); @@ -191,7 +191,7 @@ describe('', () => { await selectPhysicsSkill(); fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); await waitFor(() => expect(showToast).toHaveBeenCalledWith( - expect.stringContaining('Easy: requested 2 needs 6, available 3'), 'error', + expect.stringContaining('Easy: requested 2 needs 4, available 2'), 'error', )); expect(saveMetadata).not.toHaveBeenCalled(); }); @@ -200,7 +200,7 @@ describe('', () => { const saveMetadata = vi.fn(); const showToast = vi.fn(); const service = serviceWithSkill({ - searchSkillPoolCounts: vi.fn().mockResolvedValue({ physics: 5 }), + searchSkillPoolCounts: vi.fn().mockResolvedValue({ physics: 3 }), }); const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, showToast, content: baseContent }); render(); @@ -208,7 +208,7 @@ describe('', () => { await selectPhysicsSkill(); fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); await waitFor(() => expect(showToast).toHaveBeenCalledWith( - 'Each skill needs at least 6 Live questions. Too few for: physics', 'error', + 'Each skill needs at least 4 Live questions. Too few for: physics', 'error', )); expect(saveMetadata).not.toHaveBeenCalled(); }); diff --git a/src/constants.ts b/src/constants.ts index 9382dc6..3ad3288 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -3,7 +3,7 @@ export const TELEMETRY_VERSION = '3.0'; /** Dynamic Assess: each difficulty needs requested x this many Live questions; fallback for content without its own multiplier (the backend's dynamicassess.multiplier default). */ -export const DYNAMIC_ASSESS_POOL_MULTIPLIER = 3; +export const DYNAMIC_ASSESS_POOL_MULTIPLIER = 2; /** Dynamic Assess: each selected skill must contribute at least this many questions; fallback for content without its own minCriteria (the backend's dynamicassess.minCriteria default). */ export const DYNAMIC_ASSESS_MIN_CRITERIA = 2; diff --git a/src/dynamicAssessDraw.test.ts b/src/dynamicAssessDraw.test.ts index fb8a113..4cdf520 100644 --- a/src/dynamicAssessDraw.test.ts +++ b/src/dynamicAssessDraw.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; import { ecmlBodyForUser, pickForLearner, isGenerationStale, needsGeneration, selectedSkills, dynamicAssessSettings } from './dynamicAssessDraw'; +import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from './constants'; const levels: Record = { a1: 'EASY', a2: 'EASY', a3: 'EASY', b1: 'MEDIUM', b2: 'MEDIUM', b3: 'MEDIUM' }; const body = (dynamic: boolean) => ({ @@ -112,9 +113,9 @@ describe('dynamicAssessSettings', () => { }); it('falls back to the defaults for older content or unusable values (negative)', () => { - expect(dynamicAssessSettings(null)).toEqual({ minCriteria: 2, multiplier: 3 }); - expect(dynamicAssessSettings({})).toEqual({ minCriteria: 2, multiplier: 3 }); - expect(dynamicAssessSettings({ minCriteria: -1, multiplier: 0 })).toEqual({ minCriteria: 2, multiplier: 3 }); - expect(dynamicAssessSettings({ minCriteria: 'abc', multiplier: '' })).toEqual({ minCriteria: 2, multiplier: 3 }); + expect(dynamicAssessSettings(null)).toEqual({ minCriteria: DYNAMIC_ASSESS_MIN_CRITERIA, multiplier: DYNAMIC_ASSESS_POOL_MULTIPLIER }); + expect(dynamicAssessSettings({})).toEqual({ minCriteria: DYNAMIC_ASSESS_MIN_CRITERIA, multiplier: DYNAMIC_ASSESS_POOL_MULTIPLIER }); + expect(dynamicAssessSettings({ minCriteria: -1, multiplier: 0 })).toEqual({ minCriteria: DYNAMIC_ASSESS_MIN_CRITERIA, multiplier: DYNAMIC_ASSESS_POOL_MULTIPLIER }); + expect(dynamicAssessSettings({ minCriteria: 'abc', multiplier: '' })).toEqual({ minCriteria: DYNAMIC_ASSESS_MIN_CRITERIA, multiplier: DYNAMIC_ASSESS_POOL_MULTIPLIER }); }); }); From ad48969d80e8dbd17af3eceb9fc450fd4187007d Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Thu, 29 Oct 2026 13:14:10 +0530 Subject: [PATCH 5/7] feat(dynamic-assess): add a min-per-skill example to the Difficulty Target panel [SBCOSS-1190] --- src/components/MetadataDrawer.test.tsx | 52 +++++++++++++ src/components/MetadataDrawer.tsx | 100 ++++++++++++++++--------- src/editor.scss | 30 ++++++++ src/i18n/translations.ar.ts | 5 ++ src/i18n/translations.en.ts | 5 ++ src/i18n/translations.fr.ts | 5 ++ src/i18n/translations.hi.ts | 5 ++ src/i18n/translations.pt.ts | 5 ++ src/i18n/translations.ta.ts | 5 ++ 9 files changed, 177 insertions(+), 35 deletions(-) diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 94f733c..4275969 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -385,6 +385,58 @@ describe('', () => { await screen.findByText('Difficulty Target'); expect(screen.queryByText('Minimum questions per skill')).toBeNull(); }); + + describe('"See an example"', () => { + const withCounts = () => { + const searchAssessmentItemBucketCounts = vi.fn().mockResolvedValue({}); + const searchSkillPoolCounts = vi.fn().mockResolvedValue({}); + return { svc: mockService({ ...service(), searchAssessmentItemBucketCounts, searchSkillPoolCounts }), searchAssessmentItemBucketCounts, searchSkillPoolCounts }; + }; + const open = async (content: Record, svc = withCounts().svc) => { + render(); + fireEvent.click(await screen.findByRole('button', { name: /See an example/ })); + }; + + it('is collapsed by default (negative)', async () => { + render(); + await screen.findByText('Minimum questions per skill'); + expect(screen.queryByText(/^Example: you pick 2 skills/)).toBeNull(); + }); + + it('explains the rule with a fixed example for minCriteria 2 (positive)', async () => { + await open(dynamic); + expect(screen.getByText('Example: you pick 2 skills and ask for 2 Easy, 2 Medium and 2 Difficult.')).toBeInTheDocument(); + expect(screen.getByText('Each learner gets 6 questions.')).toBeInTheDocument(); + expect(screen.getByText('Minimum 2 questions will come from each skill.')).toBeInTheDocument(); + }); + + it("follows the content's own minCriteria (3) (positive)", async () => { + await open({ ...dynamic, minCriteria: 3 }); + expect(screen.getByText('Example: you pick 2 skills and ask for 3 Easy, 3 Medium and 3 Difficult.')).toBeInTheDocument(); + expect(screen.getByText('Each learner gets 9 questions.')).toBeInTheDocument(); + expect(screen.getByText('Minimum 3 questions will come from each skill.')).toBeInTheDocument(); + }); + + it("doesn't change with the creator's skills or target (negative)", async () => { + await open({ ...dynamic, dynamicSkills: ['physics', 'chemistry'], difficultyTarget: '{"E":5,"M":0,"D":1}' }); + expect(screen.getByText('Example: you pick 2 skills and ask for 2 Easy, 2 Medium and 2 Difficult.')).toBeInTheDocument(); + expect(screen.getByText('Each learner gets 6 questions.')).toBeInTheDocument(); + }); + + it('runs no searches when opened (negative)', async () => { + const { svc, searchAssessmentItemBucketCounts, searchSkillPoolCounts } = withCounts(); + await open(dynamic, svc); + await new Promise((r) => setTimeout(r, 700)); + expect(searchAssessmentItemBucketCounts).not.toHaveBeenCalled(); + expect(searchSkillPoolCounts).not.toHaveBeenCalled(); + }); + + it('hides the example again (negative)', async () => { + await open(dynamic); + fireEvent.click(screen.getByRole('button', { name: /Hide/ })); + expect(screen.queryByText('Each learner gets 6 questions.')).toBeNull(); + }); + }); }); describe('skills are selected in the framework\'s deepest category (Dynamic Assess)', () => { diff --git a/src/components/MetadataDrawer.tsx b/src/components/MetadataDrawer.tsx index 2ac7b2e..de90aad 100644 --- a/src/components/MetadataDrawer.tsx +++ b/src/components/MetadataDrawer.tsx @@ -70,20 +70,63 @@ const DifficultyTargetInput: React.FC<{ ); }; -/** Dynamic Assess: shows the per-skill minimum against the live Difficulty Target, so a too-small total is visible before Save rejects it. */ +/** Live pool counts the job allocates from: per skill x level, and per skill overall (knowlg-service's floor). */ +export interface PoolCounts { buckets: Record>; skillCounts: Record } + +/** Why the job couldn't generate these settings (the first problem, in the order Save reports them), or null; shared by Save's check and the panel's example. */ +export function poolProblem( + lang: string, skills: string[], target: DifficultyTarget, counts: PoolCounts, minCriteria: number, multiplier: number, +): string | null { + const { buckets, skillCounts } = counts; + const plan = planPool(skills, target, (s, l) => buckets[s]?.[l] ?? 0, minCriteria, multiplier); + if (plan.infeasible) { + return tf(lang, 'ERROR_TOO_MANY_SKILLS', { count: skills.length, needed: skills.length * minCriteria, min: minCriteria }); + } + if (plan.uncovered.length) { + const levelKey = { E: 'DIFFICULTY_EASY', M: 'DIFFICULTY_MEDIUM', D: 'DIFFICULTY_DIFFICULT' } as const; + const lines = plan.uncovered.map(({ level, covered, target: requested }) => + tf(lang, 'ERROR_POOL_SHORTFALL', { level: t(lang, levelKey[level]), requested, needed: requested * multiplier, available: covered * multiplier })); + return `${t(lang, 'ERROR_POOL_INSUFFICIENT')}: ${lines.join('; ')}`; + } + // A skill that can't get its own minimum would be left out of the pool, and the settings would then never match the questions. + if (plan.shortSkills.length) return tf(lang, 'ERROR_SKILL_LEVELS_SHORT', { skills: plan.shortSkills.join(', ') }); + // Same per-skill floor knowlg-service enforces at Generate, so it fails here, translated, instead of after a successful save. + const perSkill = minCriteria * multiplier; + const shortSkills = skills.filter((s) => (skillCounts[s] ?? 0) < perSkill); + return shortSkills.length ? tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: perSkill, skills: shortSkills.join(', ') }) : null; +} + +/** Dynamic Assess: shows the per-skill minimum against the live Difficulty Target, so a too-small total is visible before Save rejects it; "See an example" explains the rule with a fixed example. */ export const MinimumPerSkillPanel: React.FC<{ lang: string; minCriteria: number; skillCount: number; target: DifficultyTarget; }> = ({ lang, minCriteria, skillCount, target }) => { + const [expanded, setExpanded] = useState(false); const total = (target.E ?? 0) + (target.M ?? 0) + (target.D ?? 0); const minimum = minCriteria * skillCount; const short = total < minimum; + // Fixed example (2 skills, n per level), independent of what the creator entered; only the system's minCriteria feeds it. + const n = Math.max(minCriteria, 1); return (

{t(lang, 'MIN_PER_SKILL_TITLE')}

{tf(lang, short ? 'MIN_PER_SKILL_SHORT' : 'MIN_PER_SKILL_OK', { min: minCriteria, minimum })}

+ {expanded && ( +
+

{tf(lang, 'MIN_PER_SKILL_EX_INTRO', { n })}

+
    +
  • {tf(lang, 'MIN_PER_SKILL_EX_TOTAL', { total: 3 * n })}
  • +
  • {tf(lang, 'MIN_PER_SKILL_EX_EACH', { min: minCriteria })}
  • +
+
+ )}
{tf(lang, 'MIN_PER_SKILL_TOTALS', { total, minimum })} - {short && {t(lang, 'MIN_PER_SKILL_NEEDS_ADJUSTMENT')}} + + {short && {t(lang, 'MIN_PER_SKILL_NEEDS_ADJUSTMENT')}} + +
); @@ -402,44 +445,29 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { }; /** Blocks the save unless the job could generate these settings (its own allocation rules) and knowlg-service would accept every skill; returns true to proceed. */ + /** Live pool counts for these skills, from the same searches the job allocates from. */ + const loadPoolCounts = async (skills: string[]): Promise => { + const channel = (content as Record | null)?.channel as string | undefined; + const [buckets, skillCounts] = await Promise.all([ + service.searchAssessmentItemBucketCounts(skills, channel ?? ed.context.channel, skillCategoryCode ?? 'skill'), + service.searchSkillPoolCounts(skills, skillCategoryCode ?? 'skill'), + ]); + return { buckets, skillCounts }; + }; + const checkPoolSufficiency = async (candidate: Record): Promise => { const target = toDifficultyTarget(candidate.difficultyTarget); const skillValues = Array.isArray(candidate.dynamicSkills) ? candidate.dynamicSkills.map(String) : []; - const m = multiplier; - let buckets: Record>; - let skillCounts: Record; + let counts: PoolCounts; try { - const channel = (content as Record | null)?.channel as string | undefined; - [buckets, skillCounts] = await Promise.all([ - service.searchAssessmentItemBucketCounts(skillValues, channel ?? ed.context.channel, skillCategoryCode ?? 'skill'), - service.searchSkillPoolCounts(skillValues, skillCategoryCode ?? 'skill'), - ]); + counts = await loadPoolCounts(skillValues); } catch { showToast(t(lang, 'ERROR_POOL_CHECK_FAILED'), 'error'); return false; } - const plan = planPool(skillValues, target, (s, l) => buckets[s]?.[l] ?? 0, minCriteria, m); - if (plan.infeasible) { - showToast(tf(lang, 'ERROR_TOO_MANY_SKILLS', { count: skillValues.length, needed: skillValues.length * minCriteria, min: minCriteria }), 'error'); - return false; - } - if (plan.uncovered.length) { - const levelKey = { E: 'DIFFICULTY_EASY', M: 'DIFFICULTY_MEDIUM', D: 'DIFFICULTY_DIFFICULT' } as const; - const lines = plan.uncovered.map(({ level, covered, target: requested }) => - tf(lang, 'ERROR_POOL_SHORTFALL', { level: t(lang, levelKey[level]), requested, needed: requested * m, available: covered * m })); - showToast(`${t(lang, 'ERROR_POOL_INSUFFICIENT')}: ${lines.join('; ')}`, 'error'); - return false; - } - // A skill that can't get its own minimum would be left out of the pool, and the settings would then never match the questions. - if (plan.shortSkills.length) { - showToast(tf(lang, 'ERROR_SKILL_LEVELS_SHORT', { skills: plan.shortSkills.join(', ') }), 'error'); - return false; - } - // Same per-skill floor knowlg-service enforces at Generate, so it fails here, translated, instead of after a successful save. - const perSkill = minCriteria * m; - const shortSkills = skillValues.filter((s) => (skillCounts[s] ?? 0) < perSkill); - if (shortSkills.length) { - showToast(tf(lang, 'ERROR_SKILL_POOL_TOO_SMALL', { needed: perSkill, skills: shortSkills.join(', ') }), 'error'); + const problem = poolProblem(lang, skillValues, target, counts, minCriteria, multiplier); + if (problem) { + showToast(problem, 'error'); return false; } return true; @@ -495,7 +523,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (isDifficultyTargetField(f)) { const target = diffTargets[code] ?? { E: 0, M: 0, D: 0 }; - const skillCount = skillPickerCode ? (multiVals[skillPickerCode] ?? []).length : 0; + const selectedSkills = skillPickerCode ? (multiVals[skillPickerCode] ?? []) : []; return ( = ({ ed }) => { value={target} onChange={(v) => setDiffTargets((s) => ({ ...s, [code]: v }))} /> - {ed.isDynamicAssess && skillCount > 0 && ( - + {ed.isDynamicAssess && selectedSkills.length > 0 && ( + )} ); diff --git a/src/editor.scss b/src/editor.scss index e8e5265..1e6ff0c 100644 --- a/src/editor.scss +++ b/src/editor.scss @@ -1142,6 +1142,36 @@ white-space: nowrap; } +.ce-min-skill-actions { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.ce-min-skill-toggle { + padding: 0; + border: none; + background: none; + color: var(--ce-primary, inherit); + font: inherit; + font-weight: 600; + cursor: pointer; + white-space: nowrap; + + &:hover { text-decoration: underline; } +} + +.ce-min-skill-example { + margin-top: 8px; + padding-top: 8px; + border-top: 1px dashed var(--ce-border); + font-size: 13px; + line-height: 1.45; + + p { margin: 0 0 4px; } + ul { margin: 0; padding-left: 18px; } +} + .ce-generating-overlay { position: absolute; inset: 0; diff --git a/src/i18n/translations.ar.ts b/src/i18n/translations.ar.ts index 5cfc1ff..5c3bb67 100644 --- a/src/i18n/translations.ar.ts +++ b/src/i18n/translations.ar.ts @@ -237,6 +237,11 @@ export const TRANSLATIONS_AR: Record = { MIN_PER_SKILL_OK: 'تحتاج كل مهارة محددة إلى {min} أسئلة على الأقل.', MIN_PER_SKILL_TOTALS: 'المجموع: {total} · الحد الأدنى: {minimum}', MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'يحتاج إلى تعديل', + MIN_PER_SKILL_SEE_EXAMPLE: 'عرض مثال', + MIN_PER_SKILL_HIDE_EXAMPLE: 'إخفاء', + MIN_PER_SKILL_EX_INTRO: 'مثال: تختار مهارتين وتطلب {n} سهلة و{n} متوسطة و{n} صعبة.', + MIN_PER_SKILL_EX_TOTAL: 'يحصل كل متعلم على {total} سؤالًا.', + MIN_PER_SKILL_EX_EACH: 'سيأتي {min} أسئلة على الأقل من كل مهارة.', DYNAMIC_ASSESS_STALE_TITLE: 'تغيّرت الإعدادات منذ إنشاء الأسئلة', DYNAMIC_ASSESS_STALE_SUB: 'الأسئلة لا تطابق المهارة وهدف الصعوبة الحاليين. انقر على إعادة الإنشاء لتحديثها.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'لم تعد المهارة أو هدف الصعوبة يطابقان الأسئلة المُنشأة. اطلب تغييرات ليتمكن المنشئ من إعادة إنشائها.', diff --git a/src/i18n/translations.en.ts b/src/i18n/translations.en.ts index 524b257..9ebfd9e 100644 --- a/src/i18n/translations.en.ts +++ b/src/i18n/translations.en.ts @@ -239,6 +239,11 @@ export const TRANSLATIONS_EN: Record = { MIN_PER_SKILL_OK: 'Each selected skill needs at least {min} questions.', MIN_PER_SKILL_TOTALS: 'Total: {total} · Minimum: {minimum}', MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'Needs adjustment', + MIN_PER_SKILL_SEE_EXAMPLE: 'See an example', + MIN_PER_SKILL_HIDE_EXAMPLE: 'Hide', + MIN_PER_SKILL_EX_INTRO: 'Example: you pick 2 skills and ask for {n} Easy, {n} Medium and {n} Difficult.', + MIN_PER_SKILL_EX_TOTAL: 'Each learner gets {total} questions.', + MIN_PER_SKILL_EX_EACH: 'Minimum {min} questions will come from each skill.', DYNAMIC_ASSESS_STALE_TITLE: 'Settings changed since the questions were generated', DYNAMIC_ASSESS_STALE_SUB: 'The questions don\'t match the current Skill and Difficulty Target. Click Regenerate to update them.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'Skill or Difficulty Target no longer matches the generated questions. Request changes so the creator can regenerate them.', diff --git a/src/i18n/translations.fr.ts b/src/i18n/translations.fr.ts index aeda0f0..787e81d 100644 --- a/src/i18n/translations.fr.ts +++ b/src/i18n/translations.fr.ts @@ -237,6 +237,11 @@ export const TRANSLATIONS_FR: Record = { MIN_PER_SKILL_OK: 'Chaque compétence sélectionnée nécessite au moins {min} questions.', MIN_PER_SKILL_TOTALS: 'Total : {total} · Minimum : {minimum}', MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'À ajuster', + MIN_PER_SKILL_SEE_EXAMPLE: 'Voir un exemple', + MIN_PER_SKILL_HIDE_EXAMPLE: 'Masquer', + MIN_PER_SKILL_EX_INTRO: 'Exemple : vous choisissez 2 compétences et demandez {n} Facile, {n} Moyen et {n} Difficile.', + MIN_PER_SKILL_EX_TOTAL: 'Chaque apprenant reçoit {total} questions.', + MIN_PER_SKILL_EX_EACH: 'Au moins {min} questions viendront de chaque compétence.', DYNAMIC_ASSESS_STALE_TITLE: 'Paramètres modifiés depuis la génération des questions', DYNAMIC_ASSESS_STALE_SUB: 'Les questions ne correspondent pas à la compétence et à l’objectif de difficulté actuels. Cliquez sur Régénérer pour les mettre à jour.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'La compétence ou l’objectif de difficulté ne correspond plus aux questions générées. Demandez des modifications pour que le créateur les régénère.', diff --git a/src/i18n/translations.hi.ts b/src/i18n/translations.hi.ts index f2361ab..111436a 100644 --- a/src/i18n/translations.hi.ts +++ b/src/i18n/translations.hi.ts @@ -237,6 +237,11 @@ export const TRANSLATIONS_HI: Record = { MIN_PER_SKILL_OK: 'प्रत्येक चयनित कौशल के लिए कम से कम {min} प्रश्न चाहिए।', MIN_PER_SKILL_TOTALS: 'कुल: {total} · न्यूनतम: {minimum}', MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'समायोजन आवश्यक', + MIN_PER_SKILL_SEE_EXAMPLE: 'उदाहरण देखें', + MIN_PER_SKILL_HIDE_EXAMPLE: 'छिपाएं', + MIN_PER_SKILL_EX_INTRO: 'उदाहरण: आप 2 कौशल चुनते हैं और {n} आसान, {n} मध्यम और {n} कठिन माँगते हैं।', + MIN_PER_SKILL_EX_TOTAL: 'हर शिक्षार्थी को {total} प्रश्न मिलते हैं।', + MIN_PER_SKILL_EX_EACH: 'हर कौशल से कम से कम {min} प्रश्न आएँगे।', DYNAMIC_ASSESS_STALE_TITLE: 'प्रश्न तैयार होने के बाद सेटिंग्स बदली गई हैं', DYNAMIC_ASSESS_STALE_SUB: 'प्रश्न वर्तमान कौशल और कठिनाई लक्ष्य से मेल नहीं खाते। उन्हें अपडेट करने के लिए फिर से तैयार करें पर क्लिक करें।', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'कौशल या कठिनाई लक्ष्य अब तैयार किए गए प्रश्नों से मेल नहीं खाता। परिवर्तन का अनुरोध करें ताकि निर्माता उन्हें फिर से तैयार कर सके।', diff --git a/src/i18n/translations.pt.ts b/src/i18n/translations.pt.ts index dbec994..40f7901 100644 --- a/src/i18n/translations.pt.ts +++ b/src/i18n/translations.pt.ts @@ -237,6 +237,11 @@ export const TRANSLATIONS_PT: Record = { MIN_PER_SKILL_OK: 'Cada habilidade selecionada precisa de pelo menos {min} questões.', MIN_PER_SKILL_TOTALS: 'Total: {total} · Mínimo: {minimum}', MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'Precisa de ajuste', + MIN_PER_SKILL_SEE_EXAMPLE: 'Ver um exemplo', + MIN_PER_SKILL_HIDE_EXAMPLE: 'Ocultar', + MIN_PER_SKILL_EX_INTRO: 'Exemplo: você escolhe 2 habilidades e pede {n} Fáceis, {n} Médias e {n} Difíceis.', + MIN_PER_SKILL_EX_TOTAL: 'Cada aluno recebe {total} questões.', + MIN_PER_SKILL_EX_EACH: 'No mínimo {min} questões virão de cada habilidade.', DYNAMIC_ASSESS_STALE_TITLE: 'Configurações alteradas desde que as questões foram geradas', DYNAMIC_ASSESS_STALE_SUB: 'As questões não correspondem à Habilidade e à Meta de dificuldade atuais. Clique em Gerar novamente para atualizá-las.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'A Habilidade ou a Meta de dificuldade não corresponde mais às questões geradas. Solicite alterações para que o criador as gere novamente.', diff --git a/src/i18n/translations.ta.ts b/src/i18n/translations.ta.ts index a3ae671..a031040 100644 --- a/src/i18n/translations.ta.ts +++ b/src/i18n/translations.ta.ts @@ -237,6 +237,11 @@ export const TRANSLATIONS_TA: Record = { MIN_PER_SKILL_OK: 'தேர்ந்தெடுக்கப்பட்ட ஒவ்வொரு திறனுக்கும் குறைந்தது {min} கேள்விகள் தேவை.', MIN_PER_SKILL_TOTALS: 'மொத்தம்: {total} · குறைந்தபட்சம்: {minimum}', MIN_PER_SKILL_NEEDS_ADJUSTMENT: 'சரிசெய்தல் தேவை', + MIN_PER_SKILL_SEE_EXAMPLE: 'ஒரு எடுத்துக்காட்டைக் காண்க', + MIN_PER_SKILL_HIDE_EXAMPLE: 'மறை', + MIN_PER_SKILL_EX_INTRO: 'எடுத்துக்காட்டு: நீங்கள் 2 திறன்களைத் தேர்ந்தெடுத்து {n} எளிதான, {n} நடுத்தர, {n} கடினமான கேள்விகளைக் கேட்கிறீர்கள்.', + MIN_PER_SKILL_EX_TOTAL: 'ஒவ்வொரு கற்பவருக்கும் {total} கேள்விகள் கிடைக்கும்.', + MIN_PER_SKILL_EX_EACH: 'ஒவ்வொரு திறனிலிருந்தும் குறைந்தது {min} கேள்விகள் வரும்.', DYNAMIC_ASSESS_STALE_TITLE: 'கேள்விகள் உருவாக்கப்பட்ட பிறகு அமைப்புகள் மாற்றப்பட்டுள்ளன', DYNAMIC_ASSESS_STALE_SUB: 'கேள்விகள் தற்போதைய திறன் மற்றும் கடினத்தன்மை இலக்குடன் பொருந்தவில்லை. அவற்றைப் புதுப்பிக்க மீண்டும் உருவாக்கு என்பதைக் கிளிக் செய்யவும்.', DYNAMIC_ASSESS_STALE_SUB_READONLY: 'திறன் அல்லது கடினத்தன்மை இலக்கு உருவாக்கப்பட்ட கேள்விகளுடன் இனி பொருந்தவில்லை. உருவாக்குநர் அவற்றை மீண்டும் உருவாக்க மாற்றங்களைக் கோரவும்.', From 08ba7ccbda3168e4f01cf46cced73f404c603824 Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Mon, 2 Nov 2026 11:30:04 +0530 Subject: [PATCH 6/7] chore(release): bump version to 2.0.7 [SBCOSS-1190] --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7f739d3..018f84c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@project-sunbird/generic-editor-v2", - "version": "2.0.4", + "version": "2.0.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@project-sunbird/generic-editor-v2", - "version": "2.0.4", + "version": "2.0.7", "dependencies": { "jszip": "^3.10.1" }, diff --git a/package.json b/package.json index 5dd7718..e537f95 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@project-sunbird/generic-editor-v2", - "version": "2.0.6", + "version": "2.0.7", "description": "Sunbird Generic Editor — React content upload/generic editor (theme-reactive, multilingual). Fork of @sunbird/content-editor that previews via the legacy ekstep content renderer.", "main": "dist/sunbird-generic-editor.umd.js", "module": "dist/sunbird-generic-editor.es.js", From ca54f2b673658b3076fc63d18e4de1309fd5cf92 Mon Sep 17 00:00:00 2001 From: Deeksha Deepak Date: Mon, 2 Nov 2026 16:11:23 +0530 Subject: [PATCH 7/7] fix(dynamic-assess): address review feedback [SBCOSS-1190] - Cap each level of the draw at generated / multiplier, using the content's own multiplier, so the pool is never shown - Detect generation by the generated body vs the pre-request one, guard overlapping polls, count hidden-tab ticks - Block saves, review, publish and collaborator writes while generation runs; require a user id before generating - Regenerate when only the framework changes (not for content saved without one) - Framework picker: placeholder keeps Skill disabled, only the latest framework read applies, reset only multiselect values on switch, clear skills when their parent category changes - Send [] when the last skill is removed; drop a generating save if the drawer closes during the pool check - Parse a JSON-string generated target; difficultyTarget type accepts the API's string form - Retry each pool count search once; memoise needsGeneration; Record in the draw path - Tests use literal expected ids and cover an undersized pool --- src/components/EditorPreview.tsx | 4 +- src/components/MetadataDrawer.test.tsx | 118 ++++++++++++++++++++ src/components/MetadataDrawer.tsx | 34 ++++-- src/dynamicAssessDraw.test.ts | 31 +++++- src/dynamicAssessDraw.ts | 80 ++++++++------ src/i18n/translations.ar.ts | 1 + src/i18n/translations.en.ts | 1 + src/i18n/translations.fr.ts | 1 + src/i18n/translations.hi.ts | 1 + src/i18n/translations.pt.ts | 1 + src/i18n/translations.ta.ts | 1 + src/services/ContentEditorService.test.ts | 30 ++++++ src/services/ContentEditorService.ts | 14 +-- src/types.ts | 4 +- src/useEditor.test.ts | 124 ++++++++++++++++++++++ src/useEditor.ts | 42 +++++--- 16 files changed, 419 insertions(+), 68 deletions(-) diff --git a/src/components/EditorPreview.tsx b/src/components/EditorPreview.tsx index 803c98b..7e83ebe 100644 --- a/src/components/EditorPreview.tsx +++ b/src/components/EditorPreview.tsx @@ -4,7 +4,7 @@ import type { ContentData, EditorContext, RawTranscript } from '../types'; import { getMimeTypeLabel, t } from '../i18n/i18n'; import { FileIcon } from '../icons'; import { isVideoMimeType } from '../constants'; -import { ecmlBodyForUser } from '../dynamicAssessDraw'; +import { dynamicAssessSettings, ecmlBodyForUser } from '../dynamicAssessDraw'; interface PlayerTranscript { language: string; @@ -56,7 +56,7 @@ const RendererPreview: React.FC<{ if (!win || typeof win.initializePreview !== 'function') return; const rawBody = (content as Record).body; // Only Dynamic Assess renders from its generated body (the user's own draw, never the whole pool); other content keeps the renderer's own loading. - const data = isDynamicAssess ? ecmlBodyForUser(rendererData(rawBody), content.identifier, context.user?.id) : {}; + const data = isDynamicAssess ? ecmlBodyForUser(rendererData(rawBody), content.identifier, context.user?.id, dynamicAssessSettings(content as Record).multiplier) : {}; // metadata.body carries the same draw, like the portal's ecmlForLearner, so the full pool never reaches the renderer. const metadata = isDynamicAssess && rawBody ? { ...content, body: typeof rawBody === 'string' && data && typeof data === 'object' ? JSON.stringify(data) : data } diff --git a/src/components/MetadataDrawer.test.tsx b/src/components/MetadataDrawer.test.tsx index 4275969..75f47a3 100644 --- a/src/components/MetadataDrawer.test.tsx +++ b/src/components/MetadataDrawer.test.tsx @@ -522,6 +522,124 @@ describe('', () => { expect(skill).toBeDisabled(); }); + it('keeps the Save label in step with skill changes, and with other edits, after memoizing it (positive/negative)', async () => { + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), content }); + render(); + expect(await screen.findByRole('button', { name: 'Save changes' })).toBeInTheDocument(); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + expect(await screen.findByRole('button', { name: 'Save & Generate' })).toBeInTheDocument(); + fireEvent.change(screen.getByDisplayValue('Sample content'), { target: { value: 'Renamed' } }); + expect(screen.getByRole('button', { name: 'Save & Generate' })).toBeInTheDocument(); + }); + + it('keeps Skill disabled after the author picks the framework placeholder (positive)', async () => { + const service = nonUsfService({ searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }]) }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, framework: 'BMGS', content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await screen.findByRole('button', { name: /Select Topic/ }); + fireEvent.change(picker, { target: { value: '' } }); + await new Promise((r) => setTimeout(r, 20)); // let any fallback framework read resolve + expect(screen.getByRole('button', { name: /Select a framework first/ })).toBeDisabled(); + }); + + it('applies only the latest framework\'s categories when an earlier read resolves last (positive)', async () => { + let resolveBmgs: (v: unknown) => void = () => {}; + const readFramework = vi.fn((fw: string) => (fw === 'BMGS' + ? new Promise((r) => { resolveBmgs = r; }) + : Promise.resolve([{ code: 'skill', name: 'Skill', index: 3, terms: [{ code: 'ph', name: 'Physics' }] }]))); + const service = nonUsfService({ + readFramework, + searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }, { identifier: 'USF', name: 'Universal Skills' }]), + }); + const ed = makeEd({ drawer: 'metadata', service, isDynamicAssess: true, content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(readFramework).toHaveBeenCalledWith('BMGS')); + fireEvent.change(picker, { target: { value: 'USF' } }); + await screen.findByRole('button', { name: /Select Skill/ }); + resolveBmgs([{ code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }] }]); + await new Promise((r) => setTimeout(r, 20)); + expect(screen.getByRole('button', { name: /Select Skill/ })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Select Topic/ })).toBeNull(); + }); + + it('drops a generating save when the drawer closes during the pool check (positive)', async () => { + const saveMetadata = vi.fn(); + let resolvePool: (v: unknown) => void = () => {}; + const service = nonUsfService({ searchAssessmentItemBucketCounts: vi.fn(() => new Promise((r) => { resolvePool = r; })) }); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service, saveMetadata, content }); + const { rerender } = render(); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(service.searchAssessmentItemBucketCounts).toHaveBeenCalled()); + rerender(); + resolvePool({ Algebra: { E: 9, M: 9, D: 9 } }); + await new Promise((r) => setTimeout(r, 20)); + expect(saveMetadata).not.toHaveBeenCalled(); + }); + + it('sends an empty array when the author removes the last skill (positive)', async () => { + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), saveMetadata, content: { ...content, dynamicSkills: ['Algebra'] } }); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Algebra|Select Topic/ })); + fireEvent.click((await screen.findAllByText('Algebra')).at(-1) as HTMLElement); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + expect(saveMetadata.mock.calls[0][0]).toHaveProperty('topic', []); + }); + + describe('with a single-select parent category', () => { + const parentService = (over: Record = {}) => nonUsfService({ + readFormFields: vi.fn().mockResolvedValue([ + { code: 'name', inputType: 'text', label: 'Title', required: true, visible: true, editable: true }, + { code: 'board', inputType: 'select', label: 'Board', visible: true, editable: true }, + { code: 'skill', inputType: 'multiSelect', label: 'Skill', required: true, visible: true, editable: true }, + { code: 'difficultyTarget', label: 'Difficulty Target', required: true, visible: true, editable: true }, + ]), + readFramework: vi.fn().mockResolvedValue([ + { code: 'board', name: 'Board', index: 1, terms: [ + { code: 's1', name: 'Maths', associations: [{ category: 'topic', name: 'Algebra' }] }, + { code: 's2', name: 'Science', associations: [{ category: 'topic', name: 'Optics' }] }, + ] }, + { code: 'topic', name: 'Topic', index: 2, terms: [{ code: 't1', name: 'Algebra' }, { code: 't2', name: 'Optics' }] }, + ]), + searchFrameworks: vi.fn().mockResolvedValue([{ identifier: 'BMGS', name: 'BMGS' }, { identifier: 'USF', name: 'Universal Skills' }]), + ...over, + }); + const parentSelect = async () => (await screen.findByRole('option', { name: 'Maths' })).closest('select') as HTMLSelectElement; + + it('lets a parent picked after a framework switch still narrow the skills (positive)', async () => { + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: parentService(), content: { ...content, framework: 'BMGS' } }); + render(); + const picker = await screen.findByLabelText('Framework') as HTMLSelectElement; + await waitFor(() => expect(picker.value).toBe('BMGS')); + fireEvent.change(picker, { target: { value: 'USF' } }); + fireEvent.change(await parentSelect(), { target: { value: 'Maths' } }); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + expect(await screen.findByText('Algebra')).toBeInTheDocument(); + expect(screen.queryByText('Optics')).toBeNull(); + }); + + it('clears picked skills when their parent category changes (positive)', async () => { + const saveMetadata = vi.fn(); + const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: parentService(), saveMetadata, content: { ...content, framework: 'BMGS' } }); + render(); + fireEvent.change(await parentSelect(), { target: { value: 'Maths' } }); + fireEvent.click(await screen.findByRole('button', { name: /Select Topic/ })); + fireEvent.click(await screen.findByText('Algebra')); + fireEvent.mouseDown(document.body); + fireEvent.change(await parentSelect(), { target: { value: 'Science' } }); + expect(await screen.findByRole('button', { name: /Select Topic/ })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Save (changes|& Generate)/ })); + await waitFor(() => expect(saveMetadata).toHaveBeenCalled()); + expect(saveMetadata.mock.calls[0][0]).toHaveProperty('topic', []); + }); + }); + it('does not fall back to a free-text box when no category is literally named skill (negative)', async () => { const ed = makeEd({ isDynamicAssess: true, drawer: 'metadata', service: nonUsfService(), content }); render(); diff --git a/src/components/MetadataDrawer.tsx b/src/components/MetadataDrawer.tsx index de90aad..49d6ef7 100644 --- a/src/components/MetadataDrawer.tsx +++ b/src/components/MetadataDrawer.tsx @@ -242,7 +242,10 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { const [fwOptions, setFwOptions] = useState>([]); const contentChannel = (content as Record | null)?.channel as string | undefined; + // Bumped on every open/close, so a save still awaiting its pool check after the drawer closed is dropped. + const sessionRef = useRef(0); useEffect(() => { + sessionRef.current += 1; if (open) setSelectedFw(String(content?.framework || framework || '')); // eslint-disable-next-line react-hooks/exhaustive-deps }, [open, content?.identifier]); @@ -254,11 +257,15 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { /* Framework categories for taxonomy cascade. */ useEffect(() => { - const fw = selectedFw || content?.framework || framework; + // Dynamic Assess follows the picker alone, so choosing its placeholder leaves Skill without options. + const fw = ed.isDynamicAssess ? selectedFw : (content?.framework || framework); if (!open || !fw || loadedFw.current === fw) return; loadedFw.current = fw; - service.readFramework(fw).then(setCategories).catch(() => setCategories([])); - }, [open, content, framework, service, selectedFw]); + // Only the latest requested framework may apply, since a slower earlier read can resolve after it. + service.readFramework(fw) + .then((c) => { if (loadedFw.current === fw) setCategories(c); }) + .catch(() => { if (loadedFw.current === fw) setCategories([]); }); + }, [open, content, framework, service, selectedFw, ed.isDynamicAssess]); /* Form/read field definitions — save form for Edit Details, review form for * Submit-for-review. Keyed on subtype+action so switching mode refetches even @@ -379,6 +386,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setMulti(code, []); setVal(code, ''); } + // The Dynamic skill picker holds the deepest category's terms under its own code, so it resets with that category. + if (ed.isDynamicAssess && skillPickerCode && skillCategoryCode && orderedTaxoCodes.slice(idx + 1).includes(skillCategoryCode)) setMulti(skillPickerCode, []); }; /** A new framework means different category terms, so clear skill and every category value picked under the old one. */ @@ -387,7 +396,8 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { setSelectedFw(fw); setCategories([]); loadedFw.current = null; // otherwise re-picking the original framework (or the placeholder) never reloads its categories - setMultiVals((s) => ({ ...s, ...Object.fromEntries(codes.map((c) => [c, []])) })); + // Only fields already held as multiselects; an empty array for a single-select would mask its later value in selectedTaxo. + setMultiVals((s) => ({ ...s, ...Object.fromEntries(codes.filter((c) => c in s || c === skillPickerCode).map((c) => [c, []])) })); setValues((s) => ({ ...s, ...Object.fromEntries(codes.filter((c) => c in s).map((c) => [c, ''])) })); }; @@ -425,8 +435,9 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (isReplacedBySkillPicker(f)) continue; if (ed.isDynamicAssess && isSkillField(f)) { // Saved in the framework's deepest category field, where the backend reads the selection; left out until that field is known. - const arr = multiVals[f.code] ?? []; - if (skillCategoryCode) out[skillCategoryCode] = arr.length ? arr : undefined; + const arr = multiVals[f.code]; + // An empty array, not undefined, so removing the last skill clears it on the server too; an unseeded picker writes nothing. + if (skillCategoryCode && arr) out[skillCategoryCode] = arr; continue; } if (isMultiField(f, ed.isDynamicAssess)) { @@ -487,13 +498,14 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { if (miss.length) { setReviewErrors(miss); return; } } const out = buildOut(); - const generates = needsGeneration(withSelection(out)); + const generates = needsGeneration(withSelection(out), content?.framework ?? ''); // Submitting can't also generate, so changed settings must be saved (and generated) first. if (reviewSubmitMode && generates) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_SUBMIT_STALE'), 'error'); return; } if (generates) { + const session = sessionRef.current; setChecking(true); try { // The pool is only checked when this save will generate, so other edits cost no extra searches. @@ -501,6 +513,7 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { } finally { setChecking(false); } + if (sessionRef.current !== session) return; // the drawer closed or switched content during the check } setReviewErrors([]); // Only a Dynamic save names the skill field it wrote; other content keeps the plain call. @@ -649,7 +662,12 @@ const MetadataDrawer: React.FC<{ ed: EditorController }> = ({ ed }) => { }; // Live label: tells the author when Save will also generate questions. - const saveGenerates = ed.isDynamicAssess && open && needsGeneration(withSelection(buildOut())); + // needsGeneration parses the ECML body, so it reruns only when skill, target, framework or content change, not on every keystroke in other fields. + const saveGenerates = useMemo( + () => ed.isDynamicAssess && open && needsGeneration(withSelection(buildOut()), content?.framework ?? ''), + // eslint-disable-next-line react-hooks/exhaustive-deps + [ed.isDynamicAssess, open, content, fields, multiVals, diffTargets, selectedFw, skillCategoryCode, skillPickerCode], + ); // Skill always renders with the other fields (under its framework picker), even when a framework names a category 'skill'. const taxoFields = fields.filter((f) => taxoCodes.has(f.code) && !(ed.isDynamicAssess && isSkillField(f)) && !isReplacedBySkillPicker(f)); diff --git a/src/dynamicAssessDraw.test.ts b/src/dynamicAssessDraw.test.ts index 4cdf520..0ddad15 100644 --- a/src/dynamicAssessDraw.test.ts +++ b/src/dynamicAssessDraw.test.ts @@ -16,8 +16,7 @@ describe('ecmlBodyForUser', () => { it("previews only the user's draw per level, matching the portal's seed (positive)", () => { const out = ecmlBodyForUser(body(true), 'do_c', 'u1') as any; const kept = quizOf(out)['org.ekstep.question'].map((q: any) => q.id); - expect(kept).toHaveLength(2); - expect(kept.filter((id: string) => levels[id] === 'MEDIUM')).toEqual(pickForLearner(['b1', 'b2', 'b3'], 1, 'u1:do_c:MEDIUM')); + expect(kept).toEqual(['a2', 'b3']); // literal ids, so a change to the draw or its count fails here expect(JSON.parse(quizOf(out).config.__cdata).total_items).toBe(2); }); @@ -63,6 +62,12 @@ describe('isGenerationStale', () => { expect(isGenerationStale(undefined, { E: 1 }, ['Physics'])).toBe(false); expect(isGenerationStale(JSON.stringify(body(false)), { E: 9 }, ['Physics'])).toBe(false); }); + + it('reads a JSON-string generated target, so matching settings are not stale (negative)', () => { + const stringTarget = generated({ skills: ['Physics'], target: '{"E":1,"M":1,"D":0}' }); + expect(isGenerationStale(stringTarget, { E: 1, M: 1, D: 0 }, ['Physics'])).toBe(false); + expect(isGenerationStale(stringTarget, { E: 1, M: 2, D: 0 }, ['Physics'])).toBe(true); + }); }); describe('ecmlBodyForUser — fail closed and parity', () => { @@ -79,6 +84,16 @@ describe('ecmlBodyForUser — fail closed and parity', () => { expect(quizOf(ecmlBodyForUser(withTarget('nope'), 'do_c', 'u1'))['org.ekstep.question']).toEqual([]); }); + it('caps each level at its generated size ÷ multiplier, so an undersized pool is never shown whole (positive)', () => { + // 3 per level with target 3: uncapped this returned all 6 unshuffled; at ×2 only floor(3/2) = 1 per level is drawn. + expect(quizOf(ecmlBodyForUser(withTarget({ E: 3, M: 3, D: 0 }), 'do_c', 'u1', 2))['org.ekstep.question'].map((q: any) => q.id)).toEqual(['a2', 'b3']); + expect(quizOf(ecmlBodyForUser(withTarget({ E: 3, M: 3, D: 0 }), 'do_c', 'u1', 3))['org.ekstep.question'].map((q: any) => q.id)).toEqual(['a2', 'b3']); + }); + + it('draws the full target when the pool holds target × multiplier (negative)', () => { + expect(quizOf(ecmlBodyForUser(withTarget({ E: 2, M: 0, D: 0 }), 'do_c', 'u1', 1))['org.ekstep.question'].map((q: any) => q.id)).toEqual(['a1', 'a2']); + }); + it('accepts a JSON-string target like the portal does (positive)', () => { expect(quizOf(ecmlBodyForUser(withTarget('{"E":1,"M":1,"D":0}'), 'do_c', 'u1'))['org.ekstep.question']).toHaveLength(2); }); @@ -104,6 +119,18 @@ describe('selectedSkills and needsGeneration (the selection lives in the framewo expect(needsGeneration({ ...base, skill: ['Algebra'] } as never)).toBe(false); expect(needsGeneration({ ...base, primaryCategory: 'Learning Resource', dynamicSkills: ['Algebra'] })).toBe(false); }); + + it('regenerates when only the framework changed, since its pool can differ (positive/negative)', () => { + const generatedBody = JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Algebra'], target: { E: 1, M: 0, D: 0 } } }) } } }] }, + }); + const c = { primaryCategory: 'Dynamic Course Assessment', difficultyTarget: '{"E":1,"M":0,"D":0}', totalQuestions: 1, body: generatedBody, dynamicSkills: ['Algebra'] }; + expect(needsGeneration({ ...c, framework: 'USF' }, 'BMGS')).toBe(true); + expect(needsGeneration({ ...c, framework: 'BMGS' }, 'BMGS')).toBe(false); + expect(needsGeneration({ ...c, framework: 'USF' })).toBe(false); + expect(needsGeneration({ ...c, primaryCategory: 'Learning Resource', framework: 'USF' }, 'BMGS')).toBe(false); + expect(needsGeneration({ ...c, framework: 'USF' }, '')).toBe(false); // content saved without a framework, editor default filled in + }); }); describe('dynamicAssessSettings', () => { diff --git a/src/dynamicAssessDraw.ts b/src/dynamicAssessDraw.ts index 3c32ba8..50e9d85 100644 --- a/src/dynamicAssessDraw.ts +++ b/src/dynamicAssessDraw.ts @@ -3,7 +3,16 @@ import { DYNAMIC_ASSESS_MIN_CRITERIA, DYNAMIC_ASSESS_POOL_MULTIPLIER } from './constants'; const LEVELS = [['E', 'EASY'], ['M', 'MEDIUM'], ['D', 'DIFFICULT']] as const; -type AnyRecord = Record; +type Rec = Record; + +/** The value as a plain object, or undefined; narrows parsed ECML before it is indexed. */ +const asRec = (v: unknown): Rec | undefined => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Rec) : undefined); +/** ECML holds a single child as an object and several as an array; null/undefined is none. */ +const asList = (v: unknown): unknown[] => (v == null ? [] : Array.isArray(v) ? v : [v]); +/** A quiz's parsed config.__cdata, or undefined when missing or unparseable. */ +function quizConfig(quiz: Rec | undefined): Rec | undefined { + try { return asRec(JSON.parse(String(asRec(quiz?.config)?.__cdata ?? ''))); } catch { return undefined; } +} function hashSeed(seed: string): number { let h = 0x811c9dc5; @@ -37,21 +46,19 @@ export function pickForLearner(ids: string[], count: number, seed: string): stri return pool.slice(0, Math.max(0, count)); } -function parseBody(body: unknown): AnyRecord | null { - if (body && typeof body === 'object') return body as AnyRecord; +function parseBody(body: unknown): Rec | null { + if (body && typeof body === 'object') return body as Rec; if (typeof body !== 'string' || !body.trim()) return null; - try { return JSON.parse(body); } catch { return null; } + try { return asRec(JSON.parse(body)) ?? null; } catch { return null; } } /** The target (and, from newer job builds, skills) the job generated the current questions for; null when there is no generated quiz. */ -export function generatedSettings(body: unknown): { target: AnyRecord; skills?: string[] } | null { - const stages: AnyRecord[] = parseBody(body)?.theme?.stage ?? []; +export function generatedSettings(body: unknown): { target: Rec; skills?: string[] } | null { + const stages = asRec(parseBody(body)?.theme)?.stage; for (const stage of Array.isArray(stages) ? stages : []) { - for (const quiz of ([] as AnyRecord[]).concat(stage?.['org.ekstep.questionset'] ?? [])) { - let config: AnyRecord; - try { config = JSON.parse(quiz?.config?.__cdata ?? ''); } catch { continue; } - const block = config?.dynamic_assess; - if (block?.target) return { target: block.target, skills: Array.isArray(block.skills) ? block.skills.map(String) : undefined }; + for (const quiz of asList(asRec(stage)?.['org.ekstep.questionset'])) { + const block = asRec(quizConfig(asRec(quiz))?.dynamic_assess); + if (block?.target) return { target: parseTarget(block.target), skills: Array.isArray(block.skills) ? block.skills.map(String) : undefined }; } } return null; @@ -67,10 +74,10 @@ export function isGenerationStale(body: unknown, savedTarget: { E?: number; M?: return saved.size !== new Set(generated.skills).size || generated.skills.some((s) => !saved.has(s)); } -function parseTarget(raw: unknown): AnyRecord { +function parseTarget(raw: unknown): Rec { let value = raw; if (typeof value === 'string') { try { value = JSON.parse(value); } catch { value = undefined; } } - return value && typeof value === 'object' ? (value as AnyRecord) : {}; + return value && typeof value === 'object' ? (value as Rec) : {}; } /** The content's own minCriteria/multiplier (stored at create by knowlg-service), or the defaults for content created before they were, or holding unusable values; mirrors the publish job's nodeSetting. */ @@ -88,49 +95,54 @@ export function selectedSkills(c: Record, skillField: string): return [...new Set((Array.isArray(v) ? v : v ? [v] : []).map(String).filter(Boolean))]; } -/** Save must also generate when Skill + Difficulty Target are usable and there are no questions yet or they were built for other settings; any other save is a plain save. */ -export function needsGeneration(c: { primaryCategory?: string; dynamicSkills?: unknown; difficultyTarget?: unknown; totalQuestions?: unknown; body?: unknown } | null): boolean { +/** Save must also generate when Skill + Difficulty Target are usable and there are no questions yet, they were built for other settings, or the framework differs from `savedFramework`; any other save is a plain save. */ +export function needsGeneration(c: { primaryCategory?: string; dynamicSkills?: unknown; difficultyTarget?: unknown; totalQuestions?: unknown; body?: unknown; framework?: unknown } | null, savedFramework?: unknown): boolean { if (c?.primaryCategory !== 'Dynamic Course Assessment') return false; const skills = Array.isArray(c.dynamicSkills) ? c.dynamicSkills.map(String) : []; const target = parseTarget(c.difficultyTarget); const savedTarget = { E: Number(target.E) || 0, M: Number(target.M) || 0, D: Number(target.D) || 0 }; if (!skills.length || savedTarget.E + savedTarget.M + savedTarget.D <= 0) return false; + // Another framework can keep the same skill names in a different category field, so its questions come from another pool; content saved without one isn't a switch. + if (savedFramework && String(c.framework ?? '') !== String(savedFramework)) return true; return !(Number(c.totalQuestions ?? 0) > 0) || isGenerationStale(c.body, savedTarget, skills); } -/** Trims each generated quiz in a parsed ECML body to this user's draw; bodies without the job's dynamic_assess block are returned unchanged. */ -export function ecmlBodyForUser(body: unknown, contentId: string, userId: string | undefined): unknown { +/** Trims each generated quiz in a parsed ECML body to this user's draw; bodies without the job's dynamic_assess block are returned unchanged. `multiplier` is the content's own (dynamicAssessSettings). */ +export function ecmlBodyForUser(body: unknown, contentId: string, userId: string | undefined, multiplier = DYNAMIC_ASSESS_POOL_MULTIPLIER): unknown { if (!body || typeof body !== 'object') return body; - const stages: AnyRecord[] = Array.isArray((body as AnyRecord).theme?.stage) ? (body as AnyRecord).theme.stage : []; - if (!stages.some((s) => s?.['org.ekstep.questionset'])) return body; - const copy: AnyRecord = structuredClone(body); + const theme = asRec((body as Rec).theme); + const stages = Array.isArray(theme?.stage) ? theme.stage : []; + if (!stages.some((s) => asRec(s)?.['org.ekstep.questionset'])) return body; + const copy = structuredClone(body) as Rec; + const perLevel = Math.max(1, Math.trunc(multiplier) || 1); let changed = false; - for (const stage of copy.theme.stage as AnyRecord[]) { - const quizzes: AnyRecord[] = ([] as AnyRecord[]).concat(stage?.['org.ekstep.questionset'] ?? []); - for (const quiz of quizzes) { - let config: AnyRecord; - try { config = JSON.parse(quiz?.config?.__cdata ?? ''); } catch { continue; } - const block = config?.dynamic_assess; - const questions: AnyRecord[] = ([] as AnyRecord[]).concat(quiz['org.ekstep.question'] ?? []); - if (!block || questions.length === 0) continue; + for (const stage of (asRec(copy.theme)?.stage ?? []) as unknown[]) { + for (const quiz of asList(asRec(stage)?.['org.ekstep.questionset']).map(asRec)) { + const config = quizConfig(quiz); + const block = asRec(config?.dynamic_assess); + const questions = asList(quiz?.['org.ekstep.question']).map((q) => asRec(q) ?? {}); + if (!quiz || !config || !block || questions.length === 0) continue; // Fails closed like the portal: a missing, zero or unparseable target draws nothing rather than revealing the pool. const target = parseTarget(block.target); - const levels: AnyRecord = block.levels ?? {}; + const levels = asRec(block.levels) ?? {}; const picked = new Set(); for (const [key, level] of LEVELS) { const atLevel = questions.map((q) => String(q.id)).filter((id) => String(levels[id] ?? '').toUpperCase() === level); - pickForLearner(atLevel, Number(target[key]) || 0, `${userId || 'anonymous'}:${contentId}:${level}`).forEach((id) => picked.add(id)); + // Capped at what the job generated for this level, like the QuestionSet editor, so an undersized pool is never shown whole. + const count = Math.min(Number(target[key]) || 0, Math.floor(atLevel.length / perLevel)); + pickForLearner(atLevel, count, `${userId || 'anonymous'}:${contentId}:${level}`).forEach((id) => picked.add(id)); } const kept = questions.filter((q) => picked.has(String(q.id))); if (kept.length === questions.length) continue; - let items: AnyRecord[] = []; - try { items = JSON.parse(quiz?.data?.__cdata ?? '[]'); } catch { items = []; } + let items: Rec[] = []; + const data = asRec(quiz.data); + try { items = asList(JSON.parse(String(data?.__cdata ?? '[]'))).map((i) => asRec(i) ?? {}); } catch { items = []; } const keptItems = items.filter((item) => picked.has(String(item.identifier))); quiz['org.ekstep.question'] = kept; - if (quiz.data) quiz.data.__cdata = JSON.stringify(keptItems); + if (data) data.__cdata = JSON.stringify(keptItems); config.total_items = kept.length; config.max_score = keptItems.length ? keptItems.reduce((sum, item) => sum + (Number(item.max_score) || 1), 0) : kept.length; - quiz.config.__cdata = JSON.stringify(config); + (quiz.config as Rec).__cdata = JSON.stringify(config); changed = true; } } diff --git a/src/i18n/translations.ar.ts b/src/i18n/translations.ar.ts index 5c3bb67..be864f6 100644 --- a/src/i18n/translations.ar.ts +++ b/src/i18n/translations.ar.ts @@ -222,6 +222,7 @@ export const TRANSLATIONS_AR: Record = { DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'اختر إطارًا أولاً', DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'لم يتم إنشاء أي أسئلة لهذا المحتوى بعد.', ERROR_DYNAMIC_ASSESS_INPUTS: 'حدّد المهارة وهدف الصعوبة قبل إنشاء الأسئلة.', + ERROR_DYNAMIC_ASSESS_NO_USER: 'لا يوجد مستخدم في جلستك، لذا لا يمكن إنشاء الأسئلة. سجّل الدخول مرة أخرى وأعد المحاولة.', ERROR_POOL_INSUFFICIENT: 'لا توجد أسئلة كافية للمهارات المحددة', ERROR_POOL_CHECK_FAILED: 'تعذّر التحقق من توفر الأسئلة. يرجى المحاولة مرة أخرى.', ERROR_POOL_SHORTFALL: '{level}: المطلوب {requested} يحتاج {needed}، المتاح {available}', diff --git a/src/i18n/translations.en.ts b/src/i18n/translations.en.ts index 9ebfd9e..a8d9166 100644 --- a/src/i18n/translations.en.ts +++ b/src/i18n/translations.en.ts @@ -224,6 +224,7 @@ export const TRANSLATIONS_EN: Record = { DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'Select a framework first', DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'No questions have been generated for this content yet.', ERROR_DYNAMIC_ASSESS_INPUTS: 'Set Skill and Difficulty Target before generating questions.', + ERROR_DYNAMIC_ASSESS_NO_USER: 'Your session has no user, so questions can\'t be generated. Sign in again and retry.', ERROR_POOL_INSUFFICIENT: 'Not enough questions available for the selected skill(s)', ERROR_POOL_CHECK_FAILED: 'Could not verify question availability. Please try again.', ERROR_POOL_SHORTFALL: '{level}: requested {requested} needs {needed}, available {available}', diff --git a/src/i18n/translations.fr.ts b/src/i18n/translations.fr.ts index 787e81d..f7a1cd8 100644 --- a/src/i18n/translations.fr.ts +++ b/src/i18n/translations.fr.ts @@ -222,6 +222,7 @@ export const TRANSLATIONS_FR: Record = { DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'Sélectionnez d’abord un cadre', DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'Aucune question n’a encore été générée pour ce contenu.', ERROR_DYNAMIC_ASSESS_INPUTS: 'Définissez la compétence et l’objectif de difficulté avant de générer les questions.', + ERROR_DYNAMIC_ASSESS_NO_USER: 'Votre session n’a pas d’utilisateur, les questions ne peuvent donc pas être générées. Reconnectez-vous et réessayez.', ERROR_POOL_INSUFFICIENT: 'Pas assez de questions disponibles pour la ou les compétences sélectionnées', ERROR_POOL_CHECK_FAILED: 'Impossible de vérifier la disponibilité des questions. Veuillez réessayer.', ERROR_POOL_SHORTFALL: '{level} : {requested} demandées, {needed} nécessaires, {available} disponibles', diff --git a/src/i18n/translations.hi.ts b/src/i18n/translations.hi.ts index 111436a..2528a30 100644 --- a/src/i18n/translations.hi.ts +++ b/src/i18n/translations.hi.ts @@ -222,6 +222,7 @@ export const TRANSLATIONS_HI: Record = { DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'पहले फ्रेमवर्क चुनें', DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'इस सामग्री के लिए अभी तक कोई प्रश्न तैयार नहीं किया गया है।', ERROR_DYNAMIC_ASSESS_INPUTS: 'प्रश्न तैयार करने से पहले कौशल और कठिनाई लक्ष्य सेट करें।', + ERROR_DYNAMIC_ASSESS_NO_USER: 'आपके सत्र में कोई उपयोगकर्ता नहीं है, इसलिए प्रश्न तैयार नहीं किए जा सकते। फिर से साइन इन करें और पुनः प्रयास करें।', ERROR_POOL_INSUFFICIENT: 'चुने गए कौशल के लिए पर्याप्त प्रश्न उपलब्ध नहीं हैं', ERROR_POOL_CHECK_FAILED: 'प्रश्नों की उपलब्धता की जांच नहीं हो सकी। कृपया फिर से प्रयास करें।', ERROR_POOL_SHORTFALL: '{level}: अनुरोधित {requested}, आवश्यक {needed}, उपलब्ध {available}', diff --git a/src/i18n/translations.pt.ts b/src/i18n/translations.pt.ts index 40f7901..0bcd723 100644 --- a/src/i18n/translations.pt.ts +++ b/src/i18n/translations.pt.ts @@ -222,6 +222,7 @@ export const TRANSLATIONS_PT: Record = { DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'Selecione uma estrutura primeiro', DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'Nenhuma questão foi gerada para este conteúdo ainda.', ERROR_DYNAMIC_ASSESS_INPUTS: 'Defina a Habilidade e a Meta de dificuldade antes de gerar as questões.', + ERROR_DYNAMIC_ASSESS_NO_USER: 'Sua sessão não tem usuário, então as questões não podem ser geradas. Entre novamente e tente de novo.', ERROR_POOL_INSUFFICIENT: 'Não há questões suficientes disponíveis para a(s) habilidade(s) selecionada(s)', ERROR_POOL_CHECK_FAILED: 'Não foi possível verificar a disponibilidade de questões. Tente novamente.', ERROR_POOL_SHORTFALL: '{level}: solicitadas {requested}, necessárias {needed}, disponíveis {available}', diff --git a/src/i18n/translations.ta.ts b/src/i18n/translations.ta.ts index a031040..5989c40 100644 --- a/src/i18n/translations.ta.ts +++ b/src/i18n/translations.ta.ts @@ -222,6 +222,7 @@ export const TRANSLATIONS_TA: Record = { DYNAMIC_ASSESS_SELECT_FRAMEWORK_FIRST: 'முதலில் ஒரு கட்டமைப்பைத் தேர்ந்தெடுக்கவும்', DYNAMIC_ASSESS_EMPTY_SUB_READONLY: 'இந்த உள்ளடக்கத்திற்கு இதுவரை கேள்விகள் எதுவும் உருவாக்கப்படவில்லை.', ERROR_DYNAMIC_ASSESS_INPUTS: 'கேள்விகளை உருவாக்கும் முன் திறன் மற்றும் கடினத்தன்மை இலக்கை அமைக்கவும்.', + ERROR_DYNAMIC_ASSESS_NO_USER: 'உங்கள் அமர்வில் பயனர் இல்லை, எனவே கேள்விகளை உருவாக்க முடியாது. மீண்டும் உள்நுழைந்து முயற்சிக்கவும்.', ERROR_POOL_INSUFFICIENT: 'தேர்ந்தெடுத்த திறன்களுக்குப் போதுமான கேள்விகள் இல்லை', ERROR_POOL_CHECK_FAILED: 'கேள்விகள் கிடைப்பதைச் சரிபார்க்க முடியவில்லை. மீண்டும் முயற்சிக்கவும்.', ERROR_POOL_SHORTFALL: '{level}: கோரியது {requested}, தேவை {needed}, கிடைப்பது {available}', diff --git a/src/services/ContentEditorService.test.ts b/src/services/ContentEditorService.test.ts index a4b9dd8..839ed9c 100644 --- a/src/services/ContentEditorService.test.ts +++ b/src/services/ContentEditorService.test.ts @@ -114,6 +114,36 @@ describe('ContentEditorService.searchAssessmentItemBucketCounts', () => { } }); + it('retries a search that fails once instead of failing the whole batch (positive)', async () => { + const savedFetch = globalThis.fetch; + let calls = 0; + globalThis.fetch = (async () => { + calls += 1; + if (calls === 2) return { ok: false, status: 503, json: async () => ({}) }; + return { ok: true, json: async () => ({ responseCode: 'OK', result: { count: 3 } }) }; + }) as unknown as typeof fetch; + try { + expect(await new ContentEditorService().searchAssessmentItemBucketCounts(['A'], 'ch1')).toEqual({ A: { E: 3, M: 3, D: 3 } }); + expect(calls).toBe(4); + } finally { + globalThis.fetch = savedFetch; + } + }); + + it('still fails when a search fails twice, so the save is not checked against a guess (negative)', async () => { + const savedFetch = globalThis.fetch; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + const f = JSON.parse(String(init?.body)).request.filters; + if (f.qlevel === 'MEDIUM') return { ok: false, status: 503, json: async () => ({}) }; + return { ok: true, json: async () => ({ responseCode: 'OK', result: { count: 3 } }) }; + }) as unknown as typeof fetch; + try { + await expect(new ContentEditorService().searchAssessmentItemBucketCounts(['A'], 'ch1')).rejects.toBeTruthy(); + } finally { + globalThis.fetch = savedFetch; + } + }); + it('makes no calls when no skills are given (negative)', async () => { const savedFetch = globalThis.fetch; let called = false; diff --git a/src/services/ContentEditorService.ts b/src/services/ContentEditorService.ts index 412ce39..f6aec32 100644 --- a/src/services/ContentEditorService.ts +++ b/src/services/ContentEditorService.ts @@ -460,7 +460,7 @@ export class ContentEditorService { const results = await Promise.all(pairs.map(({ skill, qlevel }) => { const filters: Record = { status: ['Live'], objectType: 'AssessmentItem', [categoryField]: [skill], qlevel }; if (channel) filters.channel = channel; - return this.request<{ count?: number }>('POST', this.ep.compositeSearch, { request: { filters, fields: ['identifier'], limit: 1 } }); + return this.searchCount(filters); })); const out: Record> = {}; pairs.forEach(({ skill, key }, i) => { @@ -470,13 +470,15 @@ export class ContentEditorService { return out; } + /** One pool count search, retried once so a single transient failure doesn't refuse the whole save; search-service allows no qlevel facet to merge these. */ + private searchCount(filters: Record): Promise<{ count?: number }> { + const run = () => this.request<{ count?: number }>('POST', this.ep.compositeSearch, { request: { filters, fields: ['identifier'], limit: 1 } }); + return run().catch(() => run()); + } + /** Live AssessmentItems per skill, with the same filters knowlg-service uses to reject a refresh (no channel, any level). */ async searchSkillPoolCounts(skills: string[], categoryField = 'skill'): Promise> { - const results = await Promise.all(skills.map((skill) => this.request<{ count?: number }>( - 'POST', - this.ep.compositeSearch, - { request: { filters: { status: ['Live'], objectType: 'AssessmentItem', [categoryField]: [skill] }, fields: ['identifier'], limit: 1 } }, - ))); + const results = await Promise.all(skills.map((skill) => this.searchCount({ status: ['Live'], objectType: 'AssessmentItem', [categoryField]: [skill] }))); return Object.fromEntries(skills.map((skill, i) => [skill, Number(results[i]?.count ?? 0) || 0])); } diff --git a/src/types.ts b/src/types.ts index 95ff22b..2faf4dd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -84,8 +84,8 @@ export interface ContentData { rejectComment?: string; /** Dynamic Assess only, in memory: the selected skills, read from the framework's deepest category field (e.g. "topic"); never sent back as-is. */ dynamicSkills?: string[]; - /** Dynamic Assess custom field (Dynamic Course Assessment category only). */ - difficultyTarget?: { E?: number; M?: number; D?: number }; + /** Dynamic Assess custom field (Dynamic Course Assessment category only); the API stores and returns it as a JSON string. */ + difficultyTarget?: string | { E?: number; M?: number; D?: number }; /** Dynamic Assess only, set by knowlg-service at create; read through dynamicAssessSettings, which falls back for older content. */ minCriteria?: number; multiplier?: number; diff --git a/src/useEditor.test.ts b/src/useEditor.test.ts index 8dbd30c..bd7484f 100644 --- a/src/useEditor.test.ts +++ b/src/useEditor.test.ts @@ -396,6 +396,130 @@ describe('useEditor — Dynamic Assess refreshBody timeout', () => { }); }); +describe('useEditor — Dynamic Assess completion and writes during generation', () => { + const quiz = (levels: Record) => JSON.stringify({ + theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 1, M: 0, D: 0 }, levels } }) } } }] }, + }); + const oldBody = quiz({ q1: 'EASY', q2: 'EASY' }); + const daContent = (over: Partial = {}): ContentData => videoContent({ + identifier: 'do_da_c', mimeType: 'application/vnd.ekstep.ecml-archive', + primaryCategory: 'Dynamic Course Assessment', status: 'Draft', totalQuestions: 1, lastUpdatedOn: 't0', + skill: ['Physics'], difficultyTarget: '{"E":1,"M":0,"D":0}', body: oldBody, ...over, + } as Partial); + + it('reports done on the first poll when the job wrote before the baseline read (positive)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + // Baseline and every poll already see the job's write: new body, new timestamp. + (service.readContent as ReturnType).mockResolvedValue(daContent({ lastUpdatedOn: 't1', body: quiz({ q3: 'EASY', q4: 'EASY' }) })); + await act(async () => { await result.current.refreshBody(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + expect(result.current.toast?.msg).toBe('Questions generated'); + } finally { + vi.useRealTimers(); + } + }); + + it('keeps waiting while the Live edit copy only carries the old body (negative)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + // The API's edit copy bumps lastUpdatedOn before the baseline read but keeps the old quiz. + (service.readContent as ReturnType).mockResolvedValue(daContent({ lastUpdatedOn: 't1' })); + await act(async () => { await result.current.refreshBody(); }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000 * 3); }); + expect(result.current.dynamicAssessRefreshing).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it('ignores header Save and Send for Review while generating, and allows them after (positive/negative)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + await act(async () => { await result.current.refreshBody(); }); + expect(result.current.dynamicAssessRefreshing).toBe(true); + await act(async () => { await result.current.saveDraft(); await result.current.sendForReview(); }); + expect(service.updateContent).not.toHaveBeenCalled(); + expect(service.sendForReview).not.toHaveBeenCalled(); + + (service.readContent as ReturnType).mockResolvedValue(daContent({ lastUpdatedOn: 't2', body: quiz({ q5: 'EASY', q6: 'EASY' }) })); + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + await act(async () => { await result.current.saveDraft(); }); + expect(service.updateContent).toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it('blocks Generate with a translated message when the session has no user id (positive)', async () => { + const refreshContentBody = vi.fn(); + const service = svc({ refreshContentBody }); + (service.readContent as ReturnType).mockResolvedValue(daContent()); + const { result } = renderHook(() => useEditor({ context: { ...mockContext, user: { ...mockContext.user, id: '' } }, contentId: 'do_da_c', service })); + await waitFor(() => expect(result.current.content?.identifier).toBe('do_da_c')); + await act(async () => { await result.current.refreshBody(); }); + expect(refreshContentBody).not.toHaveBeenCalled(); + expect(result.current.toast?.msg).toMatch(/no user/); + expect(result.current.dynamicAssessRefreshing).toBe(false); + }); + + it('never stacks a poll on a read still in flight (positive)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + vi.useFakeTimers(); + try { + const readContent = service.readContent as ReturnType; + readContent.mockResolvedValueOnce(daContent()); // baseline + await act(async () => { await result.current.refreshBody(); }); + readContent.mockClear(); + readContent.mockReturnValue(new Promise(() => {})); // the first poll's read never returns + await act(async () => { await vi.advanceTimersByTimeAsync(3000 * 4); }); + expect(readContent).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it('times out in a hidden tab instead of keeping the overlay up forever (positive)', async () => { + const service = svc({ refreshContentBody: vi.fn().mockResolvedValue({}) }); + const result = await mountWithContent(service, daContent()); + const originalHidden = Object.getOwnPropertyDescriptor(Document.prototype, 'hidden'); + vi.useFakeTimers(); + try { + await act(async () => { await result.current.refreshBody(); }); + Object.defineProperty(document, 'hidden', { configurable: true, get: () => true }); + await act(async () => { await vi.advanceTimersByTimeAsync(3000 * 21); }); + expect(result.current.dynamicAssessRefreshing).toBe(false); + expect(result.current.toast?.msg).toMatch(/haven't appeared yet/); + } finally { + vi.useRealTimers(); + if (originalHidden) Object.defineProperty(document, 'hidden', originalHidden); + } + }); + + it('regenerates when a save only switches the framework (positive)', async () => { + const refreshContentBody = vi.fn().mockResolvedValue({}); + const result = await mountWithContent(svc({ refreshContentBody }), daContent({ framework: 'BMGS' })); + await act(async () => { await result.current.saveMetadata({ framework: 'USF', skill: ['Physics'] }, { skillField: 'skill' }); }); + await waitFor(() => expect(refreshContentBody).toHaveBeenCalled()); + }); + + it('is a plain save when the framework stays the same (negative)', async () => { + const refreshContentBody = vi.fn(); + const result = await mountWithContent(svc({ refreshContentBody }), daContent({ framework: 'BMGS' })); + await act(async () => { await result.current.saveMetadata({ framework: 'BMGS', skill: ['Physics'] }, { skillField: 'skill' }); }); + expect(refreshContentBody).not.toHaveBeenCalled(); + }); +}); + describe('useEditor — Save also generates when needed', () => { const generatedBody = JSON.stringify({ theme: { stage: [{ 'org.ekstep.questionset': { config: { __cdata: JSON.stringify({ dynamic_assess: { skills: ['Physics'], target: { E: 1, M: 0, D: 0 } } }) } } }] }, diff --git a/src/useEditor.ts b/src/useEditor.ts index a8354fb..d07ca66 100644 --- a/src/useEditor.ts +++ b/src/useEditor.ts @@ -6,7 +6,7 @@ import type { } from './types'; import { ContentEditorService } from './services/ContentEditorService'; import { difficultyTargetTotal, toDifficultyTarget } from './difficultyTarget'; -import { isGenerationStale, needsGeneration, selectedSkills } from './dynamicAssessDraw'; +import { generatedSettings, isGenerationStale, needsGeneration, selectedSkills } from './dynamicAssessDraw'; import { deepestCategoryCode } from './taxonomy'; import { UploadService, detectFileMime, detectUrlMime } from './services/UploadService'; import { TelemetryService } from './telemetry/TelemetryService'; @@ -460,7 +460,7 @@ export function useEditor(opts: UseEditorOptions) { /** `skillField`: the Dynamic Assess skill field the drawer wrote (its framework's deepest category), so the in-memory selection follows the save. */ const saveMetadata = useCallback( async (fields: Record, opts: { skillField?: string } = {}) => { - if (!content?.identifier) return; + if (!content?.identifier || generatingRef.current) return; setBusy(true); setBusyAction('save-metadata'); try { @@ -472,7 +472,7 @@ export function useEditor(opts: UseEditorOptions) { telemetry.current?.interact('modify', 'metadata', 'save'); emit(EDITOR_EVENTS.SAVED, { id: content.identifier }); // Dynamic Assess generates as part of Save, only when Skill/Target need it; generation shows its own loader and toast. - if (needsGeneration(merged)) void generateRef.current(merged); + if (needsGeneration(merged, content.framework ?? '')) void generateRef.current(merged); else showToast(t(lang, 'TOAST_DETAILS_SAVED')); } catch (err) { telemetry.current?.error(String((err as Error)?.message ?? err), 'edit'); @@ -487,6 +487,7 @@ export function useEditor(opts: UseEditorOptions) { /* ---- Save draft (header Save) ---- */ const saveDraft = useCallback(async () => { + if (generatingRef.current) return; // a write while the job runs could race it and look like its completion if (!content?.identifier) { showToast(t(lang, 'TOAST_SAVED')); return; @@ -510,7 +511,7 @@ export function useEditor(opts: UseEditorOptions) { /* ---- Collaborators ---- */ const saveCollaborators = useCallback( async (collaborators: string[]) => { - if (!content?.identifier) return; + if (!content?.identifier || generatingRef.current) return; setBusy(true); setBusyAction('collaborator'); try { @@ -575,7 +576,7 @@ export function useEditor(opts: UseEditorOptions) { }, [content, lang, service, validateForReview, context]); const sendForReview = useCallback(async () => { - if (!content?.identifier) return; + if (!content?.identifier || generatingRef.current) return; if (isStaleGeneration(content)) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_STALE'), 'error'); return; } if (lacksGeneratedQuestions(content)) { showToast(t(lang, 'DYNAMIC_ASSESS_GENERATE_FIRST'), 'error'); return; } setBusy(true); @@ -603,7 +604,7 @@ export function useEditor(opts: UseEditorOptions) { /** Saves edited metadata, re-validates against the review form, and only submits for review if valid. */ const saveMetadataAndSubmit = useCallback( async (fields: Record, opts: { skillField?: string } = {}) => { - if (!content?.identifier) return; + if (!content?.identifier || generatingRef.current) return; setBusy(true); setBusyAction('save-submit'); let merged: ContentData; @@ -662,7 +663,7 @@ export function useEditor(opts: UseEditorOptions) { /* ---- Reviewer actions ---- */ const publish = useCallback(async () => { - if (!content?.identifier) return; + if (!content?.identifier || generatingRef.current) return; if (isStaleGeneration(content)) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_STALE_REVIEW'), 'error'); return; } if (lacksGeneratedQuestions(content)) { showToast(t(lang, 'DYNAMIC_ASSESS_GENERATE_FIRST'), 'error'); return; } setBusy(true); @@ -684,7 +685,7 @@ export function useEditor(opts: UseEditorOptions) { const requestChanges = useCallback( async (reasons: string[], comment?: string) => { - if (!content?.identifier) return; + if (!content?.identifier || generatingRef.current) return; setBusy(true); setBusyAction('reject'); try { @@ -775,17 +776,26 @@ export function useEditor(opts: UseEditorOptions) { showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_INPUTS'), 'error'); return; } + // The API rejects a blank lastPublishedBy, so say why here rather than surface its raw error. + if (!context.user?.id) { + showToast(t(lang, 'ERROR_DYNAMIC_ASSESS_NO_USER'), 'error'); + return; + } const id = current.identifier; // Polled reads must carry the skill field too, or the refreshed content would lose the selection. const skillField = skillFieldRef.current; const readGenerated = () => service.readContent(id, 'edit', { withBody: true, extraFields: [skillField] }).then((c) => withDynamicSkills(c, skillField)); // lastUpdatedOn changes on every job write even when the count doesn't. const snapshot = (c: ContentData | null) => `${String(c?.totalQuestions ?? '')}|${String(c?.lastUpdatedOn ?? '')}`; + const bodyKey = (b: unknown) => (typeof b === 'string' ? b : JSON.stringify(b ?? '')); + // A generated quiz unlike the pre-request body is the job's own write, even if it landed before the baseline read. + const preBody = bodyKey(current.body); + const landed = (c: ContentData) => snapshot(c) !== baseline || (generatedSettings(c.body) !== null && bodyKey(c.body) !== preBody); setDynamicAssessRefreshing(true); generatingRef.current = true; let baseline: string; try { - await service.refreshContentBody(id, context.user?.id ?? ''); + await service.refreshContentBody(id, context.user.id); telemetry.current?.interact('click', 'dynamicAssessRefreshButton', 'refresh-body'); // Baseline only after the API returns: for Live content it first writes the edit copy, which also bumps lastUpdatedOn. baseline = snapshot(await service.readContent(id).catch(() => current)); @@ -798,23 +808,26 @@ export function useEditor(opts: UseEditorOptions) { // The job writes asynchronously: poll until it lands, bounded like the transcripts poll below. let attempts = 0; let done = false; + // One read at a time, so a slow read doesn't stack polls against a backend that is busy running the job. + let inFlight = false; const poll = () => { + if (inFlight) return; + inFlight = true; readGenerated().then((updated) => { if (!mountedRef.current || done) return; - if (snapshot(updated) !== baseline) { + if (landed(updated)) { done = true; generatingRef.current = false; setContent(updated); setDynamicAssessRefreshing(false); showToast(t(lang, 'TOAST_DYNAMIC_ASSESS_REFRESH_DONE')); } - }).catch(() => {}); + }).catch(() => {}).finally(() => { inFlight = false; }); }; if (refreshPollRef.current) clearInterval(refreshPollRef.current); const interval = setInterval(() => { if (done || !mountedRef.current) { clearInterval(interval); return; } - // A hidden tab doesn't poll, so it mustn't use up attempts either. - if (typeof document !== 'undefined' && document.hidden) return; + // Hidden ticks still count, like the transcript poll, so the cap stays a real timeout and the overlay can't stay up forever. attempts += 1; if (attempts > DYNAMIC_ASSESS_POLL_MAX_ATTEMPTS) { clearInterval(interval); @@ -824,7 +837,7 @@ export function useEditor(opts: UseEditorOptions) { .then((updated) => { if (!mountedRef.current) return; setContent(updated); - showToast(t(lang, snapshot(updated) !== baseline ? 'TOAST_DYNAMIC_ASSESS_REFRESH_DONE' : 'TOAST_DYNAMIC_ASSESS_PENDING')); + showToast(t(lang, landed(updated) ? 'TOAST_DYNAMIC_ASSESS_REFRESH_DONE' : 'TOAST_DYNAMIC_ASSESS_PENDING')); }) .catch(() => { if (mountedRef.current) showToast(t(lang, 'TOAST_DYNAMIC_ASSESS_PENDING')); }) .finally(() => { @@ -833,6 +846,7 @@ export function useEditor(opts: UseEditorOptions) { }); return; } + if (typeof document !== 'undefined' && document.hidden) return; poll(); }, DYNAMIC_ASSESS_POLL_MS); refreshPollRef.current = interval;