Add HTTP routes, app wiring, V1 migration, backups, templates and API tests

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:22:47 -07:00
parent 3e74ecd843
commit eae109c166
11 changed files with 2085 additions and 1 deletions

183
server/services/backup.ts Normal file
View file

@ -0,0 +1,183 @@
/**
* Backups.
* - Automatic: a compact snapshot of the database is written to data/backups once a day
* and the newest few are kept.
* - On demand: a zip with the database snapshot plus every uploaded file and image.
* - Content export: a portable JSON bundle of classes, quizzes, decks and notes.
*/
import fs from 'node:fs';
import path from 'node:path';
import { Zip, ZipPassThrough } from 'fflate';
import { questionToDraft } from '../../shared/content.ts';
import { EXPORT_FORMAT, EXPORT_VERSION, exportDeck, exportQuiz } from '../../shared/importer.ts';
import type { AppContext } from '../http.ts';
import { dayKey, now } from '../util.ts';
import { listCards, listQuestions, type ClassRow, type FolderRow, type NoteRow, type QuizRow } from './content.ts';
export interface BackupInfo {
name: string;
size: number;
createdAt: number;
}
export function listBackups(app: AppContext): BackupInfo[] {
const dir = app.config.backupsDir;
if (!fs.existsSync(dir)) return [];
return fs
.readdirSync(dir)
.filter((f) => f.endsWith('.db'))
.map((name) => {
const st = fs.statSync(path.join(dir, name));
return { name, size: st.size, createdAt: st.mtimeMs };
})
.sort((a, b) => b.createdAt - a.createdAt);
}
export function createSnapshot(app: AppContext, prefix = 'manual'): BackupInfo {
const stamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19);
const name = `${prefix}-${stamp}.db`;
const target = path.join(app.config.backupsDir, name);
app.db.snapshot(target);
return { name, size: fs.statSync(target).size, createdAt: now() };
}
/** Writes today's automatic snapshot if it does not exist yet, then prunes old automatic ones. */
export function runDailyBackup(app: AppContext): BackupInfo | null {
const today = dayKey(now(), 'UTC');
const name = `auto-${today}.db`;
const target = path.join(app.config.backupsDir, name);
let created: BackupInfo | null = null;
if (!fs.existsSync(target)) {
// Skip an empty install: there is nothing worth keeping yet.
const hasData = (app.db.get<{ n: number }>('SELECT (SELECT COUNT(*) FROM classes) + (SELECT COUNT(*) FROM ai_providers) AS n')?.n ?? 0) > 0;
if (hasData) {
app.db.snapshot(target);
created = { name, size: fs.statSync(target).size, createdAt: now() };
}
}
const prune = (prefix: string, keep: number) => {
const files = listBackups(app).filter((b) => b.name.startsWith(prefix));
for (const old of files.slice(keep)) fs.rmSync(path.join(app.config.backupsDir, old.name), { force: true });
};
prune('auto-', app.config.backupKeep);
prune('pre-migration-', 5);
prune('manual-', 10);
return created;
}
export function startBackupSchedule(app: AppContext): () => void {
const tick = () => {
try {
const made = runDailyBackup(app);
if (made) app.log('info', `Automatic backup written: ${made.name}`);
} catch (e) {
app.log('error', 'Automatic backup failed', e);
}
};
const first = setTimeout(tick, 30_000);
const timer = setInterval(tick, 6 * 3_600_000);
first.unref?.();
timer.unref?.();
return () => {
clearTimeout(first);
clearInterval(timer);
};
}
/** Streams a zip containing a fresh database snapshot and all uploaded files. One file is in memory at a time. */
export function fullBackupStream(app: AppContext): { stream: ReadableStream<Uint8Array>; filename: string } {
const tmp = path.join(app.config.backupsDir, `.export-${Date.now()}.db`);
app.db.snapshot(tmp);
const entries: { name: string; file: string }[] = [{ name: 'study.db', file: tmp }];
for (const [dir, prefix] of [
[app.config.uploadsDir, 'uploads'],
[app.config.mediaDir, 'media'],
] as const) {
if (!fs.existsSync(dir)) continue;
for (const f of fs.readdirSync(dir)) {
const full = path.join(dir, f);
if (fs.statSync(full).isFile()) entries.push({ name: `${prefix}/${f}`, file: full });
}
}
const manifest = {
format: 'studydesk-backup',
version: 1,
createdAt: new Date().toISOString(),
files: entries.length,
restore: 'Stop the container, copy study.db, uploads/ and media/ into the data folder (replacing what is there), keep your existing secret.key, then start the container.',
};
let index = -1;
let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;
const cleanup = () => fs.rmSync(tmp, { force: true });
const zip = new Zip((err, chunk, final) => {
if (err) {
controllerRef?.error(err);
cleanup();
return;
}
controllerRef?.enqueue(chunk);
if (final) {
controllerRef?.close();
cleanup();
}
});
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controllerRef = controller;
const entry = new ZipPassThrough('manifest.json');
zip.add(entry);
entry.push(new TextEncoder().encode(JSON.stringify(manifest, null, 2)), true);
},
pull() {
index += 1;
if (index >= entries.length) {
zip.end();
return;
}
const { name, file } = entries[index];
const entry = new ZipPassThrough(name);
zip.add(entry);
try {
entry.push(new Uint8Array(fs.readFileSync(file)), true);
} catch {
entry.push(new Uint8Array(0), true);
}
},
cancel() {
cleanup();
},
});
return { stream, filename: `studydesk-backup-${new Date().toISOString().slice(0, 10)}.zip` };
}
/** Portable JSON bundle: classes with their folders, quizzes, decks and notes (no progress, no uploads). */
export function exportBundle(app: AppContext, classId?: string) {
const { db } = app;
const classes = classId ? db.all<ClassRow>('SELECT * FROM classes WHERE id = ?', classId) : db.all<ClassRow>('SELECT * FROM classes ORDER BY sort_order, created_at');
return {
format: EXPORT_FORMAT,
version: EXPORT_VERSION,
kind: 'bundle' as const,
exportedAt: new Date().toISOString(),
classes: classes.map((cls) => {
const folders = db.all<FolderRow>('SELECT * FROM folders WHERE class_id = ? ORDER BY sort_order', cls.id);
const folderName = (id: string | null) => folders.find((f) => f.id === id)?.name ?? null;
return {
name: cls.name,
code: cls.code,
description: cls.description,
color: cls.color,
folders: folders.map((f) => f.name),
quizzes: db.all<QuizRow>('SELECT * FROM quizzes WHERE class_id = ? ORDER BY sort_order, created_at', cls.id).map((q) => ({
...exportQuiz({ title: q.title, description: q.description, questions: listQuestions(db, q.id).map(questionToDraft) }),
folder: folderName(q.folder_id),
})),
decks: db.all<QuizRow>('SELECT * FROM decks WHERE class_id = ? ORDER BY sort_order, created_at', cls.id).map((d) => ({
...exportDeck({ title: d.title, description: d.description, cards: listCards(db, d.id).map((c) => ({ front: c.front, back: c.back, hint: c.hint, tags: c.tags })) }),
folder: folderName(d.folder_id),
})),
notes: db.all<NoteRow>('SELECT * FROM notes WHERE class_id = ? ORDER BY sort_order, created_at', cls.id).map((n) => ({ kind: 'note' as const, title: n.title, content: n.content, folder: folderName(n.folder_id) })),
};
}),
};
}

