feat: enforce Europe/Istanbul timezone, fix PWA image proxy, add Monday weekly login sync, and standardize English routes
This commit is contained in:
parent
56274f479b
commit
93f0bcb7a1
16 changed files with 851 additions and 175 deletions
|
|
@ -10,20 +10,32 @@ 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');
|
||||
|
||||
// Use an isolated temporary directory so tests never pollute production data/
|
||||
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.DB_PATH = testDbPath;
|
||||
process.env.LEGACY_JSON_PATH = testLegacyJsonPath;
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
|
|
@ -1014,6 +1026,13 @@ async function runAllTests() {
|
|||
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', () => {
|
||||
|
|
@ -1067,6 +1086,210 @@ async function runAllTests() {
|
|||
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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue