diff --git a/public/css/style.css b/public/css/style.css index 2dc6113..5f2b2d8 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -718,3 +718,328 @@ code { flex-direction: column; } } + +/* ---------------- Syllabus & Navigation Styles ---------------- */ +.brand-group { + display: flex; + align-items: center; + gap: 20px; +} + +.main-nav { + display: flex; + gap: 6px; +} + +.nav-item { + text-decoration: none; + color: var(--text-muted); + font-size: 0.85rem; + font-weight: 500; + padding: 4px 10px; + border-radius: var(--radius); + transition: all 0.15s ease; +} + +.nav-item:hover { + color: var(--text-main); + background: #f1f5f9; +} + +.nav-item.active { + color: var(--primary); + font-weight: 600; + background: #eff6ff; +} + +.station-select-row, .view-toggle-row { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.toolbar-label { + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); + min-width: 55px; +} + +.station-pills, .view-toggle-pills { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.station-btn, .view-btn { + background: #f1f5f9; + border: 1px solid var(--border); + color: var(--text-main); + font-size: 0.8rem; + padding: 4px 10px; + border-radius: var(--radius); + cursor: pointer; + transition: all 0.15s ease; +} + +.station-btn:hover, .view-btn:hover { + background: #e2e8f0; +} + +.station-btn.active, .view-btn.active { + background: var(--primary); + border-color: var(--primary); + color: white; + font-weight: 600; +} + +.live-period-banner { + background: #eff6ff; + border: 1px solid #bfdbfe; + color: #1e40af; + padding: 8px 12px; + border-radius: var(--radius); + font-size: 0.85rem; + font-weight: 500; + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 14px; +} + +.live-dot { + color: #2563eb; + animation: pulse 1.5s infinite; +} + +@keyframes pulse { + 0% { opacity: 1; } + 50% { opacity: 0.3; } + 100% { opacity: 1; } +} + +.day-tabs { + display: flex; + gap: 6px; + margin-bottom: 12px; + flex-wrap: wrap; +} + +.day-tab-btn { + background: var(--bg-card); + border: 1px solid var(--border); + color: var(--text-muted); + padding: 6px 12px; + border-radius: var(--radius); + font-size: 0.85rem; + font-weight: 500; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; + transition: all 0.15s ease; +} + +.day-tab-btn:hover { + background: #f8fafc; + color: var(--text-main); +} + +.day-tab-btn.active { + background: var(--primary); + border-color: var(--primary); + color: white; +} + +.today-badge { + background: #fef3c7; + color: #b45309; + font-size: 0.7rem; + padding: 1px 4px; + border-radius: 3px; + font-weight: 600; +} + +.day-tab-btn.active .today-badge { + background: rgba(255, 255, 255, 0.25); + color: white; +} + +.day-count-badge { + background: #f1f5f9; + color: var(--text-muted); + font-size: 0.7rem; + padding: 1px 5px; + border-radius: 9999px; +} + +.day-tab-btn.active .day-count-badge { + background: rgba(255, 255, 255, 0.2); + color: white; +} + +.timetable-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.timetable-row { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 16px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} + +.period-col { + display: flex; + flex-direction: column; + min-width: 90px; +} + +.period-num { + font-weight: 700; + font-size: 0.95rem; +} + +.period-time { + font-size: 0.78rem; + color: var(--text-muted); +} + +.subject-col { + flex: 1; +} + +.subject-title { + font-weight: 600; + font-size: 0.95rem; + color: var(--text-main); +} + +.teacher-info { + display: flex; + align-items: center; + gap: 6px; + margin-top: 2px; +} + +.teacher-thumb { + width: 20px; + height: 20px; + border-radius: 50%; + object-fit: cover; +} + +.teacher-name { + font-size: 0.8rem; + color: var(--text-muted); +} + +.station-badge { + background: #fef3c7; + color: #b45309; + font-size: 0.75rem; + font-weight: 700; + padding: 2px 8px; + border-radius: 4px; + border: 1px solid #fde68a; +} + +.class-badge { + background: #f1f5f9; + color: var(--text-muted); + font-size: 0.75rem; + padding: 2px 8px; + border-radius: 4px; +} + +.table-responsive { + overflow-x: auto; +} + +.week-grid-table { + width: 100%; + border-collapse: collapse; + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + font-size: 0.825rem; +} + +.week-grid-table th, .week-grid-table td { + border: 1px solid var(--border); + padding: 8px 10px; + text-align: left; + vertical-align: top; +} + +.week-grid-table th { + background: #f8fafc; + font-weight: 600; +} + +.grid-today-th { + background: #eff6ff !important; + color: var(--primary); +} + +.grid-today-pill { + font-size: 0.68rem; + background: #dbeafe; + color: #1e40af; + padding: 1px 4px; + border-radius: 3px; + margin-left: 4px; +} + +.grid-period-cell { + min-width: 80px; + background: #f8fafc; +} + +.grid-period-title { + font-weight: 700; +} + +.grid-period-time { + font-size: 0.725rem; + color: var(--text-muted); +} + +.grid-lesson-cell { + min-width: 135px; +} + +.grid-lesson-cell.has-lesson { + background: #ffffff; +} + +.grid-lesson-subject { + font-weight: 600; + font-size: 0.825rem; +} + +.grid-lesson-teacher { + font-size: 0.75rem; + color: var(--text-muted); +} + +.grid-station-tag { + display: inline-block; + font-size: 0.68rem; + background: #fef3c7; + color: #b45309; + padding: 1px 4px; + border-radius: 3px; + margin-top: 3px; +} + +.grid-empty-cell { + color: var(--text-light); +} diff --git a/public/js/syllabus.js b/public/js/syllabus.js new file mode 100644 index 0000000..47817e6 --- /dev/null +++ b/public/js/syllabus.js @@ -0,0 +1,106 @@ +document.addEventListener('DOMContentLoaded', () => { + const stationPills = document.getElementById('stationPills'); + const viewTogglePills = document.getElementById('viewTogglePills'); + const dayTabs = document.getElementById('dayTabs'); + const dayViewContainer = document.getElementById('dayViewContainer'); + const weekViewContainer = document.getElementById('weekViewContainer'); + const btnSyncSyllabus = document.getElementById('btnSyncSyllabus'); + const syllabusAlert = document.getElementById('syllabusAlert'); + + // 1. Station Pill Selection (AJAX) + if (stationPills) { + stationPills.addEventListener('click', async (e) => { + const btn = e.target.closest('.station-btn'); + if (!btn) return; + + const station = btn.dataset.station; + stationPills.querySelectorAll('.station-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + + try { + const res = await fetch('/api/syllabus/station', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ station }) + }); + const data = await res.json(); + if (data.success) { + // Fast reload to render both day & week grids accurately + window.location.reload(); + } + } catch (err) { + console.error('Failed to change station:', err); + } + }); + } + + // 2. View Toggle (Day View vs Full Week Grid) + if (viewTogglePills) { + viewTogglePills.addEventListener('click', (e) => { + const btn = e.target.closest('.view-btn'); + if (!btn) return; + + const viewMode = btn.dataset.view; + viewTogglePills.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + + if (viewMode === 'day') { + if (dayViewContainer) dayViewContainer.classList.remove('hidden'); + if (weekViewContainer) weekViewContainer.classList.add('hidden'); + } else { + if (dayViewContainer) dayViewContainer.classList.add('hidden'); + if (weekViewContainer) weekViewContainer.classList.remove('hidden'); + } + }); + } + + // 3. Day Tabs Switching + if (dayTabs) { + dayTabs.addEventListener('click', (e) => { + const btn = e.target.closest('.day-tab-btn'); + if (!btn) return; + + const dayNumber = btn.dataset.day; + dayTabs.querySelectorAll('.day-tab-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + + // Hide all panels, show target panel + document.querySelectorAll('.day-schedule-panel').forEach(p => p.classList.add('hidden')); + const activePanel = document.getElementById(`panelDay${dayNumber}`); + if (activePanel) activePanel.classList.remove('hidden'); + }); + } + + // 4. Sync Syllabus + if (btnSyncSyllabus) { + btnSyncSyllabus.addEventListener('click', async () => { + btnSyncSyllabus.disabled = true; + btnSyncSyllabus.textContent = 'Syncing...'; + showAlert('Fetching weekly timetable across all 5 days...', 'info'); + + try { + const res = await fetch('/api/syllabus/sync', { method: 'POST' }); + const data = await res.json(); + if (data.success) { + showAlert('Syllabus updated successfully!', 'info'); + window.location.reload(); + } else { + showAlert(`Sync failed: ${data.error}`, 'danger'); + btnSyncSyllabus.disabled = false; + btnSyncSyllabus.textContent = 'Sync Syllabus'; + } + } catch (err) { + showAlert('Network error while syncing syllabus.', 'danger'); + btnSyncSyllabus.disabled = false; + btnSyncSyllabus.textContent = 'Sync Syllabus'; + } + }); + } + + function showAlert(msg, type = 'info') { + if (!syllabusAlert) return; + syllabusAlert.className = `alert alert-${type}`; + syllabusAlert.textContent = msg; + syllabusAlert.classList.remove('hidden'); + } +}); diff --git a/src/server.ts b/src/server.ts index c069ba5..f51dc65 100644 --- a/src/server.ts +++ b/src/server.ts @@ -6,6 +6,7 @@ import dotenv from 'dotenv'; import { ScraperService } from './services/scraper'; import { LocalDatabase } from './services/db'; import { InsightService } from './services/insight'; +import { SyllabusService, DAY_NAMES } from './services/syllabus'; import { Assignment } from './types'; dotenv.config(); @@ -406,6 +407,154 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => { } }); +/** + * GET /syllabus + * Syllabus (Ders Programı) View with station filtering & weekly updates + */ +app.get('/syllabus', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const currentWeek = SyllabusService.getWeekMetadata(); + + let syllabusStore = db.getSyllabus(studentId); + + // If syllabus missing or belongs to an older week, auto-sync from portal! + if (!syllabusStore || !syllabusStore.weekId || syllabusStore.weekId !== currentWeek.weekId) { + let cookies = req.session.portalCookies; + if (!cookies) { + const creds = db.getRememberedCredentials(studentId); + if (creds) { + const loginRes = await ScraperService.login(creds.studentId, creds.password); + if (loginRes.success) { + cookies = loginRes.cookies; + req.session.portalCookies = cookies; + } + } + } + + if (cookies) { + try { + const schedule = await ScraperService.scrapeSyllabus(cookies); + db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule); + syllabusStore = db.getSyllabus(studentId); + } catch (err: any) { + console.error('Failed auto-syncing weekly syllabus:', err.message); + } + } + } + + // Selected station (default to İst-4 if not chosen yet) + const selectedStation = syllabusStore?.selectedStation || 'İst-4'; + + // Active day: 1 = Mon .. 5 = Fri (if weekend, default to Mon) + const todayDay = new Date().getDay(); + const defaultDay = todayDay >= 1 && todayDay <= 5 ? todayDay : 1; + const activeDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay; + + // Compute filtered schedule for selected station + const rawSchedule = syllabusStore?.schedule || {}; + const filteredSchedule: Record = {}; + for (let d = 1; d <= 5; d++) { + filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation); + } + + const currentStatus = SyllabusService.getCurrentLessonStatus( + filteredSchedule[activeDay] || [], + activeDay + ); + + res.render('syllabus', { + title: 'Syllabus - BeKultur', + studentId, + weekId: currentWeek.weekId, + weekRange: currentWeek.weekRange, + selectedStation, + activeDay, + filteredSchedule, + currentStatus, + lastSynced: syllabusStore?.lastSynced || null, + DAY_NAMES + }); +}); + +/** + * POST /api/syllabus/station + * Update selected station + */ +app.post('/api/syllabus/station', requireAuth, (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const { station } = req.body; + + db.setStudentStation(studentId, station || null); + const syllabusStore = db.getSyllabus(studentId); + + const rawSchedule = syllabusStore?.schedule || {}; + const filteredSchedule: Record = {}; + for (let d = 1; d <= 5; d++) { + filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null); + } + + res.json({ + success: true, + selectedStation: station, + filteredSchedule + }); +}); + +/** + * POST /api/syllabus/sync + * Manually refresh syllabus across all 5 days from portal + */ +app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + let cookies = req.session.portalCookies; + + try { + if (!cookies) { + const creds = db.getRememberedCredentials(studentId); + if (creds) { + const loginRes = await ScraperService.login(creds.studentId, creds.password); + if (loginRes.success) { + cookies = loginRes.cookies; + req.session.portalCookies = cookies; + } + } + } + + if (!cookies) { + return res.status(401).json({ + success: false, + error: 'Session expired. Please log in again to sync syllabus.' + }); + } + + const currentWeek = SyllabusService.getWeekMetadata(); + const schedule = await ScraperService.scrapeSyllabus(cookies); + db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule); + + const store = db.getSyllabus(studentId); + const selectedStation = store?.selectedStation || 'İst-4'; + + const filteredSchedule: Record = {}; + for (let d = 1; d <= 5; d++) { + filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation); + } + + res.json({ + success: true, + weekId: currentWeek.weekId, + weekRange: currentWeek.weekRange, + lastSynced: store?.lastSynced, + filteredSchedule + }); + } catch (err: any) { + console.error('API syllabus sync error:', err.message); + res.status(500).json({ + success: false, + error: `Syllabus sync failed: ${err.message}` + }); + } +}); + // Start Server if (process.env.NODE_ENV !== 'test') { app.listen(PORT, () => { diff --git a/src/services/db.ts b/src/services/db.ts index 57fe79b..056aa25 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -142,4 +142,44 @@ export class LocalDatabase { const student = this.cache.students[studentId]; return student?.rememberedCredentials || null; } + + public saveSyllabus( + studentId: string, + weekId: string, + weekRange: string, + schedule: Record + ): void { + const student = this.getStudentStore(studentId); + const existingStation = student.syllabus?.selectedStation || null; + + student.syllabus = { + weekId, + weekRange, + selectedStation: existingStation, + lastSynced: new Date().toISOString(), + schedule + }; + this.save(); + } + + public setStudentStation(studentId: string, station: string | null): void { + const student = this.getStudentStore(studentId); + if (!student.syllabus) { + student.syllabus = { + weekId: '', + weekRange: '', + selectedStation: station, + lastSynced: null, + schedule: {} + }; + } else { + student.syllabus.selectedStation = station; + } + this.save(); + } + + public getSyllabus(studentId: string): any { + const student = this.cache.students[studentId]; + return student?.syllabus || null; + } } diff --git a/src/services/scraper.ts b/src/services/scraper.ts index 76908e9..49c9cf7 100644 --- a/src/services/scraper.ts +++ b/src/services/scraper.ts @@ -1,8 +1,9 @@ import axios from 'axios'; import * as cheerio from 'cheerio'; import crypto from 'crypto'; -import { Assignment } from '../types'; +import { Assignment, Lesson } from '../types'; import { InsightService } from './insight'; +import { DAY_NAMES } from './syllabus'; const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com'; const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; @@ -304,4 +305,90 @@ export class ScraperService { totalPages }; } + + /** + * Scrape the 5-day syllabus (Ders Programı) from the portal + */ + public static async scrapeSyllabus(cookies: string): Promise> { + const weeklySchedule: Record = { + 1: [], + 2: [], + 3: [], + 4: [], + 5: [] + }; + + for (let day = 1; day <= 5; day++) { + try { + const url = `${BASE_URL}/dersprogrami?gun=${day}`; + const res = await axios.get(url, { + headers: { + 'User-Agent': USER_AGENT, + 'Cookie': cookies, + 'Referer': `${BASE_URL}/` + }, + validateStatus: () => true + }); + + if (res.status === 200 && typeof res.data === 'string') { + const $ = cheerio.load(res.data); + const dayLessons: Lesson[] = []; + + $('.col-md-8 .kltr-card').each((_, cardEl) => { + const card = $(cardEl); + const periodText = card.find('h5.card-title').text().trim(); + if (!periodText) return; + + const pNumMatch = periodText.match(/(\d+)/); + const periodNumber = pNumMatch ? parseInt(pNumMatch[1], 10) : 0; + + const pTags = card.find('p'); + const subject = $(pTags[0]).text().trim(); + const teacher = $(pTags[1]).text().trim(); + const time = $(pTags[2]).text().trim(); + + let stationRaw = ''; + for (let i = 3; i < pTags.length; i++) { + const text = $(pTags[i]).text().trim(); + if (text && /[İiIı]st/i.test(text)) { + stationRaw = text; + break; + } + } + + const station = stationRaw ? stationRaw : null; + const teacherPhoto = card.find('img.profil-resmi').attr('src') || null; + + let startTime = ''; + let endTime = ''; + if (time && time.includes('-')) { + const parts = time.split('-').map(t => t.trim()); + startTime = parts[0] || ''; + endTime = parts[1] || ''; + } + + dayLessons.push({ + period: periodText, + periodNumber, + subject, + teacher, + teacherPhoto, + startTime, + endTime, + time, + station, + day, + dayName: DAY_NAMES[day] || '' + }); + }); + + weeklySchedule[day] = dayLessons; + } + } catch (err: any) { + console.error(`Failed to scrape syllabus for day ${day}:`, err.message); + } + } + + return weeklySchedule; + } } diff --git a/src/services/syllabus.ts b/src/services/syllabus.ts new file mode 100644 index 0000000..d8b4eb1 --- /dev/null +++ b/src/services/syllabus.ts @@ -0,0 +1,175 @@ +import { Lesson } from '../types'; + +export const DAY_NAMES: Record = { + 1: 'Pazartesi', + 2: 'Salı', + 3: 'Çarşamba', + 4: 'Perşembe', + 5: 'Cuma' +}; + +export class SyllabusService { + /** + * Compute ISO week and Monday-Friday date range for a given date + */ + public static getWeekMetadata(refDate: Date = new Date()): { weekId: string; weekRange: string; mondayDate: Date } { + const d = new Date(refDate); + // Find Monday of the current week + const day = d.getDay(); // 0 is Sunday, 1 is Monday + const diffToMonday = day === 0 ? -6 : 1 - day; + const monday = new Date(d); + monday.setDate(d.getDate() + diffToMonday); + monday.setHours(0, 0, 0, 0); + + const friday = new Date(monday); + friday.setDate(monday.getDate() + 4); + + // Compute ISO week number + const target = new Date(monday); + const dayNr = (target.getDay() + 6) % 7; + target.setDate(target.getDate() - dayNr + 3); + const firstThursday = target.valueOf(); + target.setMonth(0, 1); + if (target.getDay() !== 4) { + target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7); + } + const weekNumber = 1 + Math.ceil((firstThursday - target.valueOf()) / 604800000); + const year = monday.getFullYear(); + + const weekId = `${year}-W${String(weekNumber).padStart(2, '0')}`; + + const fmtDate = (date: Date) => { + const dd = String(date.getDate()).padStart(2, '0'); + const mm = String(date.getMonth() + 1).padStart(2, '0'); + const yyyy = date.getFullYear(); + return `${dd}.${mm}.${yyyy}`; + }; + + const weekRange = `${fmtDate(monday)} - ${fmtDate(friday)}`; + + return { weekId, weekRange, mondayDate: monday }; + } + + /** + * Normalize station representations (e.g. "İst4", "ist-4", "4" -> "İst-4") + */ + public static normalizeStation(stationStr: string | null | undefined): string | null { + if (!stationStr) return null; + const s = stationStr.trim().toLowerCase(); + if (s === 'all') return 'all'; + const match = s.match(/([1-5])/); + if (match) { + return `İst-${match[1]}`; + } + return null; + } + + /** + * Filter lessons for a specific station (or show all stations without portal duplicate garbage) + */ + public static filterLessonsForStation(rawLessons: Lesson[], selectedStation: string | null): Lesson[] { + if (!rawLessons || !rawLessons.length) return []; + + const normTarget = this.normalizeStation(selectedStation); + + // Group lessons by periodNumber + const byPeriod: Record = {}; + for (const item of rawLessons) { + if (!byPeriod[item.periodNumber]) { + byPeriod[item.periodNumber] = []; + } + byPeriod[item.periodNumber].push(item); + } + + const result: Lesson[] = []; + const sortedPeriodKeys = Object.keys(byPeriod).map(Number).sort((a, b) => a - b); + + for (const pNum of sortedPeriodKeys) { + const periodGroup = byPeriod[pNum]; + + // Check if this period has station-based lessons + const stationLessons = periodGroup.filter(l => l.station !== null); + + if (stationLessons.length > 0) { + if (normTarget && normTarget !== 'all') { + // Find the lesson matching the student's assigned station + const matched = stationLessons.find(l => this.normalizeStation(l.station) === normTarget); + if (matched) { + result.push(matched); + } else { + // Fallback: if student station not in list, show first available + result.push(stationLessons[0]); + } + } else { + // If "All Stations" selected: keep unique station lessons (one per station) + const seenStations = new Set(); + for (const sl of stationLessons) { + const stNorm = this.normalizeStation(sl.station) || sl.station || ''; + if (!seenStations.has(stNorm)) { + seenStations.add(stNorm); + result.push(sl); + } + } + } + } else { + // Whole-class lesson (no stations): deduplicate if portal printed multiple copies + const seenKeys = new Set(); + for (const cl of periodGroup) { + const key = `${cl.periodNumber}|${cl.subject}|${cl.teacher}|${cl.time}`; + if (!seenKeys.has(key)) { + seenKeys.add(key); + result.push(cl); + } + } + } + } + + return result; + } + + /** + * Determine current active lesson or upcoming next lesson + */ + public static getCurrentLessonStatus( + dayLessons: Lesson[], + currentDayNumber: number, + refDate: Date = new Date() + ): { currentLesson: Lesson | null; nextLesson: Lesson | null; statusText: string | null } { + const todayDay = refDate.getDay(); // 1 = Mon, ..., 5 = Fri + if (todayDay !== currentDayNumber) { + return { currentLesson: null, nextLesson: null, statusText: null }; + } + + const nowMinutes = refDate.getHours() * 60 + refDate.getMinutes(); + + let current: Lesson | null = null; + let next: Lesson | null = null; + + for (const l of dayLessons) { + if (!l.startTime || !l.endTime) continue; + const [sh, sm] = l.startTime.split(':').map(Number); + const [eh, em] = l.endTime.split(':').map(Number); + + const startMin = sh * 60 + sm; + const endMin = eh * 60 + em; + + if (nowMinutes >= startMin && nowMinutes <= endMin) { + current = l; + break; + } else if (nowMinutes < startMin) { + if (!next) { + next = l; + } + } + } + + let statusText: string | null = null; + if (current) { + statusText = `Now in session: ${current.period} — ${current.subject} (${current.time})`; + } else if (next) { + statusText = `Next up: ${next.period} — ${next.subject} at ${next.startTime}`; + } + + return { currentLesson: current, nextLesson: next, statusText }; + } +} diff --git a/src/types/index.ts b/src/types/index.ts index 2a88453..954f89e 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -45,6 +45,31 @@ export interface DashboardStats { bySubject: Record; } +// ---------------------------------------------------- +// Syllabus (Ders Programı) Types +// ---------------------------------------------------- +export interface Lesson { + period: string; // e.g. "1. Ders" + periodNumber: number; // e.g. 1 + subject: string; // e.g. "TYT Kimya" + teacher: string; // e.g. "ÜLKÜ ESEN" + teacherPhoto: string | null; // image url + startTime: string; // "09:30" + endTime: string; // "10:05" + time: string; // "09:30 - 10:05" + station: string | null; // "İst1", "İst2", ..., null for whole-class + day: number; // 1 = Pazartesi ... 5 = Cuma + dayName: string; // "Pazartesi" ... "Cuma" +} + +export interface SyllabusStore { + weekId: string; // e.g. "2026-W43" + weekRange: string; // e.g. "19.10.2026 - 23.10.2026" + selectedStation: string | null; // e.g. "İst-4" or null/all + lastSynced: string | null; + schedule: Record; // day (1..5) -> raw lessons +} + export interface StudentStore { studentId: string; lastSynced: string | null; @@ -53,6 +78,7 @@ export interface StudentStore { password: string; }; assignments: Record; + syllabus?: SyllabusStore; } export interface DatabaseSchema { diff --git a/test/run-tests.ts b/test/run-tests.ts index cfcb4f3..aac0e30 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -2,7 +2,8 @@ import assert from 'assert'; import { LocalDatabase } from '../src/services/db'; import { InsightService } from '../src/services/insight'; import { ScraperService } from '../src/services/scraper'; -import { Assignment } from '../src/types'; +import { SyllabusService } from '../src/services/syllabus'; +import { Assignment, Lesson } from '../src/types'; async function runAllTests() { console.log('========================================================'); @@ -278,6 +279,95 @@ async function runAllTests() { 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', () => { + 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 activeRes = SyllabusService.getCurrentLessonStatus(lessons, 3, activeTime); + assert(activeRes.currentLesson !== null); + assert.strictEqual(activeRes.currentLesson?.subject, 'TYT Kimya'); + + // Simulate Wednesday at 10:08 (break before 2. Ders) + const breakTime = new Date(2026, 9, 21, 10, 8); + const breakRes = SyllabusService.getCurrentLessonStatus(lessons, 3, breakTime); + assert.strictEqual(breakRes.currentLesson, null); + assert(breakRes.nextLesson !== null); + assert.strictEqual(breakRes.nextLesson?.subject, 'TYT Matematik'); + }); + + await test('LocalDatabase: saveSyllabus, getSyllabus, and setStudentStation persist in db.json', () => { + 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.strictEqual(s.selectedStation, 'İst-4'); + }); + // 6. Optional Live Portal Test (via environment variables only) const testStudentId = process.env.TEST_STUDENT_ID; const testPassword = process.env.TEST_PASSWORD; diff --git a/views/partials/header.ejs b/views/partials/header.ejs index 200b408..341c453 100644 --- a/views/partials/header.ejs +++ b/views/partials/header.ejs @@ -9,10 +9,16 @@
-
+
BeKultur + <% if (typeof studentId !== 'undefined' && studentId) { %> + + <% } %>
<% if (typeof studentId !== 'undefined' && studentId) { %>
diff --git a/views/syllabus.ejs b/views/syllabus.ejs new file mode 100644 index 0000000..f2eea8c --- /dev/null +++ b/views/syllabus.ejs @@ -0,0 +1,189 @@ +<%- include('partials/header') %> + +
+ +
+
+

Syllabus

+

+ Week: <%= weekRange %> (<%= weekId %>) + • + + <% if (lastSynced) { %> + Synced: <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + <% } else { %> + Not synced + <% } %> + +

+
+ +
+ +
+
+ + + + + <% if (currentStatus && currentStatus.statusText) { %> +
+ ● + <%= currentStatus.statusText %> +
+ <% } %> + + +
+
+ Station: +
+ + + + + + +
+
+ +
+ View: +
+ + +
+
+
+ + +
+ +
+ <% [1, 2, 3, 4, 5].forEach(function(d) { %> + <% const isToday = (new Date().getDay() === d); %> + + <% }); %> +
+ + + <% [1, 2, 3, 4, 5].forEach(function(d) { %> +
+ <% const lessons = filteredSchedule[d] || []; %> + <% if (lessons.length === 0) { %> +
+

No lessons found for <%= DAY_NAMES[d] %>. Click "Sync Syllabus" to fetch from portal.

+
+ <% } else { %> +
+ <% lessons.forEach(function(l) { %> +
+
+ <%= l.period %> + <%= l.time %> +
+ +
+
<%= l.subject %>
+
+ <% if (l.teacherPhoto) { %> + <%= l.teacher %> + <% } %> + <%= l.teacher %> +
+
+ +
+ <% if (l.station) { %> + <%= l.station %> + <% } else { %> + Class + <% } %> +
+
+ <% }); %> +
+ <% } %> +
+ <% }); %> +
+ + + +
+ + +<%- include('partials/footer') %>