BeKultur/test/run-tests.ts
2026-11-09 22:07:19 +00:00

1335 lines
58 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'assert';
import fs from 'fs';
import os from 'os';
import path from 'path';
import crypto from 'crypto';
import { LocalDatabase } from '../src/services/db';
import { SQLiteSessionStore } from '../src/services/session-store';
import { translate, normalizeLocale } from '../src/services/i18n';
import { InsightService } from '../src/services/insight';
import { ScraperService } from '../src/services/scraper';
import { SyllabusService } from '../src/services/syllabus';
import { ExamService } from '../src/services/exam';
import {
ISTANBUL_TIMEZONE,
getIstanbulParts,
toIstanbulIsoString,
formatIstanbulTime,
formatIstanbulDate,
getIstanbulMondayStart,
isBeforeCurrentMondayInIstanbul
} from '../src/utils/time';
import { Assignment, Lesson, ExamReportDetail } from '../src/types';
// Configure isolated temporary directory BEFORE any server/db singleton initialization
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-'));
const testDbPath = path.join(tempDir, 'test-bekultur.db');
const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json');
process.env.NODE_ENV = 'test';
process.env.DB_PATH = testDbPath;
process.env.LEGACY_JSON_PATH = testLegacyJsonPath;
import { shouldTriggerMondayWeeklySync, syncWeeklyStudentData } from '../src/server';
async function runAllTests() {
console.log('========================================================');
console.log(' BeKultur - Automated Test Suite');
console.log('========================================================\n');
let passed = 0;
let failed = 0;
function test(name: string, fn: () => void | Promise<void>) {
return (async () => {
try {
await fn();
console.log(` ✓ ${name}`);
passed++;
} catch (err: any) {
console.error(` ✗ ${name}`);
console.error(` Error: ${err.message}\n`);
failed++;
}
})();
}
try {
// 1. Date Parsing
await test('InsightService: parsePortalDate parses Turkish DD.MM.YYYY correctly', () => {
const d1 = InsightService.parsePortalDate('20.10.2026');
assert(d1 !== null, 'Date should not be null');
assert.strictEqual(d1.getFullYear(), 2026);
assert.strictEqual(d1.getMonth(), 9);
assert.strictEqual(d1.getDate(), 20);
const d2 = InsightService.parsePortalDate('8.11.2026');
assert(d2 !== null);
assert.strictEqual(d2.getMonth(), 10);
assert.strictEqual(d2.getDate(), 8);
const invalid = InsightService.parsePortalDate('');
assert.strictEqual(invalid, null);
});
// 2. Teacher Note Extraction
await test('InsightService: extractTeacherCheckNote detects various teacher notes', () => {
const n1 = InsightService.extractTeacherCheckNote('fenomen ayt 237-242 kontrol tarihi 26-30 ekim');
assert.strictEqual(n1?.toLowerCase(), '26-30 ekim');
const n2 = InsightService.extractTeacherCheckNote('3D TYT sf. 99-118 + 3D AYT sf. 123-130 (kontrol tarihi 27 Ekim)');
assert.strictEqual(n2?.toLowerCase(), '27 ekim');
const n3 = InsightService.extractTeacherCheckNote('12 MF:X YAYINCILIK (ÖDEVLER 26-30 EKİM ARASINDA KONTROL EDİLECEKTİR.)');
assert.strictEqual(n3?.toLowerCase(), '26-30 ekim');
const n4 = InsightService.extractTeacherCheckNote('AYT 1. KİTAP [26-56] ÇÖZÜLECEKTİR. 26 10 KONTROL');
assert.strictEqual(n4?.toLowerCase(), '26 ekim');
const nNone = InsightService.extractTeacherCheckNote('Toprak Yayınları Bölüm 4 çözülecek.');
assert.strictEqual(nNone, null);
});
// 3. Status Computation
await test('InsightService: computeStatus correctly handles completed, next-week, and overdue', () => {
const refDate = new Date(2026, 9, 21);
const s1 = InsightService.computeStatus({
id: 'test1',
subject: 'Matematik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '10.10.2026',
endDate: '25.10.2026',
parsedStartDate: '2026-10-10',
parsedEndDate: '2026-10-25',
description: 'Test',
detectedCheckDate: null,
completed: true,
completedAt: '2026-10-21T10:00:00Z'
}, refDate);
assert.strictEqual(s1, 'completed');
const s2 = InsightService.computeStatus({
id: 'test2',
subject: 'Biyoloji',
type: 'Yayın',
unit: '',
topic: '',
startDate: '01.10.2026',
endDate: '19.10.2026',
parsedStartDate: '2026-10-01',
parsedEndDate: '2026-10-19',
description: 'Old test',
detectedCheckDate: null,
completed: false,
completedAt: null
}, refDate);
assert.strictEqual(s2, 'overdue');
const s3 = InsightService.computeStatus({
id: 'test3',
subject: 'AYT Kimya',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'ayt 237-242 kontrol tarihi 26-30 ekim',
detectedCheckDate: '26-30 ekim',
completed: false,
completedAt: null
}, refDate);
assert.strictEqual(s3, 'next-week');
});
// 4. Statistics Calculation
await test('InsightService: calculateStats computes accurate completion rates and subject breakdown', () => {
const sampleAssignments: Assignment[] = [
{
id: '1',
subject: 'Kimya',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'Test 1',
detectedCheckDate: null,
status: 'next-week',
completed: false,
completedAt: null
},
{
id: '2',
subject: 'Kimya',
type: 'Yayın',
unit: '',
topic: '',
startDate: '10.10.2026',
endDate: '15.10.2026',
parsedStartDate: '2026-10-10',
parsedEndDate: '2026-10-15',
description: 'Test 2',
detectedCheckDate: null,
status: 'completed',
completed: true,
completedAt: '2026-10-21T10:00:00Z'
},
{
id: '3',
subject: 'Fizik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '01.10.2026',
endDate: '10.10.2026',
parsedStartDate: '2026-10-01',
parsedEndDate: '2026-10-10',
description: 'Test 3',
detectedCheckDate: null,
status: 'overdue',
completed: false,
completedAt: null
}
];
const stats = InsightService.calculateStats(sampleAssignments);
assert.strictEqual(stats.total, 3);
assert.strictEqual(stats.completed, 1);
assert.strictEqual(stats.checkedNextWeek, 1);
assert.strictEqual(stats.overdue, 1);
assert.strictEqual(stats.completionRate, 33);
assert.strictEqual(stats.bySubject['Kimya'].total, 2);
assert.strictEqual(stats.bySubject['Kimya'].completed, 1);
assert.strictEqual(stats.bySubject['Kimya'].percentage, 50);
// Test with an excluded (disincluded) assignment
const sampleWithExcluded: Assignment[] = [
...sampleAssignments,
{
id: '4',
subject: 'Fizik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'Other class homework',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null,
excluded: true
}
];
const statsExcluded = InsightService.calculateStats(sampleWithExcluded);
assert.strictEqual(statsExcluded.total, 3, 'Disincluded assignment must NOT increase total count');
assert.strictEqual(statsExcluded.excludedCount, 1);
assert.strictEqual(statsExcluded.bySubject['Fizik'].total, 1, 'Disincluded assignment must NOT be in subject total');
});
// 5. Local Database (SQLite)
await test('LocalDatabase (SQLite): save, merge, and toggle checkboxes with ACID persistence', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_${Date.now()}`;
const testItem: Assignment = {
id: `hash_${Date.now()}`,
subject: 'Matematik',
type: 'Yayın',
unit: 'Fonksiyonlar',
topic: 'Test',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'Sayfa 50-60',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null
};
db.mergeAssignments(testStudentId, [testItem]);
let store = db.getStudentStore(testStudentId);
assert(store.assignments[testItem.id]);
assert.strictEqual(store.assignments[testItem.id].completed, false);
const updated = db.toggleAssignment(testStudentId, testItem.id, true);
assert.strictEqual(updated?.completed, true);
assert(updated?.completedAt !== null);
db.mergeAssignments(testStudentId, [{
...testItem,
completed: false
}]);
store = db.getStudentStore(testStudentId);
assert.strictEqual(
store.assignments[testItem.id].completed,
true,
'mergeAssignments MUST preserve user checked status!'
);
// Test disinclude / exclude toggle & preservation across merge
const excludedRes = db.toggleExcludeAssignment(testStudentId, testItem.id, true);
assert.strictEqual(excludedRes?.excluded, true);
// Re-merge from scraper (which always returns excluded undefined or false)
db.mergeAssignments(testStudentId, [{
...testItem,
completed: false
}]);
store = db.getStudentStore(testStudentId);
assert.strictEqual(
store.assignments[testItem.id].excluded,
true,
'mergeAssignments MUST preserve disincluded (excluded) status across scraper syncs!'
);
// Restore / Include back
db.toggleExcludeAssignment(testStudentId, testItem.id, false);
store = db.getStudentStore(testStudentId);
assert.strictEqual(store.assignments[testItem.id].excluded, false);
db.saveCredentials(testStudentId, 'test_pass');
const creds = db.getRememberedCredentials(testStudentId);
assert.strictEqual(creds?.password, 'test_pass');
db.clearCredentials(testStudentId);
assert.strictEqual(db.getRememberedCredentials(testStudentId), null);
});
// 6. Syllabus & Station Filtering Tests
await test('SyllabusService: getWeekMetadata computes accurate ISO week and Monday-Friday dates', () => {
const refDate = new Date(2026, 9, 21); // Wednesday 21 Oct 2026
const meta = SyllabusService.getWeekMetadata(refDate);
assert(meta.weekId.includes('2026-W43') || meta.weekId.includes('2026-W'), 'Must have valid week ID');
assert(meta.weekRange.includes('19.10.2026 - 23.10.2026'), `Expected 19.10 - 23.10, got ${meta.weekRange}`);
});
await test('SyllabusService: normalizeStation handles various formats', () => {
assert.strictEqual(SyllabusService.normalizeStation('İst4'), 'İst-4');
assert.strictEqual(SyllabusService.normalizeStation('İst-4'), 'İst-4');
assert.strictEqual(SyllabusService.normalizeStation('ist1'), 'İst-1');
assert.strictEqual(SyllabusService.normalizeStation('2'), 'İst-2');
assert.strictEqual(SyllabusService.normalizeStation(null), null);
});
await test('SyllabusService: filterLessonsForStation isolates student station and keeps class lessons', () => {
const rawWednesdayLessons: Lesson[] = [
// Period 1 has 5 stations + duplicates
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst1', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst2', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst3', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'Türk Edebiyatı', teacher: 'OĞUZHAN YİĞİT', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst5', day: 3, dayName: 'Çarşamba' },
// Period 2 is whole-class (no station)
{ period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
];
// Filter for İst-4
const filteredForIst4 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-4');
assert.strictEqual(filteredForIst4.length, 2, 'Should have exactly 2 lessons: 1 for İst-4 and 1 for class');
assert.strictEqual(filteredForIst4[0].subject, 'TYT Kimya');
assert.strictEqual(filteredForIst4[0].station, 'İst4');
assert.strictEqual(filteredForIst4[1].subject, 'TYT Matematik');
assert.strictEqual(filteredForIst4[1].station, null);
// Filter for İst-5
const filteredForIst5 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-5');
assert.strictEqual(filteredForIst5.length, 2);
assert.strictEqual(filteredForIst5[0].subject, 'Türk Edebiyatı');
assert.strictEqual(filteredForIst5[0].station, 'İst5');
// Filter for "all"
const filteredAll = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'all');
assert.strictEqual(filteredAll.length, 6, 'Should show all 5 stations + 1 class lesson');
});
await test('SyllabusService: getCurrentLessonStatus correctly detects active and upcoming lessons in TR & EN', () => {
const lessons: Lesson[] = [
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
{ period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
];
// Simulate Wednesday at 09:45 (during 1. Ders)
const activeTime = new Date(2026, 9, 21, 9, 45);
const activeResTr = SyllabusService.getCurrentLessonStatus(lessons, 3, activeTime, 'tr');
assert(activeResTr.currentLesson !== null);
assert.strictEqual(activeResTr.currentLesson?.subject, 'TYT Kimya');
assert(activeResTr.statusText?.includes('Şu anki ders:'), 'Default Turkish statusText must include "Şu anki ders:"');
// Simulate Wednesday at 10:08 (break before 2. Ders)
const breakTime = new Date(2026, 9, 21, 10, 8);
const breakResEn = SyllabusService.getCurrentLessonStatus(lessons, 3, breakTime, 'en');
assert.strictEqual(breakResEn.currentLesson, null);
assert(breakResEn.nextLesson !== null);
assert.strictEqual(breakResEn.nextLesson?.subject, 'TYT Matematik');
assert(breakResEn.statusText?.includes('Next up:'), 'English statusText must include "Next up:"');
});
await test('LocalDatabase: saveSyllabus, getSyllabus, and setStudentStation persist in SQLite', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_syl_${Date.now()}`;
db.saveSyllabus(testStudentId, '2026-W43', '19.10.2026 - 23.10.2026', {
1: [],
2: [],
3: [],
4: [],
5: []
});
let s = db.getSyllabus(testStudentId);
assert(s !== null);
assert.strictEqual(s.weekId, '2026-W43');
db.setStudentStation(testStudentId, 'İst-4');
s = db.getSyllabus(testStudentId);
assert(s !== null);
assert.strictEqual(s.selectedStation, 'İst-4');
});
// 7. Advisory Teacher & Private Lessons Tests
await test('SyllabusService: advisoryTeacher filtering collapses multiple Danışmanlık teachers down to student advisor', () => {
const tuesdayLessons: Lesson[] = [
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'CAN TÜRKOĞLU', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'SEVGİ BİKİL', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MERVE BAŞTAN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MUSTAFA ŞEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' }
];
const filteredForCan = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'CAN TÜRKOĞLU');
assert.strictEqual(filteredForCan.length, 1, 'Should filter out the other 4 teachers and keep exactly 1');
assert.strictEqual(filteredForCan[0].teacher, 'CAN TÜRKOĞLU');
const filteredForUlku = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'ÜLKÜ ESEN');
assert.strictEqual(filteredForUlku.length, 1);
assert.strictEqual(filteredForUlku[0].teacher, 'ÜLKÜ ESEN');
});
await test('LocalDatabase: savePrivateLessons, getPrivateLessons, and advisory teacher persistence', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_pl_${Date.now()}`;
const mockLessons = [
{
id: 'pl_1',
subject: 'Coğrafya',
teacherName: 'SEVDA KILIÇOĞLU',
teacherPhoto: 'http://example.com/2337.jpg',
date: '26.10.2026',
parsedDate: '2026-10-26',
isUpcoming: true
},
{
id: 'pl_2',
subject: 'Danışmanlık',
teacherName: 'CAN TÜRKOĞLU',
teacherPhoto: 'http://example.com/2211.jpg',
date: '20.10.2026',
parsedDate: '2026-10-20',
isUpcoming: false
}
];
db.savePrivateLessons(testStudentId, mockLessons, undefined, 'CAN TÜRKOĞLU');
const plStore = db.getPrivateLessons(testStudentId);
assert(plStore !== null);
assert.strictEqual(plStore.lessons.length, 2);
assert.strictEqual(plStore.detectedAdvisor, 'CAN TÜRKOĞLU');
// Verify auto-set advisory teacher
assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'CAN TÜRKOĞLU');
// Manual override
db.setStudentAdvisoryTeacher(testStudentId, 'SEVGİ BİKİL');
assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'SEVGİ BİKİL');
});
// 8. Exam Reports & Analytics Tests
await test('ExamService: categorizeExam correctly segregates TYT and AYT', () => {
assert.strictEqual(ExamService.categorizeExam('12 YKS-01_MF'), 'TYT');
assert.strictEqual(ExamService.categorizeExam('12 YKS-04 MF'), 'TYT');
assert.strictEqual(ExamService.categorizeExam('TYT Deneme Sınavı 3'), 'TYT');
assert.strictEqual(ExamService.categorizeExam('12 AYT-01 MF'), 'AYT');
assert.strictEqual(ExamService.categorizeExam('AYT Sayısal Deneme'), 'AYT');
assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 80), 'AYT');
assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 120), 'TYT');
});
await test('ExamService: computeDeltasAndRatings calculates Net deltas, Rank deltas, and difficulty-adjusted ratings', () => {
const mockExams: ExamReportDetail[] = [
{
summary: {
id: '3322',
name: '12 YKS-01_MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 78,
totalWrong: 22,
totalEmpty: 20,
totalNet: 72.50,
totalScore: 72.50,
generalRank: 16
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 6, emptyCount: 4, net: 28.5, score: 28.5, percentage: 71 }
],
hasAnswerKey: true
},
{
summary: {
id: '3326',
name: '12 YKS-02_MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 88,
totalWrong: 18,
totalEmpty: 14,
totalNet: 83.50,
totalScore: 83.50,
generalRank: 14
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 35, wrongCount: 2, emptyCount: 3, net: 34.5, score: 34.5, percentage: 86 }
],
hasAnswerKey: true
},
{
summary: {
id: '3340',
name: '12 YKS-03 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 92,
totalWrong: 16,
totalEmpty: 12,
totalNet: 88.00,
totalScore: 88.00,
generalRank: 8
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 36, wrongCount: 2, emptyCount: 2, net: 35.5, score: 35.5, percentage: 89 }
],
hasAnswerKey: true
},
{
summary: {
id: '3366',
name: '12 YKS-04 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 86,
totalWrong: 14,
totalEmpty: 20,
totalNet: 82.50,
totalScore: 82.50,
generalRank: 9
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 7, emptyCount: 3, net: 28.25, score: 28.25, percentage: 75 }
],
hasAnswerKey: true
}
];
const processed = ExamService.computeDeltasAndRatings(mockExams);
assert.strictEqual(processed.length, 4);
const yks1 = processed.find(p => p.summary.id === '3322')!;
const yks2 = processed.find(p => p.summary.id === '3326')!;
const yks3 = processed.find(p => p.summary.id === '3340')!;
const yks4 = processed.find(p => p.summary.id === '3366')!;
assert.strictEqual(yks1.summary.deltaNet, undefined);
assert.strictEqual(yks1.summary.deltaRank, undefined);
assert.strictEqual(yks2.summary.deltaNet, 11.00);
assert.strictEqual(yks2.summary.deltaRank, 2);
assert.strictEqual(yks2.summary.rating?.label, 'Breakthrough');
assert.strictEqual(yks2.subjects[0].deltaNet, 6.00);
assert.strictEqual(yks3.summary.deltaNet, 4.50);
assert.strictEqual(yks3.summary.deltaRank, 6);
assert.strictEqual(yks3.summary.rating?.label, 'Breakthrough');
assert.strictEqual(yks4.summary.deltaNet, -5.50);
assert.strictEqual(yks4.summary.deltaRank, -1);
assert.strictEqual(yks4.summary.rating?.label, 'Outperformed Curve');
});
await test('ExamService: calculateKPIs correctly computes aggregate metrics', () => {
const mockDetails: ExamReportDetail[] = [
{
summary: {
id: '1',
name: 'Exam 1',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 80,
totalWrong: 20,
totalEmpty: 20,
totalNet: 75.0,
totalScore: 75.0,
generalRank: 15
},
subjects: [],
hasAnswerKey: false
},
{
summary: {
id: '2',
name: 'Exam 2',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 90,
totalWrong: 15,
totalEmpty: 15,
totalNet: 85.0,
totalScore: 85.0,
generalRank: 5
},
subjects: [],
hasAnswerKey: false
}
];
const kpis = ExamService.calculateKPIs(mockDetails);
assert.strictEqual(kpis.latestNet, 75.0);
assert.strictEqual(kpis.bestNet, 85.0);
assert.strictEqual(kpis.averageNet, 80.0);
assert.strictEqual(kpis.bestRank, 5);
assert.strictEqual(kpis.averageRank, 10);
assert.strictEqual(kpis.totalExams, 2);
});
await test('LocalDatabase: saveExamReports and saveTopicWeaknesses persistence', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_exam_${Date.now()}`;
const mockDetail: ExamReportDetail = {
summary: {
id: '9999',
name: 'Test Exam',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 80,
totalWrong: 20,
totalEmpty: 20,
totalNet: 75.0,
totalScore: 75.0,
generalRank: 10
},
subjects: [],
hasAnswerKey: false
};
db.saveExamReports(testStudentId, [mockDetail]);
const examStore = db.getExamReports(testStudentId);
assert(examStore !== null);
assert(examStore.reports['9999'] !== undefined);
assert.strictEqual(examStore.reports['9999'].summary.name, 'Test Exam');
const mockWeakness = [
{
examId: '9999',
examName: 'Test Exam',
subjectName: 'Türkçe',
topicName: 'Paragraf',
totalCount: 5,
correctCount: 2,
wrongCount: 3,
emptyCount: 0,
successRate: 40
}
];
db.saveTopicWeaknesses(testStudentId, '9999', mockWeakness);
const retrieved = db.getTopicWeaknesses(testStudentId, '9999');
assert(retrieved !== null);
assert.strictEqual(retrieved.length, 1);
assert.strictEqual(retrieved[0].topicName, 'Paragraf');
});
// 9. PWA & Offline Support Tests
await test('PWA: manifest.json is valid and contains standard required PWA fields and icons', () => {
const manifestPath = path.resolve(__dirname, '../public/manifest.json');
assert(fs.existsSync(manifestPath), 'manifest.json must exist in public directory');
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
assert.strictEqual(manifest.name, 'BeKultur');
assert.strictEqual(manifest.short_name, 'BeKultur');
assert.strictEqual(manifest.display, 'standalone');
assert.strictEqual(manifest.start_url, '/');
assert(Array.isArray(manifest.icons) && manifest.icons.length >= 2, 'manifest must declare icons');
manifest.icons.forEach((ic: { src: string }) => {
const iconPath = path.resolve(__dirname, '../public', ic.src.replace(/^\//, ''));
assert(fs.existsSync(iconPath), `Icon file ${ic.src} must exist at ${iconPath}`);
});
});
await test('PWA: sw.js contains static asset pre-caching and offline cache fallback strategies', () => {
const swPath = path.resolve(__dirname, '../public/sw.js');
assert(fs.existsSync(swPath), 'sw.js must exist in public directory');
const swContent = fs.readFileSync(swPath, 'utf-8');
assert(swContent.includes('CACHE_NAME'), 'sw.js must define cache name');
assert(swContent.includes('STATIC_ASSETS'), 'sw.js must define static assets array');
assert(swContent.includes("addEventListener('install'"), 'sw.js must have install event listener');
assert(swContent.includes("addEventListener('activate'"), 'sw.js must have activate event listener');
assert(swContent.includes("addEventListener('fetch'"), 'sw.js must have fetch event listener');
assert(swContent.includes('caches.match'), 'sw.js must contain cache match fallback');
});
await test('PWA: pwa.js contains offline detection, theme toggle, and UI safeguard handlers', () => {
const pwaPath = path.resolve(__dirname, '../public/js/pwa.js');
assert(fs.existsSync(pwaPath), 'pwa.js must exist in public/js directory');
const pwaContent = fs.readFileSync(pwaPath, 'utf-8');
assert(pwaContent.includes(".register('/sw.js'"), 'pwa.js must register service worker');
assert(pwaContent.includes("addEventListener('online'"), 'pwa.js must listen for online event');
assert(pwaContent.includes("addEventListener('offline'"), 'pwa.js must listen for offline event');
assert(pwaContent.includes('offlineBanner'), 'pwa.js must manage offline banner');
assert(pwaContent.includes('themeToggleBtn'), 'pwa.js must wire dark/light theme toggle');
assert(pwaContent.includes('assignment-toggle'), 'pwa.js must manage homework checkboxes in offline mode');
assert(pwaContent.includes('privateLessonForm'), 'pwa.js must manage private lesson request form in offline mode');
assert(pwaContent.includes('btnSync'), 'pwa.js must manage sync buttons in offline mode');
});
// 10. Security, SQLite Migration, Session Store, i18n, and Dark Theme Tests
await test('LocalDatabase: saveCredentials encrypts with AES-256-GCM v2 and getRememberedCredentials decrypts', () => {
const db = LocalDatabase.getInstance();
const testId = 'audit_security_student';
const rawPass = 'SuperSecret123!';
db.saveCredentials(testId, rawPass);
// Verify stored format in SQLite is encrypted with enc:v2:
const row = db
.getSqliteDb()
.prepare('SELECT remembered_password FROM students WHERE student_id = ?')
.get(testId) as { remembered_password: string } | undefined;
assert(row && row.remembered_password, 'Credentials row must exist in SQLite');
assert(row.remembered_password.startsWith('enc:v2:'), 'Stored password must be encrypted with enc:v2: prefix');
assert(!row.remembered_password.includes(rawPass), 'Raw password must not be present in SQLite');
// Verify retrieval returns decrypted password
const retrieved = db.getRememberedCredentials(testId);
assert(retrieved !== null, 'Retrieved credentials must not be null');
assert.strictEqual(retrieved.password, rawPass, 'Decrypted password must match original raw password');
db.clearCredentials(testId);
});
await test('LocalDatabase: Zero-Data-Loss Migration from legacy db.json to SQLite (preserving v1 credentials & filtering synthetic test records)', () => {
const migJsonPath = path.join(tempDir, 'legacy-db.json');
const migDbPath = path.join(tempDir, 'migrated-bekultur.db');
// Encrypt a password using the legacy v1 scheme (`enc:<iv>:<tag>:<cipher>` with default legacy key)
const legacyKey = crypto.scryptSync('bekultur_secret_key_change_in_production', 'bekultur_credential_salt', 32);
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', legacyKey, iv);
let encrypted = cipher.update('MyLegacyPortalPassword99', 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
const legacyCiphertext = `enc:${iv.toString('hex')}:${authTag}:${encrypted}`;
const legacyPayload = {
students: {
'415': {
studentId: '415',
lastSynced: '2026-10-25T12:00:00.000Z',
rememberedCredentials: {
studentId: '415',
password: legacyCiphertext
},
assignments: {
hw_completed_1: {
id: 'hw_completed_1',
subject: 'AYT Matematik',
type: 'Yayın',
unit: 'Türev',
topic: 'Limit ve Süreklilik',
startDate: '20.10.2026',
endDate: '27.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-27',
description: '3D AYT Sayfa 100-120',
detectedCheckDate: '27 ekim',
status: 'completed',
completed: true,
completedAt: '2026-10-24T18:30:00.000Z',
excluded: false
},
hw_excluded_2: {
id: 'hw_excluded_2',
subject: 'Biyoloji',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '27.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-27',
description: 'Diğer şube ödevi',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null,
excluded: true
}
},
syllabus: {
weekId: '2026-W43',
weekRange: '19.10.2026 - 23.10.2026',
lastSynced: '2026-10-25T12:00:00.000Z',
selectedStation: 'İst-4',
advisoryTeacher: 'CAN TÜRKOĞLU',
days: { 1: [], 2: [], 3: [], 4: [], 5: [] }
},
privateLessons: {
lastSynced: '2026-10-25T12:00:00.000Z',
detectedAdvisor: 'CAN TÜRKOĞLU',
lessons: [
{
id: 'pl_legacy_1',
subject: 'Fizik',
teacherName: 'CAN TÜRKOĞLU',
teacherPhoto: null,
date: '26.10.2026',
parsedDate: '2026-10-26',
isUpcoming: true
}
]
},
exams: {
lastSynced: '2026-10-25T12:00:00.000Z',
reports: {
'3366': {
summary: {
id: '3366',
name: '12 YKS-04 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 90,
totalWrong: 16,
totalEmpty: 14,
totalNet: 86.0,
totalScore: 86.0,
generalRank: 7
},
subjects: [],
hasAnswerKey: true
}
},
topicWeaknesses: {
'3366': [
{
examId: '3366',
examName: '12 YKS-04 MF',
subjectName: 'Fizik',
topicName: 'Optik',
totalCount: 3,
correctCount: 1,
wrongCount: 2,
emptyCount: 0,
successRate: 33
}
]
},
questions: {
'3366_Y': [
{
questionNumber: 5,
correctAnswer: 'D',
studentAnswer: 'B',
imageUrl: 'https://example.com/q5.png',
status: 'wrong',
subjectId: '14',
subjectName: 'Fizik'
}
]
}
}
},
test_student_99999: {
studentId: 'test_student_99999',
lastSynced: null,
assignments: {}
},
audit_security_student: {
studentId: 'audit_security_student',
lastSynced: null,
assignments: {}
}
}
};
fs.writeFileSync(migJsonPath, JSON.stringify(legacyPayload, null, 2), 'utf-8');
// Instantiate LocalDatabase pointing to the legacy JSON file
const migratedDb = new LocalDatabase(migDbPath, migJsonPath);
// 1. Verify backup file was created
assert(fs.existsSync(`${migJsonPath}.bak`), 'Non-destructive backup legacy-db.json.bak must be created');
// 2. Verify real student 415 data was 100% preserved
const store415 = migratedDb.getStudentStore('415');
assert.strictEqual(store415.lastSynced, '2026-10-25T12:00:00.000Z');
assert(store415.assignments['hw_completed_1'], 'Completed assignment must be migrated');
assert.strictEqual(store415.assignments['hw_completed_1'].completed, true);
assert.strictEqual(store415.assignments['hw_completed_1'].completedAt, '2026-10-24T18:30:00.000Z');
assert(store415.assignments['hw_excluded_2'], 'Excluded assignment must be migrated');
assert.strictEqual(store415.assignments['hw_excluded_2'].excluded, true);
// 3. Verify legacy v1 encrypted password decrypts seamlessly and was upgraded to v2 at rest
const creds415 = migratedDb.getRememberedCredentials('415');
assert(creds415 !== null, 'Legacy credentials must be migrated and decryptable');
assert.strictEqual(creds415.password, 'MyLegacyPortalPassword99');
// 4. Verify syllabus, private lessons, and exam reports migrated intact
const syl415 = migratedDb.getSyllabus('415');
assert.strictEqual(syl415?.selectedStation, 'İst-4');
assert.strictEqual( migratedDb.getStudentAdvisoryTeacher('415'), 'CAN TÜRKOĞLU');
const pl415 = migratedDb.getPrivateLessons('415');
assert.strictEqual(pl415?.lessons.length, 1);
assert.strictEqual(pl415?.lessons[0].subject, 'Fizik');
const exams415 = migratedDb.getExamReports('415');
assert(exams415?.reports['3366'], 'Exam report 3366 must be migrated');
assert.strictEqual(exams415?.reports['3366'].summary.totalNet, 86.0);
assert.strictEqual(migratedDb.getTopicWeaknesses('415', '3366')?.[0].topicName, 'Optik');
assert.strictEqual(migratedDb.getExamQuestions('415', '3366_Y')?.[0].questionNumber, 5);
// 5. Verify synthetic test_student_* and audit_* records were filtered out
const rowTest = migratedDb
.getSqliteDb()
.prepare('SELECT student_id FROM students WHERE student_id IN (?, ?)')
.all('test_student_99999', 'audit_security_student');
assert.strictEqual(rowTest.length, 0, 'Synthetic test_student_* and audit_* records must be skipped during migration');
// 6. Toggle hw_excluded_2 as completed in SQLite, close DB (simulating container restart), and reopen
migratedDb.toggleAssignment('415', 'hw_excluded_2', true);
migratedDb.close();
// Modify legacy db.json (e.g. adding a new student 416 while 415 still has hw_excluded_2 completed: false in JSON)
const updatedLegacy = JSON.parse(fs.readFileSync(migJsonPath, 'utf-8'));
updatedLegacy.students['416'] = {
studentId: '416',
lastSynced: '2026-10-26T10:00:00.000Z',
assignments: {}
};
fs.writeFileSync(migJsonPath, JSON.stringify(updatedLegacy, null, 2), 'utf-8');
const reopenedDb = new LocalDatabase(migDbPath, migJsonPath);
const reopened415 = reopenedDb.getStudentStore('415');
assert.strictEqual(
reopened415.assignments['hw_excluded_2'].completed,
true,
'Restart/re-migration must NEVER overwrite newer completed state in SQLite!'
);
const reopened416 = reopenedDb.getStudentStore('416');
assert.strictEqual(reopened416.lastSynced, '2026-10-26T10:00:00.000Z', 'Additive migration must import newly added student 416');
reopenedDb.close();
});
await test('SQLiteSessionStore: persists sessions, encrypts portalCookies at rest, and prunes expired sessions', async () => {
const db = LocalDatabase.getInstance();
const store = new SQLiteSessionStore({ db: db.getSqliteDb(), pruneIntervalMs: 0 });
const sid = 'test_session_id_123';
const sessionData: any = {
cookie: {
originalMaxAge: 60000,
expires: new Date(Date.now() + 60000).toISOString()
},
studentId: '415',
portalCookies: 'ASP.NET_SessionId=secret_portal_cookie_val; path=/'
};
await new Promise<void>((resolve, reject) => {
store.set(sid, sessionData, err => (err ? reject(err) : resolve()));
});
// Verify raw SQLite row encrypts portalCookies at rest
const rawRow = db
.getSqliteDb()
.prepare('SELECT sess FROM sessions WHERE sid = ?')
.get(sid) as { sess: string } | undefined;
assert(rawRow, 'Session row must exist in SQLite');
assert(!rawRow.sess.includes('secret_portal_cookie_val'), 'Plaintext portal cookie must NOT appear in SQLite sessions table');
assert(rawRow.sess.includes('enc:v2:'), 'Portal cookie must be encrypted with AES-256-GCM v2 in SQLite');
// Verify store.get decrypts portalCookies transparently
const loaded = await new Promise<any>((resolve, reject) => {
store.get(sid, (err, sess) => (err ? reject(err) : resolve(sess)));
});
assert(loaded, 'Loaded session must not be null');
assert.strictEqual(loaded.studentId, '415');
assert.strictEqual(loaded.portalCookies, 'ASP.NET_SessionId=secret_portal_cookie_val; path=/');
// Insert an already-expired session and verify pruneExpired removes it
const expiredSid = 'expired_session_id_999';
db.getSqliteDb()
.prepare('INSERT OR REPLACE INTO sessions (sid, sess, expire) VALUES (?, ?, ?)')
.run(expiredSid, '{}', Date.now() - 10000);
store.pruneExpired();
const expiredLoaded = await new Promise<any>((resolve, reject) => {
store.get(expiredSid, (err, sess) => (err ? reject(err) : resolve(sess)));
});
assert.strictEqual(expiredLoaded, null, 'Expired session must be pruned');
// Destroy session
await new Promise<void>((resolve, reject) => {
store.destroy(sid, err => (err ? reject(err) : resolve()));
});
const afterDestroy = await new Promise<any>((resolve, reject) => {
store.get(sid, (err, sess) => (err ? reject(err) : resolve(sess)));
});
assert.strictEqual(afterDestroy, null, 'Destroyed session must return null');
});
await test('i18n Service: defaults to Turkish (tr) with official E-Kültür terminology parity and supports English (en)', () => {
assert.strictEqual(normalizeLocale(undefined), 'tr', 'Default locale must be Turkish (tr)');
assert.strictEqual(normalizeLocale('tr'), 'tr');
assert.strictEqual(normalizeLocale('en'), 'en');
assert.strictEqual(normalizeLocale('fr'), 'tr', 'Unsupported locale must fall back to Turkish (tr)');
// Verify Official E-Kültür Turkish terminology
assert.strictEqual(translate('tr', 'login.studentIdLabel'), 'Öğrenci ID');
assert.strictEqual(translate('tr', 'login.passwordLabel'), 'Parola');
assert.strictEqual(translate('tr', 'login.submit'), 'Giriş Yap');
assert.strictEqual(translate('tr', 'nav.homework'), 'Ödevler');
assert.strictEqual(translate('tr', 'nav.syllabus'), 'Ders Programı');
assert.strictEqual(translate('tr', 'nav.privateLessons'), 'Özel Ders');
assert.strictEqual(translate('tr', 'nav.exams'), 'Sınav Raporları');
assert.strictEqual(translate('tr', 'privateLessons.requestTitle'), 'Özel Ders İstek');
assert(translate('tr', 'exams.subtabBreakdown').includes('Sınav Karne'));
assert(translate('tr', 'exams.subtabWeakness').includes('Yanlış Konular'));
assert.strictEqual(translate('tr', 'exams.answerKey'), 'Cevap Anahtarı');
// Verify English translation & parameter interpolation
assert.strictEqual(translate('en', 'nav.homework'), 'Homework');
assert.strictEqual(translate('en', 'exams.kpiAcrossExams', { count: 4 }), 'Across all 4 exams');
assert.strictEqual(translate('tr', 'exams.kpiAcrossExams', { count: 4 }), 'Toplam 4 sınav içinde');
// Verify all served page routes in server.ts are strictly English (no Turkish route aliases)
const serverContent = fs.readFileSync(path.resolve(__dirname, '../src/server.ts'), 'utf-8');
const disallowedRoutes = ['/Kullanici/Giris', '/giris', '/Odev', '/odev', '/dersprogrami', '/ozelders', '/OzelDers', '/ozeldersistek', '/rapor/sinav'];
for (const route of disallowedRoutes) {
assert(!serverContent.includes(`'${route}'`), `Route ${route} must not be served; all page paths must be English`);
}
});
await test('UI & Dark Theme: header.ejs and style.css implement modern color-scheme, theme toggle, and language switcher', () => {
const headerPath = path.resolve(__dirname, '../views/partials/header.ejs');
const cssPath = path.resolve(__dirname, '../public/css/style.css');
const headerContent = fs.readFileSync(headerPath, 'utf-8');
const cssContent = fs.readFileSync(cssPath, 'utf-8');
assert(headerContent.includes('meta name="color-scheme" content="light dark"'), 'header.ejs must declare color-scheme meta tag');
assert(headerContent.includes('id="themeToggleBtn"'), 'header.ejs must include themeToggleBtn');
assert(headerContent.includes('theme-icon-sun" aria-hidden="true">L<'), 'header.ejs must use L for light theme indicator');
assert(headerContent.includes('theme-icon-moon" aria-hidden="true">D<'), 'header.ejs must use D for dark theme indicator');
assert(headerContent.includes('class="lang-switcher"'), 'header.ejs must include TR | EN language switcher');
assert(headerContent.includes('window.BeKulturDict'), 'header.ejs must expose client-side i18n dictionary');
assert(cssContent.includes('color-scheme: light dark'), 'style.css must set color-scheme: light dark on :root');
assert(cssContent.includes('@media (prefers-color-scheme: dark)'), 'style.css must support system dark mode preference');
assert(cssContent.includes(':root[data-theme="dark"]'), 'style.css must support explicit dark theme override');
});
await test('LocalDatabase: saveExamQuestions and getExamQuestions persists question review cache', () => {
const db = LocalDatabase.getInstance();
const testId = 'audit_exam_student';
const examKey = '3366_Y';
const sampleQuestions = [
{
questionNumber: 1,
correctAnswer: 'A',
studentAnswer: 'C',
imageUrl: 'https://panel.example.com/soru/1.png',
status: 'wrong' as const,
subjectId: '10',
subjectName: 'Türkçe'
}
];
db.saveExamQuestions(testId, examKey, sampleQuestions);
const cached = db.getExamQuestions(testId, examKey);
assert(cached !== null, 'Cached questions should exist');
assert.strictEqual(cached.length, 1);
assert.strictEqual(cached[0].questionNumber, 1);
assert.strictEqual(cached[0].correctAnswer, 'A');
});
await test('PWA: sw.js contains route-specific offline fallbacks and ignoreSearch', () => {
const swPath = path.resolve(__dirname, '../public/sw.js');
const swContent = fs.readFileSync(swPath, 'utf-8');
assert(swContent.includes('ignoreSearch: true'), 'sw.js must match cache ignoring query strings');
assert(swContent.includes("url.pathname.startsWith('/exams')"), 'sw.js must have route fallback for exams');
assert(swContent.includes("url.pathname.startsWith('/syllabus')"), 'sw.js must have route fallback for syllabus');
assert(swContent.includes("url.pathname.startsWith('/private-lessons')"), 'sw.js must have route fallback for private lessons');
});
// 11. Fixed Istanbul Timezone (Europe/Istanbul) Tests
await test('Istanbul Time Utility: always enforces Europe/Istanbul (UTC+3) regardless of host timezone', () => {
assert.strictEqual(ISTANBUL_TIMEZONE, 'Europe/Istanbul');
assert.strictEqual(process.env.TZ, 'Europe/Istanbul');
// 2026-10-25T20:51:45.000Z in UTC is 23:51:45 on Sunday 25.10.2026 in Istanbul (UTC+3)
const utcSundayNight = '2026-10-25T20:51:45.000Z';
assert.strictEqual(formatIstanbulTime(utcSundayNight), '23:51');
assert.strictEqual(formatIstanbulDate(utcSundayNight), '25.10.2026');
// 2026-10-25T21:30:00.000Z in UTC is 00:30:00 on Monday 26.10.2026 in Istanbul (UTC+3)
const utcMondayEarly = new Date('2026-10-25T21:30:00.000Z');
const parts = getIstanbulParts(utcMondayEarly);
assert.strictEqual(parts.year, 2026);
assert.strictEqual(parts.month, 10);
assert.strictEqual(parts.day, 26);
assert.strictEqual(parts.hour, 0);
assert.strictEqual(parts.minute, 30);
assert.strictEqual(parts.dayOfWeek, 1, '00:30 Istanbul time must be Monday (dayOfWeek = 1)');
assert.strictEqual(formatIstanbulDate(utcMondayEarly), '26.10.2026');
assert(toIstanbulIsoString(utcMondayEarly).endsWith('+03:00'), 'ISO timestamp must carry +03:00 Istanbul offset');
});
await test('Istanbul Time Utility: getIstanbulMondayStart and isBeforeCurrentMondayInIstanbul accurately detect Monday 00:00:00+03:00 boundary', () => {
// Suppose current time is Wednesday 28 Oct 2026 14:00 Istanbul time (11:00 UTC)
const wednesdayNow = new Date('2026-10-28T11:00:00.000Z');
const mondayStart = getIstanbulMondayStart(wednesdayNow);
// Monday 26 Oct 2026 00:00:00+03:00 is 2026-10-25T21:00:00.000Z
assert.strictEqual(mondayStart.toISOString(), '2026-10-25T21:00:00.000Z');
// Sunday 25 Oct 2026 23:59:59+03:00 (1 second before Monday start in Istanbul)
const sundayLastSecond = '2026-10-25T20:59:59.000Z';
assert.strictEqual(isBeforeCurrentMondayInIstanbul(sundayLastSecond, wednesdayNow), true);
// Monday 26 Oct 2026 00:00:00+03:00 (exact start of Monday in Istanbul)
const mondayFirstSecond = '2026-10-25T21:00:00.000Z';
assert.strictEqual(isBeforeCurrentMondayInIstanbul(mondayFirstSecond, wednesdayNow), false);
// Null/empty timestamp must return true (needs sync)
assert.strictEqual(isBeforeCurrentMondayInIstanbul(null, wednesdayNow), true);
});
// 12. PWA Image Proxy & URL Normalization Tests
await test('PWA Image Fix: ScraperService normalizes HTTP portal URLs to HTTPS and routes through /api/image-proxy', () => {
const rawHttpProfile = 'http://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg';
const normalized = ScraperService.normalizeImageUrl(rawHttpProfile);
assert.strictEqual(
normalized,
'https://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg',
'HTTP portal profile photo must upgrade to HTTPS'
);
const proxied = ScraperService.toProxiedImageUrl(rawHttpProfile);
assert.strictEqual(
proxied,
'/api/image-proxy?url=' + encodeURIComponent('https://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg'),
'Portal image must be rewritten to same-origin /api/image-proxy'
);
// Relative question image URL
const relQuestion = '/uploads/soru/9988.png';
assert.strictEqual(
ScraperService.normalizeImageUrl(relQuestion),
'https://panel.ozelbursakulturokullari.com/uploads/soru/9988.png'
);
// Verify sw.js upgrades to bekultur-v4, uses /api/image-proxy, and never caches opaque failed responses
const swContent = fs.readFileSync(path.resolve(__dirname, '../public/sw.js'), 'utf-8');
assert(swContent.includes("CACHE_NAME = 'bekultur-v4'"), 'sw.js must use bumped cache version bekultur-v4');
assert(swContent.includes('/api/image-proxy'), 'sw.js must route portal images through /api/image-proxy');
assert(!swContent.includes("networkResponse.type === 'opaque'"), 'sw.js must NOT cache opaque error responses');
});
// 13. Automatic Monday Weekly Sync on Login Tests
await test('Weekly Monday Login Sync: automatically syncs recent homework, exams, and syllabus when previous login was before Monday 00:00 Istanbul time', async () => {
const db = LocalDatabase.getInstance();
const studentId = 'monday_sync_student_415';
// Simulate a student who last logged in on Sunday 25 Oct 2026 at 22:00 Istanbul time (+03:00)
const sundayLogin = '2026-10-25T22:00:00.000+03:00';
db.updateLastLogin(studentId, sundayLogin);
assert.strictEqual(db.getLastLogin(studentId), sundayLogin);
// Current time: Monday 26 Oct 2026 at 08:30 Istanbul time (+03:00)
const mondayMorning = new Date('2026-10-26T08:30:00.000+03:00');
assert.strictEqual(
shouldTriggerMondayWeeklySync(studentId, mondayMorning),
true,
'Login on Monday morning after Sunday login must trigger weekly sync'
);
// Mock ScraperService methods to verify syncWeeklyStudentData orchestrates all 3 syncs
const origScrapeRecent = ScraperService.scrapeMultiplePages;
const origScrapeExams = ScraperService.scrapeAllExamDetails;
const origScrapeSyllabus = ScraperService.scrapeSyllabus;
let recentCalled = 0;
let examsCalled = 0;
let syllabusCalled = 0;
ScraperService.scrapeMultiplePages = async () => {
recentCalled++;
return {
totalPages: 2,
assignments: [
{
id: 'monday_hw_1',
subject: 'AYT Fizik',
type: 'Yayın',
unit: 'Modern Fizik',
topic: 'Fotoelektrik',
startDate: '26.10.2026',
endDate: '02.11.2026',
parsedStartDate: '2026-10-26',
parsedEndDate: '2026-11-02',
description: 'Sayfa 10-20',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null
}
]
};
};
ScraperService.scrapeAllExamDetails = async () => {
examsCalled++;
return [
{
summary: {
id: '4001',
name: '12 YKS-05 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 95,
totalWrong: 12,
totalEmpty: 13,
totalNet: 92.0,
totalScore: 92.0,
generalRank: 4
},
subjects: [],
hasAnswerKey: true
}
];
};
ScraperService.scrapeSyllabus = async () => {
syllabusCalled++;
return {
1: [
{
period: '1. Ders',
periodNumber: 1,
subject: 'TYT Matematik',
teacher: 'BİRKAN BOZKURT',
teacherPhoto: 'https://panel.ozelbursakulturokullari.com/assets/uploads/profile/1025.jpg',
startTime: '09:30',
endTime: '10:05',
time: '09:30 - 10:05',
station: null,
day: 1,
dayName: 'Pazartesi'
}
],
2: [],
3: [],
4: [],
5: []
};
};
try {
await syncWeeklyStudentData(studentId, 'mock_cookie=1', mondayMorning);
assert.strictEqual(recentCalled, 1, 'scrapeMultiplePages must be called once');
assert.strictEqual(examsCalled, 1, 'scrapeAllExamDetails must be called once');
assert.strictEqual(syllabusCalled, 1, 'scrapeSyllabus must be called once');
// Verify all 3 stores and last_login_at were updated in SQLite
const updatedStore = db.getStudentStore(studentId);
assert(updatedStore.assignments['monday_hw_1'], 'Recent homework must be saved to SQLite');
const updatedExams = db.getExamReports(studentId);
assert(updatedExams?.reports['4001'], 'Recent exam report must be saved to SQLite');
const updatedSyllabus = db.getSyllabus(studentId);
assert.strictEqual(updatedSyllabus?.schedule[1]?.length, 1, 'Updated syllabus must be saved to SQLite');
// Verify subsequent request on the same Monday does NOT re-trigger weekly sync
const mondayAfternoon = new Date('2026-10-26T15:00:00.000+03:00');
assert.strictEqual(
shouldTriggerMondayWeeklySync(studentId, mondayAfternoon),
false,
'Subsequent login/request in the same week must NOT re-trigger Monday sync'
);
} finally {
ScraperService.scrapeMultiplePages = origScrapeRecent;
ScraperService.scrapeAllExamDetails = origScrapeExams;
ScraperService.scrapeSyllabus = origScrapeSyllabus;
}
});
// Optional Live Portal Test (via environment variables only)
const testStudentId = process.env.TEST_STUDENT_ID;
const testPassword = process.env.TEST_PASSWORD;
if (testStudentId && testPassword) {
await test('ScraperService: Live portal authentication and scraping', async () => {
const loginRes = await ScraperService.login(testStudentId, testPassword);
assert.strictEqual(loginRes.success, true, `Login failed: ${loginRes.error}`);
const scrapeRes = await ScraperService.scrapePage(loginRes.cookies, 1, testStudentId);
assert(scrapeRes.assignments.length > 0, 'Page 1 must contain homework cards');
});
} else {
console.log(' - Live portal test skipped (set TEST_STUDENT_ID and TEST_PASSWORD to run)');
}
} finally {
try {
LocalDatabase.getInstance().close();
} catch {
// ignore
}
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
}
console.log('\n--------------------------------------------------------');
console.log(`Test Results: ${passed} passed, ${failed} failed`);
console.log('--------------------------------------------------------\n');
if (failed > 0) {
process.exit(1);
}
}
runAllTests().catch(err => {
console.error('Fatal test error:', err);
process.exit(1);
});