950 lines
30 KiB
TypeScript
950 lines
30 KiB
TypeScript
import '../utils/time';
|
||
import { toIstanbulIsoString } from '../utils/time';
|
||
import fs from 'fs';
|
||
import path from 'path';
|
||
import crypto from 'crypto';
|
||
import Database from 'better-sqlite3';
|
||
import {
|
||
DatabaseSchema,
|
||
StudentStore,
|
||
Assignment,
|
||
PrivateLesson,
|
||
PrivateLessonFormMeta,
|
||
PrivateLessonsStore,
|
||
ExamReportDetail,
|
||
ExamStore,
|
||
ExamTopicWeakness,
|
||
ExamQuestionItem,
|
||
SyllabusStore
|
||
} from '../types';
|
||
import {
|
||
encryptCredential,
|
||
decryptCredential
|
||
} from './secrets';
|
||
|
||
const DEFAULT_DB_FILE = path.resolve(process.cwd(), 'data', 'bekultur.db');
|
||
const DEFAULT_LEGACY_JSON_FILE = path.resolve(process.cwd(), 'data', 'db.json');
|
||
|
||
const SYNTHETIC_TEST_ID_REGEX = /^(test_student_|audit_)/i;
|
||
|
||
interface StudentRow {
|
||
student_id: string;
|
||
last_synced: string | null;
|
||
last_login_at: string | null;
|
||
remembered_password: string | null;
|
||
advisory_teacher: string | null;
|
||
syllabus_json: string | null;
|
||
private_lessons_json: string | null;
|
||
exams_json: string | null;
|
||
}
|
||
|
||
interface AssignmentRow {
|
||
student_id: string;
|
||
id: string;
|
||
subject: string;
|
||
type: string;
|
||
unit: string;
|
||
topic: string;
|
||
start_date: string;
|
||
end_date: string;
|
||
parsed_start_date: string | null;
|
||
parsed_end_date: string | null;
|
||
description: string;
|
||
detected_check_date: string | null;
|
||
status: string;
|
||
completed: number;
|
||
completed_at: string | null;
|
||
excluded: number;
|
||
page: number | null;
|
||
}
|
||
|
||
export class LocalDatabase {
|
||
private static instance: LocalDatabase | null = null;
|
||
private sqlite: Database.Database;
|
||
private dbPath: string;
|
||
private legacyJsonPath: string;
|
||
private skipTestFilter: boolean;
|
||
|
||
public constructor(
|
||
customDbPath?: string,
|
||
customLegacyJsonPath?: string,
|
||
options?: { skipTestFilter?: boolean }
|
||
) {
|
||
this.dbPath = customDbPath || process.env.DB_PATH || DEFAULT_DB_FILE;
|
||
const effectiveCustomDb = customDbPath || process.env.DB_PATH;
|
||
this.legacyJsonPath =
|
||
customLegacyJsonPath ||
|
||
process.env.LEGACY_JSON_DB_PATH ||
|
||
process.env.LEGACY_JSON_PATH ||
|
||
(effectiveCustomDb ? path.join(path.dirname(effectiveCustomDb), 'db.json') : DEFAULT_LEGACY_JSON_FILE);
|
||
this.skipTestFilter = options?.skipTestFilter ?? false;
|
||
|
||
const dir = path.dirname(this.dbPath);
|
||
if (!fs.existsSync(dir)) {
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
}
|
||
|
||
this.sqlite = new Database(this.dbPath);
|
||
this.initSchema();
|
||
this.migrateFromLegacyJson();
|
||
}
|
||
|
||
public static getInstance(): LocalDatabase {
|
||
if (!LocalDatabase.instance) {
|
||
LocalDatabase.instance = new LocalDatabase();
|
||
}
|
||
return LocalDatabase.instance;
|
||
}
|
||
|
||
public static resetInstance(): void {
|
||
if (LocalDatabase.instance) {
|
||
LocalDatabase.instance.close();
|
||
LocalDatabase.instance = null;
|
||
}
|
||
}
|
||
|
||
public getSqliteDb(): Database.Database {
|
||
return this.sqlite;
|
||
}
|
||
|
||
public getDbPath(): string {
|
||
return this.dbPath;
|
||
}
|
||
|
||
private initSchema(): void {
|
||
this.sqlite.pragma('journal_mode = WAL');
|
||
this.sqlite.pragma('synchronous = FULL');
|
||
this.sqlite.pragma('foreign_keys = ON');
|
||
this.sqlite.pragma('busy_timeout = 5000');
|
||
|
||
this.sqlite.exec(`
|
||
CREATE TABLE IF NOT EXISTS meta (
|
||
key TEXT PRIMARY KEY,
|
||
value TEXT NOT NULL
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS students (
|
||
student_id TEXT PRIMARY KEY,
|
||
last_synced TEXT,
|
||
last_login_at TEXT,
|
||
remembered_password TEXT,
|
||
advisory_teacher TEXT,
|
||
syllabus_json TEXT,
|
||
private_lessons_json TEXT,
|
||
exams_json TEXT,
|
||
updated_at TEXT NOT NULL
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS assignments (
|
||
student_id TEXT NOT NULL,
|
||
id TEXT NOT NULL,
|
||
subject TEXT NOT NULL,
|
||
type TEXT NOT NULL,
|
||
unit TEXT NOT NULL DEFAULT '',
|
||
topic TEXT NOT NULL DEFAULT '',
|
||
start_date TEXT NOT NULL DEFAULT '',
|
||
end_date TEXT NOT NULL DEFAULT '',
|
||
parsed_start_date TEXT,
|
||
parsed_end_date TEXT,
|
||
description TEXT NOT NULL DEFAULT '',
|
||
detected_check_date TEXT,
|
||
status TEXT NOT NULL DEFAULT 'active',
|
||
completed INTEGER NOT NULL DEFAULT 0,
|
||
completed_at TEXT,
|
||
excluded INTEGER NOT NULL DEFAULT 0,
|
||
page INTEGER,
|
||
PRIMARY KEY (student_id, id),
|
||
FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE CASCADE
|
||
);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_assignments_student ON assignments(student_id);
|
||
|
||
CREATE TABLE IF NOT EXISTS sessions (
|
||
sid TEXT PRIMARY KEY,
|
||
sess TEXT NOT NULL,
|
||
expire INTEGER NOT NULL
|
||
);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire);
|
||
`);
|
||
|
||
// Ensure last_login_at column exists on pre-existing databases without data loss
|
||
const studentCols = this.sqlite.pragma('table_info(students)') as Array<{ name: string }>;
|
||
if (!studentCols.some(col => col.name === 'last_login_at')) {
|
||
this.sqlite.exec('ALTER TABLE students ADD COLUMN last_login_at TEXT');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Automatically migrate data from legacy data/db.json into SQLite without losing any student data.
|
||
* Preserves a backup at data/db.json.bak and leaves data/db.json intact.
|
||
* Uses a SHA-256 content hash so that if db.json is ever restored or updated later,
|
||
* any missing records are additively merged without overwriting newer SQLite state.
|
||
*/
|
||
public migrateFromLegacyJson(): { migratedCount: number; skippedTestCount: number } {
|
||
const result = { migratedCount: 0, skippedTestCount: 0 };
|
||
|
||
if (!fs.existsSync(this.legacyJsonPath)) {
|
||
return result;
|
||
}
|
||
|
||
try {
|
||
const raw = fs.readFileSync(this.legacyJsonPath, 'utf-8');
|
||
const fileHash = crypto.createHash('sha256').update(raw).digest('hex');
|
||
|
||
const migratedHashRow = this.sqlite
|
||
.prepare('SELECT value FROM meta WHERE key = ?')
|
||
.get('json_migrated_sha256') as { value: string } | undefined;
|
||
|
||
if (migratedHashRow && migratedHashRow.value === fileHash) {
|
||
return result;
|
||
}
|
||
|
||
const parsed = JSON.parse(raw) as DatabaseSchema;
|
||
const studentsMap = parsed?.students || {};
|
||
|
||
// Backup original db.json before any changes
|
||
const backupPath = `${this.legacyJsonPath}.bak`;
|
||
if (!fs.existsSync(backupPath)) {
|
||
fs.copyFileSync(this.legacyJsonPath, backupPath);
|
||
}
|
||
|
||
const upsertStudentStmt = this.sqlite.prepare(`
|
||
INSERT INTO students (
|
||
student_id,
|
||
last_synced,
|
||
remembered_password,
|
||
advisory_teacher,
|
||
syllabus_json,
|
||
private_lessons_json,
|
||
exams_json,
|
||
updated_at
|
||
) VALUES (
|
||
@student_id,
|
||
@last_synced,
|
||
@remembered_password,
|
||
@advisory_teacher,
|
||
@syllabus_json,
|
||
@private_lessons_json,
|
||
@exams_json,
|
||
@updated_at
|
||
)
|
||
ON CONFLICT(student_id) DO UPDATE SET
|
||
last_synced = COALESCE(students.last_synced, excluded.last_synced),
|
||
remembered_password = COALESCE(students.remembered_password, excluded.remembered_password),
|
||
advisory_teacher = COALESCE(students.advisory_teacher, excluded.advisory_teacher),
|
||
syllabus_json = COALESCE(students.syllabus_json, excluded.syllabus_json),
|
||
private_lessons_json = COALESCE(students.private_lessons_json, excluded.private_lessons_json),
|
||
exams_json = COALESCE(students.exams_json, excluded.exams_json),
|
||
updated_at = excluded.updated_at
|
||
`);
|
||
|
||
const upsertAssignmentStmt = this.sqlite.prepare(`
|
||
INSERT INTO assignments (
|
||
student_id,
|
||
id,
|
||
subject,
|
||
type,
|
||
unit,
|
||
topic,
|
||
start_date,
|
||
end_date,
|
||
parsed_start_date,
|
||
parsed_end_date,
|
||
description,
|
||
detected_check_date,
|
||
status,
|
||
completed,
|
||
completed_at,
|
||
excluded,
|
||
page
|
||
) VALUES (
|
||
@student_id,
|
||
@id,
|
||
@subject,
|
||
@type,
|
||
@unit,
|
||
@topic,
|
||
@start_date,
|
||
@end_date,
|
||
@parsed_start_date,
|
||
@parsed_end_date,
|
||
@description,
|
||
@detected_check_date,
|
||
@status,
|
||
@completed,
|
||
@completed_at,
|
||
@excluded,
|
||
@page
|
||
)
|
||
ON CONFLICT(student_id, id) DO UPDATE SET
|
||
subject = COALESCE(NULLIF(assignments.subject, ''), excluded.subject),
|
||
type = COALESCE(NULLIF(assignments.type, ''), excluded.type),
|
||
unit = COALESCE(NULLIF(assignments.unit, ''), excluded.unit),
|
||
topic = COALESCE(NULLIF(assignments.topic, ''), excluded.topic),
|
||
start_date = COALESCE(NULLIF(assignments.start_date, ''), excluded.start_date),
|
||
end_date = COALESCE(NULLIF(assignments.end_date, ''), excluded.end_date),
|
||
parsed_start_date = COALESCE(assignments.parsed_start_date, excluded.parsed_start_date),
|
||
parsed_end_date = COALESCE(assignments.parsed_end_date, excluded.parsed_end_date),
|
||
description = COALESCE(NULLIF(assignments.description, ''), excluded.description),
|
||
detected_check_date = COALESCE(assignments.detected_check_date, excluded.detected_check_date),
|
||
status = CASE WHEN assignments.completed = 1 OR excluded.completed = 1 THEN 'completed' ELSE assignments.status END,
|
||
completed = CASE WHEN assignments.completed = 1 OR excluded.completed = 1 THEN 1 ELSE 0 END,
|
||
completed_at = COALESCE(assignments.completed_at, excluded.completed_at),
|
||
excluded = CASE WHEN assignments.excluded = 1 OR excluded.excluded = 1 THEN 1 ELSE 0 END,
|
||
page = COALESCE(assignments.page, excluded.page)
|
||
`);
|
||
|
||
const setMetaStmt = this.sqlite.prepare(`
|
||
INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)
|
||
`);
|
||
|
||
const nowIso = toIstanbulIsoString();
|
||
|
||
const runMigration = this.sqlite.transaction(() => {
|
||
for (const [studentId, store] of Object.entries(studentsMap)) {
|
||
if (!studentId || !store) continue;
|
||
|
||
if (!this.skipTestFilter && SYNTHETIC_TEST_ID_REGEX.test(studentId)) {
|
||
result.skippedTestCount++;
|
||
continue;
|
||
}
|
||
|
||
let encryptedPassword: string | null = null;
|
||
if (store.rememberedCredentials?.password) {
|
||
const plain = decryptCredential(store.rememberedCredentials.password);
|
||
if (plain) {
|
||
encryptedPassword = encryptCredential(plain);
|
||
}
|
||
}
|
||
|
||
upsertStudentStmt.run({
|
||
student_id: studentId,
|
||
last_synced: store.lastSynced || null,
|
||
remembered_password: encryptedPassword,
|
||
advisory_teacher: store.advisoryTeacher || store.privateLessons?.detectedAdvisor || null,
|
||
syllabus_json: store.syllabus ? JSON.stringify(store.syllabus) : null,
|
||
private_lessons_json: store.privateLessons ? JSON.stringify(store.privateLessons) : null,
|
||
exams_json: store.exams ? JSON.stringify(store.exams) : null,
|
||
updated_at: nowIso
|
||
});
|
||
|
||
const assignments = store.assignments ? Object.values(store.assignments) : [];
|
||
for (const a of assignments) {
|
||
if (!a || !a.id) continue;
|
||
upsertAssignmentStmt.run({
|
||
student_id: studentId,
|
||
id: a.id,
|
||
subject: a.subject || 'Genel',
|
||
type: a.type || 'Ödev',
|
||
unit: a.unit || '',
|
||
topic: a.topic || '',
|
||
start_date: a.startDate || '',
|
||
end_date: a.endDate || '',
|
||
parsed_start_date: a.parsedStartDate || null,
|
||
parsed_end_date: a.parsedEndDate || null,
|
||
description: a.description || '',
|
||
detected_check_date: a.detectedCheckDate || null,
|
||
status: a.status || 'active',
|
||
completed: a.completed ? 1 : 0,
|
||
completed_at: a.completedAt || null,
|
||
excluded: a.excluded ? 1 : 0,
|
||
page: a.page ?? null
|
||
});
|
||
}
|
||
|
||
result.migratedCount++;
|
||
}
|
||
|
||
setMetaStmt.run('json_migrated_at', nowIso);
|
||
setMetaStmt.run('json_migrated_sha256', fileHash);
|
||
setMetaStmt.run('schema_version', '2');
|
||
});
|
||
|
||
runMigration();
|
||
} catch (err) {
|
||
console.error('Error migrating legacy db.json to SQLite:', err);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
private ensureStudentRow(studentId: string): StudentRow {
|
||
const existing = this.sqlite
|
||
.prepare('SELECT * FROM students WHERE student_id = ?')
|
||
.get(studentId) as StudentRow | undefined;
|
||
|
||
if (existing) {
|
||
return existing;
|
||
}
|
||
|
||
const now = toIstanbulIsoString();
|
||
this.sqlite
|
||
.prepare(`
|
||
INSERT INTO students (
|
||
student_id,
|
||
last_synced,
|
||
last_login_at,
|
||
remembered_password,
|
||
advisory_teacher,
|
||
syllabus_json,
|
||
private_lessons_json,
|
||
exams_json,
|
||
updated_at
|
||
) VALUES (?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?)
|
||
`)
|
||
.run(studentId, now);
|
||
|
||
return {
|
||
student_id: studentId,
|
||
last_synced: null,
|
||
last_login_at: null,
|
||
remembered_password: null,
|
||
advisory_teacher: null,
|
||
syllabus_json: null,
|
||
private_lessons_json: null,
|
||
exams_json: null
|
||
};
|
||
}
|
||
|
||
public getLastLogin(studentId: string): string | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT last_login_at, last_synced FROM students WHERE student_id = ?')
|
||
.get(studentId) as { last_login_at: string | null; last_synced: string | null } | undefined;
|
||
if (!row) return null;
|
||
return row.last_login_at || row.last_synced || null;
|
||
}
|
||
|
||
public updateLastLogin(studentId: string, loginAt: string = toIstanbulIsoString()): void {
|
||
this.ensureStudentRow(studentId);
|
||
this.sqlite
|
||
.prepare('UPDATE students SET last_login_at = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(loginAt, loginAt, studentId);
|
||
}
|
||
|
||
private mapAssignmentRow(row: AssignmentRow): Assignment {
|
||
return {
|
||
id: row.id,
|
||
subject: row.subject,
|
||
type: row.type,
|
||
unit: row.unit,
|
||
topic: row.topic,
|
||
startDate: row.start_date,
|
||
endDate: row.end_date,
|
||
parsedStartDate: row.parsed_start_date,
|
||
parsedEndDate: row.parsed_end_date,
|
||
description: row.description,
|
||
detectedCheckDate: row.detected_check_date,
|
||
status: row.status as Assignment['status'],
|
||
completed: row.completed === 1,
|
||
completedAt: row.completed_at,
|
||
excluded: row.excluded === 1,
|
||
page: row.page ?? undefined
|
||
};
|
||
}
|
||
|
||
public getStudentStore(studentId: string): StudentStore {
|
||
const row = this.ensureStudentRow(studentId);
|
||
const assignmentRows = this.sqlite
|
||
.prepare('SELECT * FROM assignments WHERE student_id = ?')
|
||
.all(studentId) as AssignmentRow[];
|
||
|
||
const assignments: Record<string, Assignment> = {};
|
||
for (const r of assignmentRows) {
|
||
assignments[r.id] = this.mapAssignmentRow(r);
|
||
}
|
||
|
||
const store: StudentStore = {
|
||
studentId: row.student_id,
|
||
lastSynced: row.last_synced,
|
||
assignments
|
||
};
|
||
|
||
if (row.remembered_password) {
|
||
store.rememberedCredentials = {
|
||
studentId: row.student_id,
|
||
password: row.remembered_password
|
||
};
|
||
}
|
||
|
||
if (row.advisory_teacher) {
|
||
store.advisoryTeacher = row.advisory_teacher;
|
||
}
|
||
|
||
if (row.syllabus_json) {
|
||
try {
|
||
store.syllabus = JSON.parse(row.syllabus_json) as SyllabusStore;
|
||
} catch {
|
||
// Ignore malformed JSON
|
||
}
|
||
}
|
||
|
||
if (row.private_lessons_json) {
|
||
try {
|
||
store.privateLessons = JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
|
||
} catch {
|
||
// Ignore malformed JSON
|
||
}
|
||
}
|
||
|
||
if (row.exams_json) {
|
||
try {
|
||
store.exams = JSON.parse(row.exams_json) as ExamStore;
|
||
} catch {
|
||
// Ignore malformed JSON
|
||
}
|
||
}
|
||
|
||
return store;
|
||
}
|
||
|
||
public mergeAssignments(studentId: string, newAssignments: Assignment[], syncedAt?: string): StudentStore {
|
||
this.ensureStudentRow(studentId);
|
||
const now = syncedAt || toIstanbulIsoString();
|
||
|
||
const updateStudentSync = this.sqlite.prepare(
|
||
'UPDATE students SET last_synced = ?, updated_at = ? WHERE student_id = ?'
|
||
);
|
||
|
||
const upsertStmt = this.sqlite.prepare(`
|
||
INSERT INTO assignments (
|
||
student_id,
|
||
id,
|
||
subject,
|
||
type,
|
||
unit,
|
||
topic,
|
||
start_date,
|
||
end_date,
|
||
parsed_start_date,
|
||
parsed_end_date,
|
||
description,
|
||
detected_check_date,
|
||
status,
|
||
completed,
|
||
completed_at,
|
||
excluded,
|
||
page
|
||
) VALUES (
|
||
@student_id,
|
||
@id,
|
||
@subject,
|
||
@type,
|
||
@unit,
|
||
@topic,
|
||
@start_date,
|
||
@end_date,
|
||
@parsed_start_date,
|
||
@parsed_end_date,
|
||
@description,
|
||
@detected_check_date,
|
||
@status,
|
||
@completed,
|
||
@completed_at,
|
||
@excluded,
|
||
@page
|
||
)
|
||
ON CONFLICT(student_id, id) DO UPDATE SET
|
||
subject = excluded.subject,
|
||
type = excluded.type,
|
||
unit = excluded.unit,
|
||
topic = excluded.topic,
|
||
start_date = excluded.start_date,
|
||
end_date = excluded.end_date,
|
||
parsed_start_date = excluded.parsed_start_date,
|
||
parsed_end_date = excluded.parsed_end_date,
|
||
description = excluded.description,
|
||
detected_check_date = excluded.detected_check_date,
|
||
status = CASE WHEN assignments.completed = 1 THEN 'completed' ELSE excluded.status END,
|
||
completed = CASE WHEN assignments.completed = 1 THEN 1 ELSE excluded.completed END,
|
||
completed_at = COALESCE(assignments.completed_at, excluded.completed_at),
|
||
excluded = CASE WHEN assignments.excluded = 1 THEN 1 ELSE excluded.excluded END,
|
||
page = excluded.page
|
||
`);
|
||
|
||
const tx = this.sqlite.transaction(() => {
|
||
updateStudentSync.run(now, now, studentId);
|
||
|
||
for (const item of newAssignments) {
|
||
const isCompleted = Boolean(item.completed);
|
||
upsertStmt.run({
|
||
student_id: studentId,
|
||
id: item.id,
|
||
subject: item.subject,
|
||
type: item.type,
|
||
unit: item.unit || '',
|
||
topic: item.topic || '',
|
||
start_date: item.startDate || '',
|
||
end_date: item.endDate || '',
|
||
parsed_start_date: item.parsedStartDate || null,
|
||
parsed_end_date: item.parsedEndDate || null,
|
||
description: item.description || '',
|
||
detected_check_date: item.detectedCheckDate || null,
|
||
status: isCompleted ? 'completed' : item.status,
|
||
completed: isCompleted ? 1 : 0,
|
||
completed_at: item.completedAt || null,
|
||
excluded: item.excluded ? 1 : 0,
|
||
page: item.page ?? null
|
||
});
|
||
}
|
||
});
|
||
|
||
tx();
|
||
return this.getStudentStore(studentId);
|
||
}
|
||
|
||
public toggleExcludeAssignment(
|
||
studentId: string,
|
||
assignmentId: string,
|
||
excluded?: boolean
|
||
): Assignment | null {
|
||
this.ensureStudentRow(studentId);
|
||
const existing = this.sqlite
|
||
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
|
||
.get(studentId, assignmentId) as AssignmentRow | undefined;
|
||
|
||
if (!existing) {
|
||
return null;
|
||
}
|
||
|
||
const newExcluded = excluded !== undefined ? excluded : existing.excluded !== 1;
|
||
this.sqlite
|
||
.prepare('UPDATE assignments SET excluded = ? WHERE student_id = ? AND id = ?')
|
||
.run(newExcluded ? 1 : 0, studentId, assignmentId);
|
||
|
||
const updated = this.sqlite
|
||
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
|
||
.get(studentId, assignmentId) as AssignmentRow;
|
||
|
||
return this.mapAssignmentRow(updated);
|
||
}
|
||
|
||
public toggleAssignment(
|
||
studentId: string,
|
||
assignmentId: string,
|
||
completed?: boolean
|
||
): Assignment | null {
|
||
this.ensureStudentRow(studentId);
|
||
const existing = this.sqlite
|
||
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
|
||
.get(studentId, assignmentId) as AssignmentRow | undefined;
|
||
|
||
if (!existing) {
|
||
return null;
|
||
}
|
||
|
||
const newCompleted = completed !== undefined ? completed : existing.completed !== 1;
|
||
const completedAt = newCompleted ? toIstanbulIsoString() : null;
|
||
const newStatus = newCompleted ? 'completed' : existing.status;
|
||
|
||
this.sqlite
|
||
.prepare(
|
||
'UPDATE assignments SET completed = ?, completed_at = ?, status = ? WHERE student_id = ? AND id = ?'
|
||
)
|
||
.run(newCompleted ? 1 : 0, completedAt, newStatus, studentId, assignmentId);
|
||
|
||
const updated = this.sqlite
|
||
.prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
|
||
.get(studentId, assignmentId) as AssignmentRow;
|
||
|
||
return this.mapAssignmentRow(updated);
|
||
}
|
||
|
||
public saveCredentials(studentId: string, password: string): void {
|
||
this.ensureStudentRow(studentId);
|
||
const encryptedPassword = encryptCredential(password);
|
||
this.sqlite
|
||
.prepare('UPDATE students SET remembered_password = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(encryptedPassword, toIstanbulIsoString(), studentId);
|
||
}
|
||
|
||
public clearCredentials(studentId: string): void {
|
||
this.ensureStudentRow(studentId);
|
||
this.sqlite
|
||
.prepare('UPDATE students SET remembered_password = NULL, updated_at = ? WHERE student_id = ?')
|
||
.run(toIstanbulIsoString(), studentId);
|
||
}
|
||
|
||
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
|
||
.get(studentId) as { remembered_password: string | null } | undefined;
|
||
|
||
if (!row?.remembered_password) return null;
|
||
const decrypted = decryptCredential(row.remembered_password);
|
||
if (!decrypted) return null;
|
||
return {
|
||
studentId,
|
||
password: decrypted
|
||
};
|
||
}
|
||
|
||
public getRawEncryptedPassword(studentId: string): string | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
|
||
.get(studentId) as { remembered_password: string | null } | undefined;
|
||
return row?.remembered_password || null;
|
||
}
|
||
|
||
public saveSyllabus(
|
||
studentId: string,
|
||
weekId: string,
|
||
weekRange: string,
|
||
schedule: Record<number, any>,
|
||
syncedAt?: string
|
||
): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
const existingSyllabus = row.syllabus_json ? (JSON.parse(row.syllabus_json) as SyllabusStore) : null;
|
||
const existingStation = existingSyllabus?.selectedStation || null;
|
||
const now = syncedAt || toIstanbulIsoString();
|
||
|
||
const syllabus: SyllabusStore = {
|
||
weekId,
|
||
weekRange,
|
||
selectedStation: existingStation,
|
||
advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null,
|
||
lastSynced: now,
|
||
schedule
|
||
};
|
||
|
||
this.sqlite
|
||
.prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(JSON.stringify(syllabus), now, studentId);
|
||
}
|
||
|
||
public setStudentStation(studentId: string, station: string | null): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
let syllabus: SyllabusStore;
|
||
if (row.syllabus_json) {
|
||
syllabus = JSON.parse(row.syllabus_json) as SyllabusStore;
|
||
syllabus.selectedStation = station;
|
||
} else {
|
||
syllabus = {
|
||
weekId: '',
|
||
weekRange: '',
|
||
selectedStation: station,
|
||
lastSynced: null,
|
||
schedule: {}
|
||
};
|
||
}
|
||
|
||
this.sqlite
|
||
.prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(JSON.stringify(syllabus), toIstanbulIsoString(), studentId);
|
||
}
|
||
|
||
public getSyllabus(studentId: string): SyllabusStore | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT syllabus_json FROM students WHERE student_id = ?')
|
||
.get(studentId) as { syllabus_json: string | null } | undefined;
|
||
|
||
if (!row?.syllabus_json) return null;
|
||
try {
|
||
return JSON.parse(row.syllabus_json) as SyllabusStore;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public savePrivateLessons(
|
||
studentId: string,
|
||
lessons: PrivateLesson[],
|
||
formMeta?: PrivateLessonFormMeta,
|
||
detectedAdvisor?: string
|
||
): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
const existing = row.private_lessons_json
|
||
? (JSON.parse(row.private_lessons_json) as PrivateLessonsStore)
|
||
: null;
|
||
|
||
const privateLessons: PrivateLessonsStore = {
|
||
lastSynced: toIstanbulIsoString(),
|
||
lessons,
|
||
formMeta: formMeta || existing?.formMeta,
|
||
detectedAdvisor: detectedAdvisor || existing?.detectedAdvisor
|
||
};
|
||
|
||
let newAdvisor = row.advisory_teacher;
|
||
let updatedSyllabusJson = row.syllabus_json;
|
||
|
||
if (detectedAdvisor && !newAdvisor) {
|
||
newAdvisor = detectedAdvisor;
|
||
if (updatedSyllabusJson) {
|
||
try {
|
||
const syl = JSON.parse(updatedSyllabusJson) as SyllabusStore;
|
||
syl.advisoryTeacher = detectedAdvisor;
|
||
updatedSyllabusJson = JSON.stringify(syl);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
}
|
||
|
||
this.sqlite
|
||
.prepare(
|
||
'UPDATE students SET private_lessons_json = ?, advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?'
|
||
)
|
||
.run(
|
||
JSON.stringify(privateLessons),
|
||
newAdvisor,
|
||
updatedSyllabusJson,
|
||
toIstanbulIsoString(),
|
||
studentId
|
||
);
|
||
}
|
||
|
||
public getPrivateLessons(studentId: string): PrivateLessonsStore | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT private_lessons_json FROM students WHERE student_id = ?')
|
||
.get(studentId) as { private_lessons_json: string | null } | undefined;
|
||
|
||
if (!row?.private_lessons_json) return null;
|
||
try {
|
||
return JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public setStudentAdvisoryTeacher(studentId: string, teacher: string | null): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
let updatedSyllabusJson = row.syllabus_json;
|
||
if (updatedSyllabusJson) {
|
||
try {
|
||
const syl = JSON.parse(updatedSyllabusJson) as SyllabusStore;
|
||
syl.advisoryTeacher = teacher;
|
||
updatedSyllabusJson = JSON.stringify(syl);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
this.sqlite
|
||
.prepare('UPDATE students SET advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(teacher, updatedSyllabusJson, toIstanbulIsoString(), studentId);
|
||
}
|
||
|
||
public getStudentAdvisoryTeacher(studentId: string): string | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT advisory_teacher, private_lessons_json FROM students WHERE student_id = ?')
|
||
.get(studentId) as { advisory_teacher: string | null; private_lessons_json: string | null } | undefined;
|
||
|
||
if (!row) return null;
|
||
if (row.advisory_teacher) return row.advisory_teacher;
|
||
if (row.private_lessons_json) {
|
||
try {
|
||
const pl = JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
|
||
return pl.detectedAdvisor || null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// ----------------------------------------------------
|
||
// Exam Reports (Sınav Rapor) Store
|
||
// ----------------------------------------------------
|
||
|
||
public saveExamReports(studentId: string, reports: ExamReportDetail[], syncedAt?: string): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
const existing = row.exams_json ? (JSON.parse(row.exams_json) as ExamStore) : null;
|
||
const reportsMap: Record<string, ExamReportDetail> = existing?.reports ? { ...existing.reports } : {};
|
||
const now = syncedAt || toIstanbulIsoString();
|
||
|
||
reports.forEach(r => {
|
||
reportsMap[r.summary.id] = r;
|
||
});
|
||
|
||
const exams: ExamStore = {
|
||
lastSynced: now,
|
||
reports: reportsMap,
|
||
topicWeaknesses: existing?.topicWeaknesses || {},
|
||
questions: existing?.questions || {}
|
||
};
|
||
|
||
this.sqlite
|
||
.prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(JSON.stringify(exams), now, studentId);
|
||
}
|
||
|
||
public getExamReports(studentId: string): ExamStore | null {
|
||
const row = this.sqlite
|
||
.prepare('SELECT exams_json FROM students WHERE student_id = ?')
|
||
.get(studentId) as { exams_json: string | null } | undefined;
|
||
|
||
if (!row?.exams_json) return null;
|
||
try {
|
||
return JSON.parse(row.exams_json) as ExamStore;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public saveTopicWeaknesses(studentId: string, examId: string, weaknesses: ExamTopicWeakness[]): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
const exams: ExamStore = row.exams_json
|
||
? (JSON.parse(row.exams_json) as ExamStore)
|
||
: {
|
||
lastSynced: toIstanbulIsoString(),
|
||
reports: {},
|
||
topicWeaknesses: {},
|
||
questions: {}
|
||
};
|
||
|
||
if (!exams.topicWeaknesses) {
|
||
exams.topicWeaknesses = {};
|
||
}
|
||
exams.topicWeaknesses[examId] = weaknesses;
|
||
|
||
this.sqlite
|
||
.prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(JSON.stringify(exams), toIstanbulIsoString(), studentId);
|
||
}
|
||
|
||
public getTopicWeaknesses(studentId: string, examId: string): ExamTopicWeakness[] | null {
|
||
const exams = this.getExamReports(studentId);
|
||
return exams?.topicWeaknesses?.[examId] || null;
|
||
}
|
||
|
||
public saveExamQuestions(studentId: string, examId: string, questions: ExamQuestionItem[]): void {
|
||
const row = this.ensureStudentRow(studentId);
|
||
const exams: ExamStore = row.exams_json
|
||
? (JSON.parse(row.exams_json) as ExamStore)
|
||
: {
|
||
lastSynced: toIstanbulIsoString(),
|
||
reports: {},
|
||
topicWeaknesses: {},
|
||
questions: {}
|
||
};
|
||
|
||
if (!exams.questions) {
|
||
exams.questions = {};
|
||
}
|
||
exams.questions[examId] = questions;
|
||
|
||
this.sqlite
|
||
.prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
|
||
.run(JSON.stringify(exams), toIstanbulIsoString(), studentId);
|
||
}
|
||
|
||
public getExamQuestions(studentId: string, examId: string): ExamQuestionItem[] | null {
|
||
const exams = this.getExamReports(studentId);
|
||
return exams?.questions?.[examId] || null;
|
||
}
|
||
|
||
public close(): void {
|
||
try {
|
||
if (this.sqlite && this.sqlite.open) {
|
||
try {
|
||
this.sqlite.pragma('wal_checkpoint(TRUNCATE)');
|
||
} catch {
|
||
// Ignore checkpoint errors
|
||
}
|
||
this.sqlite.close();
|
||
}
|
||
} catch {
|
||
// Ignore close errors
|
||
}
|
||
}
|
||
}
|