View file

@ -0,0 +1,229 @@
/**
* 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');
}

257
server/services/v1import.ts Normal file
View file

@ -0,0 +1,257 @@
/**
* One-way migration from a Study Desk V1 database (the Prisma/SQLite `study.db`).
* The V1 file is opened read-only and never modified. Everything is copied into new
* rows with new ids inside one transaction, so a failed import leaves V2 untouched.
*/
import { DatabaseSync } from 'node:sqlite';
import { isFullyCorrect, scoreQuestion, type Option } from '../../shared/content.ts';
import { badRequest, type AppContext } from '../http.ts';
import { newId, now } from '../util.ts';
import { createClass, createDeck, createFolder, createQuiz, listCards, listQuestions } from './content.ts';
export interface V1Summary {
classes: number;
folders: number;
decks: number;
cards: number;
quizzes: number;
questions: number;
attempts: number;
scheduledCards: number;
activityDays: number;
skipped: string[];
}
type Row = Record<string, any>;
function toMs(v: unknown): number | null {
if (v === null || v === undefined) return null;
if (typeof v === 'number') return v > 1e11 ? v : v * 1000;
if (typeof v === 'bigint') return Number(v);
const n = Number(v);
if (Number.isFinite(n) && String(v).trim() !== '') return n > 1e11 ? n : n * 1000;
const t = Date.parse(String(v));
return Number.isNaN(t) ? null : t;
}
export function importV1(app: AppContext, file: string, opts: { dryRun?: boolean } = {}): V1Summary {
let src: DatabaseSync;
try {
src = new DatabaseSync(file, { readOnly: true });
} catch {
throw badRequest('That file could not be opened as a SQLite database.');
}
try {
const tables = new Set((src.prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`).all() as Row[]).map((r) => String(r.name)));
if (!tables.has('Class') || !tables.has('Deck') || !tables.has('QuizSet')) {
throw badRequest('This does not look like a Study Desk V1 database (expected the tables Class, Deck and QuizSet).');
}
const all = (table: string, order = ''): Row[] => (tables.has(table) ? (src.prepare(`SELECT * FROM "${table}" ${order}`).all() as Row[]) : []);
const classes = all('Class', 'ORDER BY sortOrder, createdAt');
const groups = all('MaterialGroup', 'ORDER BY sortOrder, createdAt');
const decks = all('Deck', 'ORDER BY sortOrder, createdAt');
const cards = all('Flashcard', 'ORDER BY sortOrder');
const quizzes = all('QuizSet', 'ORDER BY sortOrder, createdAt');
const questions = all('Question', 'ORDER BY sortOrder');
const options = all('AnswerOption', 'ORDER BY sortOrder');
const attempts = all('QuizAttempt', 'ORDER BY completedAt');
const srStates = all('SpacedRepetitionCardState');
const activity = all('StudyActivity');
const summary: V1Summary = {
classes: classes.length,
folders: groups.length,
decks: decks.length,
cards: cards.length,
quizzes: quizzes.length,
questions: questions.length,
attempts: attempts.length,
scheduledCards: new Set(srStates.map((s) => s.flashcardId)).size,
activityDays: new Set(activity.map((a) => new Date(toMs(a.occurredAt) ?? 0).toISOString().slice(0, 10))).size,
skipped: [],
};
if (opts.dryRun) return summary;
const { db } = app;
const group = <T extends Row>(rows: T[], key: string) => {
const m = new Map<string, T[]>();
for (const r of rows) {
const k = String(r[key]);
if (!m.has(k)) m.set(k, []);
m.get(k)!.push(r);
}
return m;
};
const cardsByDeck = group(cards, 'deckId');
const questionsByQuiz = group(questions, 'quizSetId');
const optionsByQuestion = group(options, 'questionId');
const attemptsByQuiz = group(attempts, 'quizSetId');
// Keep the most-practised schedule when a card belonged to several V1 spaced-repetition sets.
const bestState = new Map<string, Row>();
for (const s of srStates) {
const cur = bestState.get(s.flashcardId);
if (!cur || Number(s.reps) > Number(cur.reps)) bestState.set(s.flashcardId, s);
}
db.tx(() => {
const classMap = new Map<string, string>();
const folderMap = new Map<string, string>();
for (const c of classes) {
const created = createClass(db, { name: String(c.name || 'Untitled class').slice(0, 120) });
classMap.set(c.id, created.id);
const t = toMs(c.createdAt);
if (t) db.run('UPDATE classes SET created_at = ? WHERE id = ?', t, created.id);
}
for (const g of groups) {
const classId = classMap.get(g.classId);
if (!classId) continue;
folderMap.set(g.id, createFolder(db, classId, String(g.name || 'Folder')).id);
}
for (const d of decks) {
const classId = classMap.get(d.classId);
if (!classId) {
summary.skipped.push(`Deck "${d.name}" (its class is missing)`);
continue;
}
const source = (cardsByDeck.get(d.id) ?? []).filter((c) => String(c.front ?? '').trim() && String(c.back ?? '').trim());
const deck = createDeck(db, {
classId,
folderId: d.groupId ? folderMap.get(d.groupId) : null,
title: String(d.name || 'Untitled deck').slice(0, 200),
description: String(d.description ?? '').slice(0, 4000),
cards: source.map((c) => ({ front: String(c.front).slice(0, 20000), back: String(c.back).slice(0, 20000) })),
});
const created = listCards(db, deck.id);
source.forEach((old, i) => {
const s = bestState.get(old.id);
const target = created[i];
if (!s || !target) return;
db.run(
`UPDATE cards SET state = ?, due = ?, stability = ?, difficulty = ?, scheduled_days = ?, learning_steps = ?, reps = ?, lapses = ?, last_review = ?, introduced_at = ? WHERE id = ?`,
Number(s.state) || 0,
toMs(s.due),
Number(s.stability) || 0,
Number(s.difficulty) || 0,
Number(s.scheduledDays) || 0,
Number(s.learningSteps) || 0,
Number(s.reps) || 0,
Number(s.lapses) || 0,
toMs(s.lastReview),
toMs(s.firstReviewedAt),
target.id,
);
});
}
for (const z of quizzes) {
const classId = classMap.get(z.classId);
if (!classId) {
summary.skipped.push(`Quiz "${z.name}" (its class is missing)`);
continue;
}
const source = (questionsByQuiz.get(z.id) ?? []).filter((q) => {
const opts2 = optionsByQuestion.get(q.id) ?? [];
return String(q.prompt ?? '').trim() && opts2.length >= 2 && opts2.some((o) => o.isCorrect);
});
const quiz = createQuiz(db, {
classId,
folderId: z.groupId ? folderMap.get(z.groupId) : null,
title: String(z.name || 'Untitled quiz').slice(0, 200),
description: String(z.description ?? '').slice(0, 4000),
questions: source.map((q) => {
const opts2 = (optionsByQuestion.get(q.id) ?? []).filter((o) => String(o.text ?? '').trim()).slice(0, 10);
const correct = opts2.filter((o) => o.isCorrect).length;
return {
type: String(q.type).toUpperCase() === 'SATA' || correct > 1 ? 'multi' : 'single',
stem: String(q.prompt).slice(0, 20000),
options: opts2.map((o) => ({ text: String(o.text).slice(0, 4000), correct: Boolean(o.isCorrect) })),
rationale: String(q.rationale ?? '').slice(0, 20000),
topic: String(q.category ?? '').slice(0, 80),
};
}),
});
const created = listQuestions(db, quiz.id);
// Old question / option ids -> new, so past attempts can be replayed.
const qMap = new Map<string, (typeof created)[number]>();
const oMap = new Map<string, string>();
source.forEach((old, i) => {
const target = created[i];
if (!target) return;
qMap.set(old.id, target);
const oldOpts = (optionsByQuestion.get(old.id) ?? []).filter((o) => String(o.text ?? '').trim()).slice(0, 10);
oldOpts.forEach((o, j) => target.options[j] && oMap.set(o.id, target.options[j].id));
});
for (const a of attemptsByQuiz.get(z.id) ?? []) {
let answers: Record<string, unknown> = {};
try {
const parsed = JSON.parse(String(a.answersJson ?? '{}'));
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) answers = parsed;
} catch {
/* an unreadable attempt is still imported as a score */
}
const partial = Boolean(a.isPartialRetake);
const included = created.filter((q) => {
const oldId = [...qMap.entries()].find(([, v]) => v.id === q.id)?.[0];
return !partial || (oldId !== undefined && oldId in answers);
});
const completedAt = toMs(a.completedAt) ?? now();
const newAnswers: Record<string, { selected: string[]; checked: boolean; at: number }> = {};
for (const [oldQ, sel] of Object.entries(answers)) {
const target = qMap.get(oldQ);
if (!target || !Array.isArray(sel)) continue;
newAnswers[target.id] = { selected: sel.map((s) => oMap.get(String(s))).filter((s): s is string => Boolean(s)), checked: true, at: completedAt };
}
const attemptId = newId();
const snapshot = included.map((q) => ({ id: q.id, quizId: quiz.id, quizTitle: quiz.title, type: q.type, stem: q.stem, options: q.options as Option[], rationale: q.rationale, topic: q.topic, difficulty: q.difficulty }));
db.run(
`INSERT INTO attempts (id, quiz_id, class_id, title, mode, kind, status, settings, snapshot, answers, question_count, score, max_score, started_at, updated_at, completed_at)
VALUES (?, ?, ?, ?, 'practice', ?, 'completed', ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
attemptId,
quiz.id,
classId,
quiz.title,
partial ? 'retake' : 'full',
JSON.stringify({ shuffleQuestions: false, shuffleOptions: false, timeLimitSec: null, sataScoring: 'partial' }),
JSON.stringify({ questions: snapshot }),
JSON.stringify(newAnswers),
snapshot.length,
Number(a.score) || 0,
Number(a.maxScore) || snapshot.length,
completedAt,
completedAt,
completedAt,
);
for (const q of snapshot) {
const selected = newAnswers[q.id]?.selected ?? [];
if (selected.length === 0 && partial) continue;
const score = scoreQuestion(q, selected, 'partial');
db.run(
'INSERT OR IGNORE INTO responses (attempt_id, question_id, quiz_id, class_id, topic, score, correct, answered_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
attemptId,
q.id,
quiz.id,
classId,
q.topic,
score,
isFullyCorrect(score) ? 1 : 0,
completedAt,
);
}
}
}
// Flashcard activity keeps the study heatmap and streak intact. Quiz activity is rebuilt from the attempts above.
for (const a of activity) {
if (String(a.type) !== 'FLASHCARD') continue;
const t = toMs(a.occurredAt);
if (t) db.run(`INSERT INTO reviews (card_id, deck_id, class_id, rating, state_before, scheduled_days, mode, prev, reviewed_at) VALUES ('v1', NULL, NULL, 3, 0, 0, 'legacy', '', ?)`, t);
}
});
return summary;
} finally {
src.close();
}
}