diff --git a/public/css/style.css b/public/css/style.css index 98d8860..3593c15 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1065,3 +1065,385 @@ code { .grid-empty-cell { color: var(--text-light); } + +/* ---------------- Advisor Pill (Syllabus) ---------------- */ +.advisor-row { + display: flex; + align-items: center; + gap: 8px; +} + +.advisor-pill { + display: inline-flex; + align-items: center; + gap: 6px; + background: #f1f5f9; + border: 1px solid #e2e8f0; + padding: 3px 10px; + border-radius: 9999px; + font-size: 0.775rem; +} + +.advisor-name { + font-weight: 600; + color: var(--text-main); +} + +.advisor-sub { + color: var(--text-muted); + font-size: 0.7rem; + background: #e2e8f0; + padding: 1px 6px; + border-radius: 4px; +} + +/* ---------------- Private Lessons (Özel Ders) ---------------- */ +.student-profile-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 14px 18px; + margin-bottom: 16px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.student-profile-main { + display: flex; + align-items: center; + gap: 14px; +} + +.student-avatar { + width: 52px; + height: 52px; + border-radius: 50%; + object-fit: cover; + border: 2px solid var(--border); +} + +.student-meta { + display: flex; + flex-direction: column; + gap: 2px; +} + +.student-name { + font-size: 1.05rem; + font-weight: 700; + margin: 0; +} + +.student-school { + font-size: 0.8rem; + color: var(--text-muted); + margin: 0; +} + +.student-advisor-badge { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 0.775rem; + margin-top: 4px; +} + +.advisor-badge-label { + color: var(--text-muted); +} + +.student-policy-note { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: 0.775rem; + color: #92400e; + background: #fef3c7; + padding: 8px 12px; + border-radius: 6px; + border-left: 3px solid #f59e0b; +} + +.policy-icon { + font-weight: 700; +} + +/* Request Form */ +.request-form-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 18px 20px; + margin-bottom: 20px; +} + +.form-card-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; + padding-bottom: 10px; + border-bottom: 1px solid var(--border); +} + +.form-header-badge { + font-size: 0.725rem; + font-weight: 600; + background: #e0f2fe; + color: #0369a1; + padding: 2px 8px; + border-radius: 4px; +} + +.form-grid-3 { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 14px; + margin-bottom: 16px; +} + +.form-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.form-label { + font-size: 0.8rem; + font-weight: 600; + color: var(--text-main); + display: flex; + align-items: center; + justify-content: space-between; +} + +.select-loading { + font-size: 0.7rem; + font-weight: 400; + color: var(--primary); +} + +.form-select { + padding: 8px 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: #ffffff; + color: var(--text-main); + font-size: 0.875rem; + font-family: inherit; + transition: border-color 0.15s ease; +} + +.form-select:focus { + outline: none; + border-color: var(--primary); + box-shadow: 0 0 0 2px rgba(15, 23, 42, 0.08); +} + +.form-select:disabled { + background: #f8fafc; + color: var(--text-light); + cursor: not-allowed; +} + +.form-actions-row { + display: flex; + justify-content: flex-end; +} + +.form-feedback { + margin-top: 12px; + padding: 10px 14px; + border-radius: var(--radius); + font-size: 0.825rem; + font-weight: 500; +} + +.feedback-success { + background: #dcfce7; + color: #15803d; + border: 1px solid #bbf7d0; +} + +.feedback-error { + background: #fee2e2; + color: #b91c1c; + border: 1px solid #fecaca; +} + +/* Lessons List & Grid */ +.lessons-section { + display: flex; + flex-direction: column; + gap: 18px; +} + +.lessons-header-row { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 10px; +} + +.lessons-title-wrap { + display: flex; + align-items: center; + gap: 8px; +} + +.lessons-count-badge { + background: #f1f5f9; + color: var(--text-muted); + font-size: 0.75rem; + font-weight: 700; + padding: 2px 7px; + border-radius: 9999px; +} + +.subject-filter-pills { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; +} + +.subject-pill-btn { + font-family: inherit; + font-size: 0.725rem; + font-weight: 600; + padding: 3px 10px; + border-radius: 9999px; + background: #f1f5f9; + color: var(--text-muted); + border: 1px solid transparent; + cursor: pointer; + transition: all 0.15s ease; +} + +.subject-pill-btn:hover { + background: #e2e8f0; + color: var(--text-main); +} + +.subject-pill-btn.active { + background: var(--text-main); + color: #ffffff; +} + +.upcoming-lessons-group, +.past-lessons-group { + display: flex; + flex-direction: column; + gap: 10px; +} + +.group-header { + display: flex; + align-items: center; + gap: 8px; + padding-bottom: 4px; +} + +.group-title { + font-size: 0.85rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.03em; + color: var(--text-muted); +} + +.lessons-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 12px; +} + +.lesson-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 10px; + transition: transform 0.15s ease, box-shadow 0.15s ease; +} + +.lesson-card:hover { + transform: translateY(-1px); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05); +} + +.lesson-card.is-upcoming { + border-left: 3px solid var(--success); +} + +.lesson-card-header { + display: flex; + align-items: center; + justify-content: space-between; +} + +.lesson-date { + font-size: 0.775rem; + font-weight: 600; + color: var(--text-muted); +} + +.lesson-card-body { + display: flex; + align-items: center; + gap: 10px; +} + +.lesson-teacher-photo { + width: 40px; + height: 40px; + border-radius: 50%; + object-fit: cover; + border: 1px solid var(--border); +} + +.lesson-teacher-placeholder { + width: 40px; + height: 40px; + border-radius: 50%; + background: #f1f5f9; + color: var(--text-muted); + display: flex; + align-items: center; + justify-content: center; + font-weight: 700; + font-size: 1rem; +} + +.lesson-info { + display: flex; + flex-direction: column; + gap: 2px; +} + +.lesson-subject { + font-size: 0.95rem; + font-weight: 700; + margin: 0; + color: var(--text-main); +} + +.lesson-teacher { + font-size: 0.8rem; + color: var(--text-muted); + margin: 0; +} + +.empty-lessons-card { + background: var(--bg-card); + border: 1px dashed var(--border); + border-radius: var(--radius); + padding: 24px; + text-align: center; + color: var(--text-muted); + font-size: 0.875rem; +} diff --git a/public/js/private-lessons.js b/public/js/private-lessons.js new file mode 100644 index 0000000..208643a --- /dev/null +++ b/public/js/private-lessons.js @@ -0,0 +1,219 @@ +document.addEventListener('DOMContentLoaded', () => { + const selectCourse = document.getElementById('selectCourse'); + const selectUnit = document.getElementById('selectUnit'); + const selectTopic = document.getElementById('selectTopic'); + const unitLoading = document.getElementById('unitLoading'); + const topicLoading = document.getElementById('topicLoading'); + const btnSubmit = document.getElementById('btnSubmitRequest'); + const form = document.getElementById('privateLessonForm'); + const formFeedback = document.getElementById('formFeedback'); + const btnSync = document.getElementById('btnSyncPrivateLessons'); + const alertBox = document.getElementById('privateLessonsAlert'); + const subjectPills = document.querySelectorAll('.subject-pill-btn'); + const lessonCards = document.querySelectorAll('.lesson-card'); + const sinifIdInput = document.getElementById('sinifId'); + + function showAlert(message, type = 'info', timeout = 4000) { + if (!alertBox) return; + alertBox.className = `alert alert-${type}`; + alertBox.textContent = message; + alertBox.classList.remove('hidden'); + + if (timeout > 0) { + setTimeout(() => { + alertBox.classList.add('hidden'); + }, timeout); + } + } + + function showFeedback(message, type = 'success') { + if (!formFeedback) return; + formFeedback.className = `form-feedback feedback-${type}`; + formFeedback.textContent = message; + formFeedback.classList.remove('hidden'); + } + + function hideFeedback() { + if (formFeedback) formFeedback.classList.add('hidden'); + } + + // 1. Course changed -> Load Units + if (selectCourse) { + selectCourse.addEventListener('change', async () => { + hideFeedback(); + const dersId = selectCourse.value; + const sinifId = sinifIdInput ? sinifIdInput.value : ''; + + selectUnit.innerHTML = ''; + selectUnit.disabled = true; + selectTopic.innerHTML = ''; + selectTopic.disabled = true; + if (btnSubmit) btnSubmit.disabled = true; + + if (!dersId) return; + + if (unitLoading) unitLoading.classList.remove('hidden'); + + try { + const res = await fetch(`/api/private-lessons/units?dersId=${encodeURIComponent(dersId)}&sinifId=${encodeURIComponent(sinifId)}`); + const data = await res.json(); + + if (data.success && data.units && data.units.length > 0) { + selectUnit.innerHTML = '' + + data.units.map(u => ``).join(''); + selectUnit.disabled = false; + } else { + selectUnit.innerHTML = ''; + } + } catch (err) { + console.error('Error fetching units:', err); + selectUnit.innerHTML = ''; + } finally { + if (unitLoading) unitLoading.classList.add('hidden'); + } + }); + } + + // 2. Unit changed -> Load Topics + if (selectUnit) { + selectUnit.addEventListener('change', async () => { + hideFeedback(); + const uniteId = selectUnit.value; + + selectTopic.innerHTML = ''; + selectTopic.disabled = true; + if (btnSubmit) btnSubmit.disabled = true; + + if (!uniteId) return; + + if (topicLoading) topicLoading.classList.remove('hidden'); + + try { + const res = await fetch(`/api/private-lessons/topics?uniteId=${encodeURIComponent(uniteId)}`); + const data = await res.json(); + + if (data.success && data.topics && data.topics.length > 0) { + selectTopic.innerHTML = '' + + data.topics.map(t => ``).join(''); + selectTopic.disabled = false; + } else { + selectTopic.innerHTML = ''; + } + } catch (err) { + console.error('Error fetching topics:', err); + selectTopic.innerHTML = ''; + } finally { + if (topicLoading) topicLoading.classList.add('hidden'); + } + }); + } + + // 3. Topic changed -> Enable Submit + if (selectTopic) { + selectTopic.addEventListener('change', () => { + hideFeedback(); + const hasValue = Boolean(selectTopic.value); + if (btnSubmit) btnSubmit.disabled = !hasValue; + }); + } + + // 4. Form Submit + if (form) { + form.addEventListener('submit', async (e) => { + e.preventDefault(); + hideFeedback(); + + const ogrenciDonemId = document.getElementById('ogrenciDonemId')?.value || ''; + const okulId = document.getElementById('okulId')?.value || ''; + const sinifId = document.getElementById('sinifId')?.value || ''; + const dersId = selectCourse.value; + const uniteId = selectUnit.value; + const konuId = selectTopic.value; + + if (!dersId || !uniteId || !konuId) { + showFeedback('Lütfen ders, ünite ve konu seçimlerini tamamlayınız.', 'error'); + return; + } + + if (btnSubmit) { + btnSubmit.disabled = true; + btnSubmit.textContent = 'Gönderiliyor...'; + } + + try { + const res = await fetch('/api/private-lessons/request', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ogrenciDonemId, okulId, sinifId, dersId, uniteId, konuId }) + }); + + const data = await res.json(); + + if (data.success) { + showFeedback(data.message || 'Özel ders talebiniz başarıyla iletildi!', 'success'); + // Reset select elements + selectTopic.innerHTML = ''; + selectTopic.disabled = true; + selectUnit.innerHTML = ''; + selectUnit.disabled = true; + selectCourse.value = ''; + } else { + showFeedback(data.message || 'Talep iletilemedi. Lütfen tekrar deneyiniz.', 'error'); + } + } catch (err) { + console.error('Request error:', err); + showFeedback('Bağlantı hatası oluştu. Lütfen tekrar deneyiniz.', 'error'); + } finally { + if (btnSubmit) { + btnSubmit.textContent = 'Submit Request (Gönder)'; + } + } + }); + } + + // 5. Subject Filter Pills + subjectPills.forEach(pill => { + pill.addEventListener('click', () => { + const targetSubject = pill.dataset.subject; + + subjectPills.forEach(p => p.classList.remove('active')); + pill.classList.add('active'); + + lessonCards.forEach(card => { + const cardSubject = card.dataset.subject; + if (targetSubject === 'all' || cardSubject === targetSubject) { + card.style.display = ''; + } else { + card.style.display = 'none'; + } + }); + }); + }); + + // 6. Sync Lessons + if (btnSync) { + btnSync.addEventListener('click', async () => { + btnSync.disabled = true; + btnSync.textContent = 'Syncing...'; + + try { + const res = await fetch('/api/private-lessons/sync', { method: 'POST' }); + const data = await res.json(); + + if (data.success) { + showAlert(`Successfully refreshed ${data.count} private lesson records.`, 'success'); + setTimeout(() => { + window.location.reload(); + }, 800); + } else { + showAlert(data.error || 'Sync failed.', 'danger'); + } + } catch (err) { + showAlert('Network error while syncing private lessons.', 'danger'); + } finally { + btnSync.disabled = false; + btnSync.textContent = 'Sync Lessons'; + } + }); + } +}); diff --git a/src/server.ts b/src/server.ts index f51dc65..2bf9df9 100644 --- a/src/server.ts +++ b/src/server.ts @@ -444,17 +444,18 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => { // Selected station (default to İst-4 if not chosen yet) const selectedStation = syllabusStore?.selectedStation || 'İst-4'; + const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId); // 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 + // Compute filtered schedule for selected station & advisory teacher const rawSchedule = syllabusStore?.schedule || {}; const filteredSchedule: Record = {}; for (let d = 1; d <= 5; d++) { - filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation); + filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation, advisoryTeacher); } const currentStatus = SyllabusService.getCurrentLessonStatus( @@ -468,6 +469,7 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => { weekId: currentWeek.weekId, weekRange: currentWeek.weekRange, selectedStation, + advisoryTeacher, activeDay, filteredSchedule, currentStatus, @@ -486,16 +488,43 @@ app.post('/api/syllabus/station', requireAuth, (req: Request, res: Response) => db.setStudentStation(studentId, station || null); const syllabusStore = db.getSyllabus(studentId); + const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId); const rawSchedule = syllabusStore?.schedule || {}; const filteredSchedule: Record = {}; for (let d = 1; d <= 5; d++) { - filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null); + filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null, advisoryTeacher); } res.json({ success: true, selectedStation: station, + advisoryTeacher, + filteredSchedule + }); +}); + +/** + * POST /api/syllabus/advisory-teacher + * Update assigned advisory (Danışmanlık) teacher + */ +app.post('/api/syllabus/advisory-teacher', requireAuth, (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const { teacher } = req.body; + + db.setStudentAdvisoryTeacher(studentId, teacher || null); + const syllabusStore = db.getSyllabus(studentId); + const selectedStation = syllabusStore?.selectedStation || 'İst-4'; + + const rawSchedule = syllabusStore?.schedule || {}; + const filteredSchedule: Record = {}; + for (let d = 1; d <= 5; d++) { + filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation, teacher || null); + } + + res.json({ + success: true, + advisoryTeacher: teacher, filteredSchedule }); }); @@ -533,10 +562,11 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) const store = db.getSyllabus(studentId); const selectedStation = store?.selectedStation || 'İst-4'; + const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId); const filteredSchedule: Record = {}; for (let d = 1; d <= 5; d++) { - filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation); + filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation, advisoryTeacher); } res.json({ @@ -544,6 +574,7 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) weekId: currentWeek.weekId, weekRange: currentWeek.weekRange, lastSynced: store?.lastSynced, + advisoryTeacher, filteredSchedule }); } catch (err: any) { @@ -555,6 +586,192 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) } }); +// ---------------------------------------------------- +// Private Lessons (Özel Ders & İstek) Routes +// ---------------------------------------------------- + +/** + * GET /private-lessons + * Private lessons overview (application form + scheduled lessons) + */ +app.get('/private-lessons', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + let store = db.getPrivateLessons(studentId); + + // If not yet synced or formMeta missing, try auto-syncing + if (!store || !store.lessons || !store.formMeta) { + 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 [privateRes, formMeta] = await Promise.all([ + ScraperService.scrapePrivateLessons(cookies), + ScraperService.fetchPrivateLessonFormMeta(studentId) + ]); + + db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); + store = db.getPrivateLessons(studentId); + } catch (err: any) { + console.error('Error auto-syncing private lessons:', err.message); + } + } + } + + const allLessons = store?.lessons || []; + const upcomingLessons = allLessons.filter(l => l.isUpcoming); + const pastLessons = allLessons.filter(l => !l.isUpcoming); + + // Unique subjects for filter + const subjects = Array.from(new Set(allLessons.map(l => l.subject))).sort(); + + res.render('private-lessons', { + title: 'Private Lessons - BeKultur', + studentId, + studentName: req.session.studentName || store?.formMeta?.studentName || `Student ${studentId}`, + formMeta: store?.formMeta || null, + detectedAdvisor: store?.detectedAdvisor || db.getStudentAdvisoryTeacher(studentId) || null, + lastSynced: store?.lastSynced || null, + allLessons, + upcomingLessons, + pastLessons, + subjects + }); +}); + +/** + * Redirect shortcuts + */ +app.get('/ozelders', (req: Request, res: Response) => res.redirect('/private-lessons')); +app.get('/ozeldersistek', (req: Request, res: Response) => res.redirect('/private-lessons')); + +/** + * GET /api/private-lessons/units + * Dynamic units for course + */ +app.get('/api/private-lessons/units', requireAuth, async (req: Request, res: Response) => { + const dersId = req.query.dersId as string; + const sinifId = req.query.sinifId as string; + + if (!dersId || !sinifId) { + return res.status(400).json({ success: false, error: 'dersId and sinifId are required' }); + } + + try { + const units = await ScraperService.fetchUnits(dersId, sinifId); + res.json({ success: true, units }); + } catch (err: any) { + res.status(500).json({ success: false, error: err.message }); + } +}); + +/** + * GET /api/private-lessons/topics + * Dynamic topics for unit + */ +app.get('/api/private-lessons/topics', requireAuth, async (req: Request, res: Response) => { + const uniteId = req.query.uniteId as string; + + if (!uniteId) { + return res.status(400).json({ success: false, error: 'uniteId is required' }); + } + + try { + const topics = await ScraperService.fetchTopics(uniteId); + res.json({ success: true, topics }); + } catch (err: any) { + res.status(500).json({ success: false, error: err.message }); + } +}); + +/** + * POST /api/private-lessons/request + * Submit request to bilgi portal + */ +app.post('/api/private-lessons/request', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const { ogrenciDonemId, okulId, sinifId, dersId, uniteId, konuId } = req.body; + + if (!dersId || !uniteId || !konuId) { + return res.status(400).json({ success: false, message: 'Lütfen ders, ünite ve konu seçiniz.' }); + } + + try { + const result = await ScraperService.submitPrivateLessonRequest(studentId, { + ogrenciDonemId: ogrenciDonemId || '', + okulId: okulId || '', + sinifId: sinifId || '', + dersId, + uniteId, + konuId + }); + + res.json(result); + } catch (err: any) { + res.status(500).json({ success: false, message: err.message || 'Başvuru gönderilemedi.' }); + } +}); + +/** + * POST /api/private-lessons/sync + * Manually refresh private lessons and form meta + */ +app.post('/api/private-lessons/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 private lessons.' + }); + } + + const [privateRes, formMeta] = await Promise.all([ + ScraperService.scrapePrivateLessons(cookies), + ScraperService.fetchPrivateLessonFormMeta(studentId) + ]); + + db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor); + const store = db.getPrivateLessons(studentId); + + res.json({ + success: true, + count: privateRes.lessons.length, + detectedAdvisor: privateRes.detectedAdvisor, + lastSynced: store?.lastSynced, + lessons: privateRes.lessons + }); + } catch (err: any) { + console.error('API private-lessons sync error:', err.message); + res.status(500).json({ + success: false, + error: `Private lessons 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 056aa25..ac71ee1 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -1,6 +1,6 @@ import fs from 'fs'; import path from 'path'; -import { DatabaseSchema, StudentStore, Assignment } from '../types'; +import { DatabaseSchema, StudentStore, Assignment, PrivateLesson, PrivateLessonFormMeta, PrivateLessonsStore } from '../types'; const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json'); @@ -182,4 +182,49 @@ export class LocalDatabase { const student = this.cache.students[studentId]; return student?.syllabus || null; } + + public savePrivateLessons( + studentId: string, + lessons: PrivateLesson[], + formMeta?: PrivateLessonFormMeta, + detectedAdvisor?: string + ): void { + const student = this.getStudentStore(studentId); + const existing = student.privateLessons; + + student.privateLessons = { + lastSynced: new Date().toISOString(), + lessons, + formMeta: formMeta || existing?.formMeta, + detectedAdvisor: detectedAdvisor || existing?.detectedAdvisor + }; + + if (detectedAdvisor && !student.advisoryTeacher) { + student.advisoryTeacher = detectedAdvisor; + if (student.syllabus) { + student.syllabus.advisoryTeacher = detectedAdvisor; + } + } + + this.save(); + } + + public getPrivateLessons(studentId: string): PrivateLessonsStore | null { + const student = this.cache.students[studentId]; + return student?.privateLessons || null; + } + + public setStudentAdvisoryTeacher(studentId: string, teacher: string | null): void { + const student = this.getStudentStore(studentId); + student.advisoryTeacher = teacher; + if (student.syllabus) { + student.syllabus.advisoryTeacher = teacher; + } + this.save(); + } + + public getStudentAdvisoryTeacher(studentId: string): string | null { + const student = this.cache.students[studentId]; + return student?.advisoryTeacher || student?.privateLessons?.detectedAdvisor || null; + } } diff --git a/src/services/scraper.ts b/src/services/scraper.ts index 49c9cf7..4f6290b 100644 --- a/src/services/scraper.ts +++ b/src/services/scraper.ts @@ -1,11 +1,12 @@ import axios from 'axios'; import * as cheerio from 'cheerio'; import crypto from 'crypto'; -import { Assignment, Lesson } from '../types'; +import { Assignment, Lesson, PrivateLesson, PrivateLessonFormMeta } from '../types'; import { InsightService } from './insight'; import { DAY_NAMES } from './syllabus'; const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com'; +const BILGI_BASE_URL = 'https://bilgi.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'; export interface LoginResult { @@ -391,4 +392,273 @@ export class ScraperService { return weeklySchedule; } + + /** + * Scrape scheduled private lessons (Özel Ders) and detect assigned advisor teacher + */ + public static async scrapePrivateLessons( + cookies: string + ): Promise<{ lessons: PrivateLesson[]; detectedAdvisor?: string }> { + const lessons: PrivateLesson[] = []; + const seenLessonKeys = new Set(); + let detectedAdvisor: string | undefined; + + const client = axios.create({ + baseURL: BASE_URL, + headers: { + 'User-Agent': USER_AGENT, + 'Cookie': cookies + }, + validateStatus: () => true + }); + + let currentPage = 1; + let maxPages = 1; + const visitedPages = new Set(); + + while (currentPage <= maxPages && !visitedPages.has(currentPage)) { + visitedPages.add(currentPage); + const url = currentPage === 1 ? '/ozelders' : `/OzelDers?sayfa=${currentPage}`; + + try { + const res = await client.get(url); + if (res.status !== 200 || !res.data) break; + + const $ = cheerio.load(res.data); + + // Find pagination links + $('a[href*="sayfa="]').each((_, a) => { + const href = $(a).attr('href') || ''; + const match = href.match(/sayfa=(\d+)/); + if (match) { + const p = parseInt(match[1], 10); + if (p > maxPages) maxPages = p; + } + }); + + // Each private lesson is in .kltr-card inside .col-md-8 + $('.col-md-8 .kltr-card').each((_, cardEl) => { + const card = $(cardEl); + const subject = card.find('h5.my-1').text().trim(); + const pElements = card.find('p.my-1'); + const teacherName = pElements.eq(0).text().trim(); + const dateStr = pElements.eq(1).text().trim(); // e.g. "26.10.2026" + const teacherPhoto = card.find('img.profil-resmi').attr('src') || ''; + + if (!subject || !teacherName || !dateStr) return; + + const key = `${subject}|${teacherName}|${dateStr}`; + if (seenLessonKeys.has(key)) return; + seenLessonKeys.add(key); + + const parsedObj = InsightService.parsePortalDate(dateStr); + const parsedDate = InsightService.toISODate(parsedObj) || ''; + + // Check if upcoming: has border-success class OR date is in future/today + const hasSuccessBorder = card.hasClass('border-success') || (card.attr('class') || '').includes('border-success'); + const isDateUpcoming = parsedObj ? parsedObj.getTime() >= new Date().setHours(0, 0, 0, 0) : false; + const isUpcoming = hasSuccessBorder || isDateUpcoming; + + const id = crypto.createHash('sha256').update(key).digest('hex').slice(0, 16); + + lessons.push({ + id, + subject, + teacherName, + teacherPhoto, + date: dateStr, + parsedDate, + isUpcoming + }); + + // Check if Danışmanlık to detect assigned advisor + if (/dan[ıi]şmanl[ıi]k/i.test(subject) && !detectedAdvisor) { + detectedAdvisor = teacherName; + } + }); + + currentPage++; + } catch (err: any) { + console.error(`Error scraping private lessons page ${currentPage}:`, err.message); + break; + } + } + + return { lessons, detectedAdvisor }; + } + + /** + * Fetch form metadata and course options for Private Lesson Request from bilgi portal + */ + public static async fetchPrivateLessonFormMeta(studentId: string): Promise { + try { + const client = axios.create({ + headers: { 'User-Agent': USER_AGENT }, + validateStatus: () => true + }); + + const res = await client.get(`${BILGI_BASE_URL}/ozeldersistek?Id=${encodeURIComponent(studentId)}`); + if (res.status !== 200 || !res.data) return null; + + const $ = cheerio.load(res.data); + const studentName = $('.alert-info h5').text().trim(); + const pTags = $('.alert-info p'); + const schoolName = pTags.eq(1).text().trim(); + const className = pTags.eq(2).text().trim(); + const photoUrl = $('.alert-info img.profil-resmi').attr('src') || undefined; + + const ogrenciDonemId = ($('input#OgrenciDonemId').val() as string) || ''; + const okulId = ($('input#OkulId').val() as string) || ''; + const sinifId = ($('input#SinifId').val() as string) || ''; + + const courses: Array<{ id: string; name: string }> = []; + $('select#DersId option').each((_, opt) => { + const val = $(opt).attr('value'); + const text = $(opt).text().trim(); + if (val) { + courses.push({ id: val, name: text }); + } + }); + + return { + studentName, + schoolName, + className, + photoUrl, + ogrenciDonemId, + okulId, + sinifId, + courses + }; + } catch (err: any) { + console.error('Failed to fetch private lesson form meta:', err.message); + return null; + } + } + + /** + * Fetch units for a course and class from bilgi portal over HTTPS + */ + public static async fetchUnits(dersId: string, sinifId: string): Promise> { + try { + const res = await axios.post( + `${BILGI_BASE_URL}/ortak/dersuniteler`, + new URLSearchParams({ id: dersId, sinifId }).toString(), + { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest', + 'User-Agent': USER_AGENT + } + } + ); + + const $ = cheerio.load(res.data || ''); + const units: Array<{ id: string; name: string }> = []; + $('option').each((_, opt) => { + const val = $(opt).attr('value'); + const text = $(opt).text().trim(); + if (val) { + units.push({ id: val, name: text }); + } + }); + return units; + } catch (err: any) { + console.error('Failed to fetch units:', err.message); + return []; + } + } + + /** + * Fetch topics for a unit from bilgi portal over HTTPS + */ + public static async fetchTopics(uniteId: string): Promise> { + try { + const res = await axios.post( + `${BILGI_BASE_URL}/ortak/unitekonular`, + new URLSearchParams({ id: uniteId }).toString(), + { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest', + 'User-Agent': USER_AGENT + } + } + ); + + const $ = cheerio.load(res.data || ''); + const topics: Array<{ id: string; name: string }> = []; + $('option').each((_, opt) => { + const val = $(opt).attr('value'); + const text = $(opt).text().trim(); + if (val) { + topics.push({ id: val, name: text }); + } + }); + return topics; + } catch (err: any) { + console.error('Failed to fetch topics:', err.message); + return []; + } + } + + /** + * Submit Private Lesson Request to bilgi portal + */ + public static async submitPrivateLessonRequest( + studentId: string, + payload: { + ogrenciDonemId: string; + okulId: string; + sinifId: string; + dersId: string; + uniteId: string; + konuId: string; + } + ): Promise<{ success: boolean; message: string }> { + try { + const formData = new URLSearchParams(); + formData.append('OgrenciDonemId', payload.ogrenciDonemId); + formData.append('OkulId', payload.okulId); + formData.append('SinifId', payload.sinifId); + formData.append('DersId', payload.dersId); + formData.append('UniteId', payload.uniteId); + formData.append('KonuId', payload.konuId); + + const res = await axios.post( + `${BILGI_BASE_URL}/ozeldersistek?Id=${encodeURIComponent(studentId)}`, + formData.toString(), + { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': USER_AGENT + }, + maxRedirects: 5, + validateStatus: () => true + } + ); + + if (res.status >= 200 && res.status < 400) { + const $ = cheerio.load(res.data || ''); + const alertDanger = $('.alert-danger, .text-danger').text().trim(); + + if (alertDanger && !alertDanger.includes('ÖĞRENCİ ÖZEL DERS BAŞVURU')) { + return { success: false, message: alertDanger }; + } + + return { + success: true, + message: 'Talebiniz başarıyla iletildi.' + }; + } + + return { + success: false, + message: `Portal returned status code ${res.status}` + }; + } catch (err: any) { + console.error('Failed to submit private lesson request:', err.message); + return { success: false, message: err.message || 'Submission failed' }; + } + } } diff --git a/src/services/syllabus.ts b/src/services/syllabus.ts index d8b4eb1..cd18583 100644 --- a/src/services/syllabus.ts +++ b/src/services/syllabus.ts @@ -1,4 +1,5 @@ import { Lesson } from '../types'; +import { InsightService } from './insight'; export const DAY_NAMES: Record = { 1: 'Pazartesi', @@ -66,8 +67,13 @@ export class SyllabusService { /** * Filter lessons for a specific station (or show all stations without portal duplicate garbage) + * and filter advisory (Danışmanlık) lessons if an assigned advisory teacher is provided. */ - public static filterLessonsForStation(rawLessons: Lesson[], selectedStation: string | null): Lesson[] { + public static filterLessonsForStation( + rawLessons: Lesson[], + selectedStation: string | null, + advisoryTeacher?: string | null + ): Lesson[] { if (!rawLessons || !rawLessons.length) return []; const normTarget = this.normalizeStation(selectedStation); @@ -112,9 +118,37 @@ export class SyllabusService { } } } else { - // Whole-class lesson (no stations): deduplicate if portal printed multiple copies + // Whole-class / unstationed lessons const seenKeys = new Set(); - for (const cl of periodGroup) { + + // Check if this period contains advisory (Danışmanlık) lessons + const advisoryLessons = periodGroup.filter(l => /dan[ıi]şmanl[ıi]k/i.test(l.subject)); + const nonAdvisoryLessons = periodGroup.filter(l => !/dan[ıi]şmanl[ıi]k/i.test(l.subject)); + + if (advisoryLessons.length > 1 && advisoryTeacher && advisoryTeacher.trim().length > 0) { + const normAdvisor = InsightService.normalizeTurkish(advisoryTeacher.trim()).toLowerCase(); + const advisorMatch = advisoryLessons.find(l => { + const normTeacher = InsightService.normalizeTurkish(l.teacher).toLowerCase(); + return normTeacher.includes(normAdvisor) || normAdvisor.includes(normTeacher); + }); + if (advisorMatch) { + result.push(advisorMatch); + } else { + // If student's advisor not matched, keep first unique advisory card + result.push(advisoryLessons[0]); + } + } else { + for (const al of advisoryLessons) { + const key = `${al.periodNumber}|${al.subject}|${al.teacher}|${al.time}`; + if (!seenKeys.has(key)) { + seenKeys.add(key); + result.push(al); + } + } + } + + // Add non-advisory lessons for this period (deduplicating identical cards) + for (const cl of nonAdvisoryLessons) { const key = `${cl.periodNumber}|${cl.subject}|${cl.teacher}|${cl.time}`; if (!seenKeys.has(key)) { seenKeys.add(key); diff --git a/src/types/index.ts b/src/types/index.ts index 954f89e..b6b4f29 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -66,10 +66,42 @@ 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 + advisoryTeacher?: string | null; // e.g. "CAN TÜRKOĞLU" lastSynced: string | null; schedule: Record; // day (1..5) -> raw lessons } +// ---------------------------------------------------- +// Private Lessons (Özel Ders & İstek) Types +// ---------------------------------------------------- +export interface PrivateLesson { + id: string; // deterministic ID or hash + subject: string; // e.g. "Coğrafya", "Danışmanlık" + teacherName: string; // e.g. "SEVDA KILIÇOĞLU" + teacherPhoto: string; // photo URL + date: string; // e.g. "26.10.2026" + parsedDate: string; // e.g. "2026-10-26" + isUpcoming: boolean; // true if border-success / active upcoming +} + +export interface PrivateLessonFormMeta { + studentName: string; + schoolName: string; + className: string; + photoUrl?: string; + ogrenciDonemId: string; + okulId: string; + sinifId: string; + courses: Array<{ id: string; name: string }>; +} + +export interface PrivateLessonsStore { + lastSynced: string; + lessons: PrivateLesson[]; + formMeta?: PrivateLessonFormMeta; + detectedAdvisor?: string; +} + export interface StudentStore { studentId: string; lastSynced: string | null; @@ -79,6 +111,8 @@ export interface StudentStore { }; assignments: Record; syllabus?: SyllabusStore; + advisoryTeacher?: string | null; + privateLessons?: PrivateLessonsStore; } export interface DatabaseSchema { diff --git a/test/run-tests.ts b/test/run-tests.ts index aac0e30..43c61a6 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -368,6 +368,68 @@ async function runAllTests() { 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', () => { + // 5 advisory variations for period 2 + 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ı' } + ]; + + // Filter with CAN TÜRKOĞLU + 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'); + + // Filter with ÜLKÜ ESEN + 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'); + }); + // 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 341c453..d69cf74 100644 --- a/views/partials/header.ejs +++ b/views/partials/header.ejs @@ -17,6 +17,7 @@ <% } %> diff --git a/views/private-lessons.ejs b/views/private-lessons.ejs new file mode 100644 index 0000000..257440a --- /dev/null +++ b/views/private-lessons.ejs @@ -0,0 +1,206 @@ +<%- include('partials/header') %> + +
+ +
+
+

Private Lessons

+

+ Özel Ders & Başvuru + <% if (lastSynced) { %> + • Synced: <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + <% } %> +

+
+ +
+ +
+
+ + + + + <% if (formMeta) { %> +
+
+ <% if (formMeta.photoUrl) { %> + <%= formMeta.studentName %> + <% } %> +
+

<%= formMeta.studentName %>

+

<%= formMeta.schoolName %> • <%= formMeta.className %>

+ <% if (detectedAdvisor) { %> +
+ Advisor: + <%= detectedAdvisor %> +
+ <% } %> +
+
+
+ ℹ + Başkası adına özel ders almayınız, seçtiğiniz öğretmen onayladığı takdirde özel derse alınacaksınız. +
+
+ <% } %> + + +
+
+

New Lesson Request (Özel Ders İstek)

+ Online Başvuru +
+ +
+ <% if (formMeta) { %> + + + + <% } else { %> + + + + <% } %> + +
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+
+ +
+ +
+ + +
+
+ + +
+
+
+

My Lessons (Özel Derslerim)

+ <%= allLessons.length %> +
+ + + <% if (subjects.length > 0) { %> +
+ + <% subjects.forEach(function(sub) { %> + + <% }); %> +
+ <% } %> +
+ + + <% if (upcomingLessons.length > 0) { %> +
+
+ Upcoming / Approved Lessons + <%= upcomingLessons.length %> Active +
+ +
+ <% upcomingLessons.forEach(function(item) { %> +
+
+ Upcoming + <%= item.date %> +
+
+ <% if (item.teacherPhoto) { %> + <%= item.teacherName %> + <% } else { %> +
<%= item.teacherName ? item.teacherName[0] : 'Ö' %>
+ <% } %> +
+

<%= item.subject %>

+

<%= item.teacherName %>

+
+
+
+ <% }); %> +
+
+ <% } %> + + +
+
+ Lesson History + <%= pastLessons.length %> Past +
+ + <% if (pastLessons.length === 0 && upcomingLessons.length === 0) { %> +
+

No private lessons recorded yet. Submit a request above or click Sync Lessons to fetch from the portal.

+
+ <% } else { %> +
+ <% pastLessons.forEach(function(item) { %> +
+
+ Completed + <%= item.date %> +
+
+ <% if (item.teacherPhoto) { %> + <%= item.teacherName %> + <% } else { %> +
<%= item.teacherName ? item.teacherName[0] : 'Ö' %>
+ <% } %> +
+

<%= item.subject %>

+

<%= item.teacherName %>

+
+
+
+ <% }); %> +
+ <% } %> +
+
+
+ + + +<%- include('partials/footer') %> diff --git a/views/syllabus.ejs b/views/syllabus.ejs index f2eea8c..201a557 100644 --- a/views/syllabus.ejs +++ b/views/syllabus.ejs @@ -49,6 +49,16 @@ + <% if (typeof advisoryTeacher !== 'undefined' && advisoryTeacher) { %> +
+ Advisor: +
+ <%= advisoryTeacher %> + Danışmanlık +
+
+ <% } %> +
View: