diff --git a/docs/AI.md b/docs/AI.md index 9fde298..5f68aef 100644 --- a/docs/AI.md +++ b/docs/AI.md @@ -224,7 +224,9 @@ link also has a cap of 500 requests per hour across all visitors. Class and exam links have a third visitor switch, **Generate quizzes and flashcards** (off by default). Visitors choose only the kind, how many (quizzes default to 50, at most 50: one exam; -flashcards default to 30, at most 75), the difficulty, which of the link's class materials to use and, +flashcards default to 30, at most 75), on a class link which exam the set is for (required +when the class has exams; it opens on the latest exam with materials, and the set uses only +that exam's materials and is saved into it), the difficulty, which of the link's class materials to use and, for quizzes, "Include med math" (5 calculation questions). Quizzes are NCLEX style with 25% select-all and the Python check. A link may make 4 quizzes and 2 flashcard sets a day (local midnight, failed attempts not counted), on top of the per-device request limit; **Reset diff --git a/server/routes/shares.ts b/server/routes/shares.ts index fd0280c..4abf15e 100644 --- a/server/routes/shares.ts +++ b/server/routes/shares.ts @@ -496,7 +496,12 @@ export function publicRoutes(app: AppContext): Hono { kind: z.enum(['quiz', 'deck']), count: z.number().int().min(1).max(SHARE_DECK_MAX).optional(), difficulty: z.enum(['easy', 'medium', 'hard', 'mixed']).default('mixed'), - /** Class materials to use; empty or absent: all of them. */ + /** + * Class links: the exam the set is for (null: not in an exam). Required when the class has + * exams. The set uses only that exam's materials and is saved into it. + */ + examId: z.string().max(64).nullable().optional(), + /** Class materials to use, from the chosen exam; empty or absent: all of them. */ documentIds: z.array(z.string().max(64)).max(50).optional(), /** Quizzes: add medication math questions, whatever the material covers. */ math: z.boolean().optional(), @@ -512,8 +517,18 @@ export function publicRoutes(app: AppContext): Hono { const body = await readBody(c, generateSchema); if (share.kind !== 'class' && share.kind !== 'folder') throw gone(); requireAi(c, share, 'generate'); - const docs = collectionItems(app, share).filter((i) => i.kind === 'document'); - if (docs.length === 0) throw new HttpError(400, 'no_materials', 'There are no class materials on this link to generate from.'); + // Which exam the set is for: an exam link's own, or the visitor's choice on a class link. + let examId: string | null = share.kind === 'folder' ? share.target_id : null; + if (share.kind === 'class') { + const exams = db.all<{ id: string }>('SELECT id FROM folders WHERE class_id = ?', share.target_id); + if (body.examId === undefined && exams.length > 0) throw new HttpError(400, 'exam_required', 'Choose which exam this is for.'); + if (body.examId && !exams.some((e) => e.id === body.examId)) throw gone(); + examId = body.examId ?? null; + } + const docs = collectionItems(app, share).filter( + (i) => i.kind === 'document' && (share.kind === 'folder' || (examId ? i.folderId === examId : !i.folderId || !db.get('SELECT 1 FROM folders WHERE id = ?', i.folderId))), + ); + if (docs.length === 0) throw new HttpError(400, 'no_materials', examId || share.kind === 'folder' ? 'This exam has no class materials to generate from.' : 'There are no class materials outside the exams to generate from.'); const chosen = body.documentIds?.length ? body.documentIds : docs.map((d) => d.id); if (chosen.some((id) => !docs.some((d) => d.id === id))) throw gone(); const usage = generateUsage(app, share)[body.kind]; @@ -529,7 +544,7 @@ export function publicRoutes(app: AppContext): Hono { { kind: body.kind, classId: sharedClassId(share), - folderId: share.kind === 'folder' ? share.target_id : null, + folderId: examId, source: { documentIds: chosen }, count, difficulty: body.difficulty, diff --git a/tests/revision4.test.ts b/tests/revision4.test.ts index e5e9b0f..825ed17 100644 --- a/tests/revision4.test.ts +++ b/tests/revision4.test.ts @@ -277,3 +277,40 @@ describe('share-link visitors can generate', () => { expect(draft.meta.request).toMatchObject({ count: 50, sataShare: 0.25, format: 'exam' }); }); }); + +describe('class links: visitors choose the exam', () => { + beforeEach(async () => { + const { resetShareAiLimits } = await import('../server/routes/shares.ts'); + resetShareAiLimits(); + }); + + it('requires an exam, uses only its materials and saves the set into it', async () => { + await connectAi(); + const cls = (await t.api('POST', '/api/classes', { name: 'Med-Surg' })).body.class; + const exam1 = (await t.api('POST', `/api/classes/${cls.id}/folders`, { name: 'Exam 1' })).body.folder; + const exam2 = (await t.api('POST', `/api/classes/${cls.id}/folders`, { name: 'Exam 2' })).body.folder; + const cardiac = (await t.api('POST', '/api/documents/text', { classId: cls.id, folderId: exam1.id, title: 'Cardiac', text: '# Cardiac\n\nDigoxin toxicity causes nausea and visual halos.' })).body.document; + await t.api('POST', '/api/documents/text', { classId: cls.id, folderId: exam2.id, title: 'Renal', text: '# Renal\n\nHyperkalemia in kidney failure shows peaked T waves. Kayexalate removes potassium.' }); + await queueIdle(t.ctx); + const share = (await t.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share; + await t.api('PATCH', `/api/shares/${share.id}`, { ai: { generate: true } }); + const token = share.token; + + const missing = await t.api('POST', `/api/public/${token}/generate`, { kind: 'deck', count: 3 }); + expect(missing.status).toBe(400); + expect(missing.body.error.message).toContain('Choose which exam'); + // Materials from another exam are refused. + expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'deck', count: 3, examId: exam2.id, documentIds: [cardiac.id] })).status).toBe(404); + + mock.requests.length = 0; + const res = await t.api('POST', `/api/public/${token}/generate`, { kind: 'deck', count: 3, examId: exam2.id }); + expect(res.status).toBe(202); + const draft = await waitDraft(res.body.set.id); + expect(draft.status).toBe('saved'); + const deck = (await t.api('GET', `/api/decks/${draft.savedId}`)).body.deck; + expect(deck.folderId).toBe(exam2.id); + const sent = JSON.stringify(chatCalls().map((r) => r.body.messages)); + expect(sent).toContain('Kayexalate'); + expect(sent).not.toContain('Digoxin'); + }); +}); diff --git a/web/src/features/SharedGenerate.tsx b/web/src/features/SharedGenerate.tsx index ac456a1..4be474e 100644 --- a/web/src/features/SharedGenerate.tsx +++ b/web/src/features/SharedGenerate.tsx @@ -108,7 +108,8 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol onClose={() => setOpen(false)} token={token} info={info} - documents={data.items.filter((i) => i.kind === 'document')} + allDocuments={data.items.filter((i) => i.kind === 'document')} + exams={data.folders} onStarted={(next) => qc.setQueryData(key, next)} /> @@ -120,17 +121,25 @@ function GenerateDialog({ onClose, token, info, - documents, + allDocuments, + exams, onStarted, }: { open: boolean; onClose: () => void; token: string; info: SharedGenerated; - documents: PublicCollection['items']; + allDocuments: PublicCollection['items']; + /** A class link's exams (empty on an exam link, which is one exam already). */ + exams: PublicCollection['folders']; onStarted: (next: SharedGenerated) => void; }) { const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used); + // On a class link the visitor picks the exam: its materials are offered, and the set is saved into it. + const inExam = (examId: string) => allDocuments.filter((d) => (examId ? d.folderId === examId : !d.folderId || !exams.some((e) => e.id === d.folderId))); + const looseCount = exams.length ? inExam('').length : 0; + const [examId, setExamId] = useState(''); + const documents = exams.length ? inExam(examId) : allDocuments; const [kind, setKind] = useState('quiz'); const [count, setCount] = useState(info.limits.quizMax); const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed'); @@ -145,7 +154,10 @@ function GenerateDialog({ const k: Kind = left('quiz') > 0 || left('deck') === 0 ? 'quiz' : 'deck'; setKind(k); setCount(k === 'quiz' ? info.limits.quizMax : 30); - setDocIds(documents.map((d) => d.id)); + // Start on the latest exam that has materials. + const start = exams.length ? ([...exams].reverse().find((e) => inExam(e.id).length > 0)?.id ?? '') : ''; + setExamId(start); + setDocIds((exams.length ? inExam(start) : allDocuments).map((d) => d.id)); setError(''); // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); @@ -158,6 +170,7 @@ function GenerateDialog({ kind, count, difficulty, + ...(exams.length ? { examId: examId || null } : {}), documentIds: docIds.length === documents.length ? [] : docIds, math: kind === 'quiz' && math, }); @@ -203,6 +216,28 @@ function GenerateDialog({ className="w-full" /> {none && This link has made all its {kind === 'quiz' ? 'quizzes' : 'flashcard sets'} for today. Try again tomorrow.} + {exams.length > 0 && ( + + + + )}
setCount(Math.max(1, Math.min(max, Number(e.target.value) || 1)))} />