Study/server/services/templates.ts
Elijah eae109c166 Add HTTP routes, app wiring, V1 migration, backups, templates and API tests
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 08:22:47 -07:00

229 lines
8.3 KiB
TypeScript

/**
* Reusable templates.
* - quiz / deck: a content skeleton (or a full copy of an existing item) to start from.
* - generation: a saved set of AI generation options.
* Built-in templates are (re)seeded at startup and cannot be edited, only copied.
*/
import { z } from 'zod';
import type { DB } from '../db.ts';
import { notFound } from '../http.ts';
import { newId, now, parseJson } from '../util.ts';
export const templateInputSchema = z.object({
kind: z.enum(['quiz', 'deck', 'generation']),
name: z.string().trim().min(1).max(120),
description: z.string().max(1000).optional().default(''),
payload: z.record(z.string(), z.unknown()),
});
interface TemplateRow {
id: string;
kind: 'quiz' | 'deck' | 'generation';
name: string;
description: string;
payload: string;
builtin: number;
created_at: number;
updated_at: number;
}
const mapTemplate = (r: TemplateRow) => ({
id: r.id,
kind: r.kind,
name: r.name,
description: r.description,
payload: parseJson<Record<string, unknown>>(r.payload, {}),
builtin: Boolean(r.builtin),
updatedAt: r.updated_at,
});
const BUILTIN: { id: string; kind: TemplateRow['kind']; name: string; description: string; payload: Record<string, unknown> }[] = [
{
id: 'builtin-gen-nclex',
kind: 'generation',
name: 'NCLEX practice set',
description: '25 clinical-judgment questions, about a third select-all, mixed difficulty.',
payload: { kind: 'quiz', count: 25, style: 'nclex', difficulty: 'mixed', sataShare: 0.3 },
},
{
id: 'builtin-gen-priority',
kind: 'generation',
name: 'Prioritization and delegation',
description: '15 hard questions on who to see first, what to do first, and what can be delegated.',
payload: {
kind: 'quiz',
count: 15,
style: 'nclex',
difficulty: 'hard',
sataShare: 0.2,
instructions: 'Every question must test prioritisation, delegation or assignment: which client to see first, which action comes first, or which task can be delegated to an LPN/LVN or assistive personnel.',
},
},
{
id: 'builtin-gen-recall',
kind: 'generation',
name: 'Quick recall check',
description: '20 short multiple-choice questions on key facts, values and definitions.',
payload: { kind: 'quiz', count: 20, style: 'recall', difficulty: 'easy', sataShare: 0 },
},
{
id: 'builtin-gen-drugs',
kind: 'generation',
name: 'Medication cards',
description: 'One card per drug: class, action, uses, adverse effects, nursing considerations, teaching.',
payload: { kind: 'deck', count: 30, cardStyle: 'medication' },
},
{
id: 'builtin-gen-terms',
kind: 'generation',
name: 'Key terms',
description: '40 term-and-definition cards.',
payload: { kind: 'deck', count: 40, cardStyle: 'definition' },
},
{
id: 'builtin-gen-guide',
kind: 'generation',
name: 'Chapter study guide',
description: 'Overview, key concepts by section, pitfalls and self-check questions.',
payload: { kind: 'note', noteStyle: 'study_guide' },
},
{
id: 'builtin-gen-cheat',
kind: 'generation',
name: 'Exam cheat sheet',
description: 'A dense one-page review with tables for values, drugs and comparisons.',
payload: { kind: 'note', noteStyle: 'cheat_sheet' },
},
{
id: 'builtin-deck-drug',
kind: 'deck',
name: 'Medication card layout',
description: 'A blank drug card with the standard headings, ready to fill in and duplicate.',
payload: {
title: 'Medications',
description: '',
cards: [
{
front: 'Drug name (Brand)',
back: '**Class:** \n\n**Action:** \n\n**Uses:** \n\n**Adverse effects:** \n\n**Nursing considerations:** \n\n**Client teaching:** ',
hint: '',
tags: ['pharm'],
},
],
},
},
{
id: 'builtin-deck-disease',
kind: 'deck',
name: 'Disease process layout',
description: 'One card per condition: pathophysiology, findings, diagnostics, interventions, complications.',
payload: {
title: 'Disorders',
description: '',
cards: [
{
front: 'Condition',
back: '**Pathophysiology:** \n\n**Signs and symptoms:** \n\n**Diagnostics / labs:** \n\n**Nursing interventions:** \n\n**Medications:** \n\n**Complications:** \n\n**Client teaching:** ',
hint: '',
tags: [],
},
],
},
},
{
id: 'builtin-quiz-nclex',
kind: 'quiz',
name: 'NCLEX item layout',
description: 'One multiple-choice and one select-all question with the recommended structure.',
payload: {
title: 'Practice questions',
description: '',
questions: [
{
type: 'single',
stem: 'A client with [condition] reports [finding]. Which action should the nurse take first?',
options: [
{ text: 'Correct priority action', correct: true, why: 'Why this comes first.' },
{ text: 'Plausible but lower priority action', correct: false, why: 'Why it can wait.' },
{ text: 'Appropriate action, wrong timing', correct: false, why: '' },
{ text: 'Common misconception', correct: false, why: '' },
],
rationale: 'State the principle (ABCs, safety, acute over chronic) and how it applies.',
topic: '',
difficulty: 'medium',
tags: [],
},
{
type: 'multi',
stem: 'Which findings should the nurse expect in a client with [condition]? Select all that apply.',
options: [
{ text: 'Expected finding', correct: true, why: '' },
{ text: 'Expected finding', correct: true, why: '' },
{ text: 'Opposite of the expected finding', correct: false, why: '' },
{ text: 'Expected finding', correct: true, why: '' },
{ text: 'Finding from a similar condition', correct: false, why: '' },
],
rationale: '',
topic: '',
difficulty: 'medium',
tags: [],
},
],
},
},
];
export function seedTemplates(db: DB): void {
const at = now();
db.tx(() => {
const keep = BUILTIN.map((t) => t.id);
db.run(`DELETE FROM templates WHERE builtin = 1 AND id NOT IN (${keep.map(() => '?').join(',')})`, ...keep);
for (const t of BUILTIN) {
db.run(
`INSERT INTO templates (id, kind, name, description, payload, builtin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?, ?)
ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, name = excluded.name, description = excluded.description, payload = excluded.payload, updated_at = excluded.updated_at`,
t.id,
t.kind,
t.name,
t.description,
JSON.stringify(t.payload),
at,
at,
);
}
});
}
export function listTemplates(db: DB, kind?: string) {
const rows = kind
? db.all<TemplateRow>('SELECT * FROM templates WHERE kind = ? ORDER BY builtin, name', kind)
: db.all<TemplateRow>('SELECT * FROM templates ORDER BY kind, builtin, name');
return rows.map(mapTemplate);
}
export function createTemplate(db: DB, input: z.input<typeof templateInputSchema>) {
const data = templateInputSchema.parse(input);
const id = newId();
const at = now();
db.run('INSERT INTO templates (id, kind, name, description, payload, builtin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?)', id, data.kind, data.name, data.description, JSON.stringify(data.payload), at, at);
return mapTemplate(db.get<TemplateRow>('SELECT * FROM templates WHERE id = ?', id)!);
}
export function updateTemplate(db: DB, id: string, input: { name?: string; description?: string; payload?: Record<string, unknown> }) {
const row = db.get<TemplateRow>('SELECT * FROM templates WHERE id = ? AND builtin = 0', id);
if (!row) throw notFound('Template');
db.run(
'UPDATE templates SET name = ?, description = ?, payload = ?, updated_at = ? WHERE id = ?',
input.name?.trim().slice(0, 120) || row.name,
input.description ?? row.description,
input.payload ? JSON.stringify(input.payload) : row.payload,
now(),
id,
);
return mapTemplate(db.get<TemplateRow>('SELECT * FROM templates WHERE id = ?', id)!);
}
export function deleteTemplate(db: DB, id: string): void {
const { changes } = db.run('DELETE FROM templates WHERE id = ? AND builtin = 0', id);
if (!changes) throw notFound('Template');
}