From f138403918ad0e856bd7cb6c0f48a5e84263f4e5 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Wed, 21 Oct 2026 20:03:39 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20implement=20modern=20S=C4=B1nav=20Rapor?= =?UTF-8?q?=20dashboard=20with=20dual-metric=20delta=20tracking=20and=20in?= =?UTF-8?q?line=20mistake=20review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/css/style.css | 707 ++++++++++++++++++++++++++++++++++++++ public/js/exams.js | 500 +++++++++++++++++++++++++++ src/server.ts | 254 ++++++++++++++ src/services/db.ts | 60 +++- src/services/exam.ts | 253 ++++++++++++++ src/services/scraper.ts | 375 +++++++++++++++++++- src/types/index.ts | 93 +++++ test/run-tests.ts | 214 +++++++++++- views/exams.ejs | 384 +++++++++++++++++++++ views/partials/header.ejs | 1 + 10 files changed, 2838 insertions(+), 3 deletions(-) create mode 100644 public/js/exams.js create mode 100644 src/services/exam.ts create mode 100644 views/exams.ejs diff --git a/public/css/style.css b/public/css/style.css index 3593c15..c863af9 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1447,3 +1447,710 @@ code { color: var(--text-muted); font-size: 0.875rem; } + +/* ==================================================== */ +/* Exam Reports (Sınav Rapor) Styling */ +/* ==================================================== */ + +.exam-filter-row { + margin-bottom: 14px; +} + +.filter-pills { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.filter-pill { + background: var(--bg-card); + border: 1px solid var(--border); + color: var(--text-muted); + padding: 5px 12px; + border-radius: var(--radius); + font-size: 0.825rem; + font-weight: 500; + cursor: pointer; + transition: all 0.15s ease; +} + +.filter-pill:hover { + background: #f8fafc; + color: var(--text-main); +} + +.filter-pill.active { + background: var(--primary); + border-color: var(--primary); + color: white; + font-weight: 600; +} + +/* Exam Cards Strip */ +.exam-cards-strip { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); + gap: 12px; + margin-bottom: 24px; +} + +.exam-pill-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 14px; + cursor: pointer; + transition: all 0.15s ease; + display: flex; + flex-direction: column; + gap: 8px; +} + +.exam-pill-card:hover { + border-color: #cbd5e1; + transform: translateY(-1px); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03); +} + +.exam-pill-card.active { + border-color: var(--primary); + box-shadow: 0 0 0 1.5px var(--primary); + background: #fdfdfe; +} + +.exam-pill-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; +} + +.exam-type-badge { + font-size: 0.7rem; + font-weight: 700; + padding: 2px 6px; + border-radius: 4px; + text-transform: uppercase; +} + +.exam-type-tyt { + background: #e0f2fe; + color: #0369a1; +} + +.exam-type-ayt { + background: #ede9fe; + color: #6d28d9; +} + +.exam-type-other { + background: #f1f5f9; + color: #475569; +} + +.exam-pill-name { + font-size: 0.85rem; + font-weight: 600; + color: var(--text-main); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + flex: 1; + text-align: right; +} + +.exam-pill-metrics { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 8px; +} + +.exam-pill-net { + font-size: 1.05rem; + color: var(--text-main); + display: flex; + align-items: baseline; + gap: 4px; +} + +.net-unit { + font-size: 0.75rem; + color: var(--text-muted); + font-weight: 400; +} + +.exam-pill-rank { + display: flex; + align-items: center; + gap: 4px; +} + +.rank-badge { + font-size: 0.8rem; + font-weight: 600; + color: var(--text-muted); +} + +.delta-badge { + font-size: 0.7rem; + font-weight: 700; + padding: 1px 5px; + border-radius: 4px; + display: inline-flex; + align-items: center; +} + +.delta-up { + background: #ecfdf5; + color: #047857; +} + +.delta-down { + background: #fef2f2; + color: #b91c1c; +} + +.delta-rank-badge { + font-size: 0.7rem; + font-weight: 700; + padding: 1px 4px; + border-radius: 4px; +} + +.rank-up { + background: #eff6ff; + color: #1d4ed8; +} + +.rank-down { + background: #fff1f2; + color: #be123c; +} + +.exam-pill-rating { + margin-top: 2px; +} + +/* Exam Detail Card */ +.exam-detail-card { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 20px 24px; + margin-bottom: 24px; +} + +.exam-detail-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 16px; + margin-bottom: 20px; + flex-wrap: wrap; +} + +.detail-title-line { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin-bottom: 8px; +} + +.exam-title-text { + font-size: 1.25rem; + font-weight: 700; + margin: 0; + color: var(--text-main); +} + +.exam-type-tag { + font-size: 0.75rem; + font-weight: 700; + padding: 2px 8px; + border-radius: 4px; + text-transform: uppercase; +} + +.detail-badge-line { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.detail-action-group { + display: flex; + gap: 8px; + align-items: center; +} + +/* Exam Sub-Tabs */ +.exam-subtabs { + display: flex; + gap: 8px; + border-bottom: 1px solid var(--border); + margin-bottom: 16px; +} + +.subtab-btn { + background: transparent; + border: none; + border-bottom: 2px solid transparent; + color: var(--text-muted); + padding: 8px 14px; + font-size: 0.875rem; + font-weight: 500; + cursor: pointer; + transition: all 0.15s ease; + margin-bottom: -1px; +} + +.subtab-btn:hover { + color: var(--text-main); +} + +.subtab-btn.active { + color: var(--primary); + border-bottom-color: var(--primary); + font-weight: 600; +} + +/* Exam Score Table */ +.exam-score-table { + width: 100%; + border-collapse: collapse; + font-size: 0.875rem; +} + +.exam-score-table th, +.exam-score-table td { + padding: 10px 12px; + border-bottom: 1px solid var(--border); +} + +.exam-score-table th { + background: #f8fafc; + color: var(--text-muted); + font-size: 0.75rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.03em; +} + +.exam-score-table tbody tr:hover { + background: #fcfdfe; +} + +.table-total-row { + background: #f8fafc; + border-top: 2px solid var(--border); + border-bottom: 2px solid var(--border); +} + +.total-net-text { + font-size: 1rem; + color: var(--primary); +} + +.badge-btn { + border: none; + border-radius: 4px; + font-weight: 600; + padding: 2px 8px; + font-size: 0.8rem; + cursor: pointer; + transition: transform 0.1s ease, filter 0.1s ease; +} + +.badge-btn:hover { + transform: scale(1.08); + filter: brightness(0.95); +} + +.score-progress-wrapper { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; +} + +.score-progress-bar { + width: 75px; + height: 6px; + background: #e2e8f0; + border-radius: 9999px; + overflow: hidden; +} + +.score-progress-fill { + height: 100%; + border-radius: 9999px; +} + +.fill-high { + background: #10b981; +} + +.fill-mid { + background: #f59e0b; +} + +.fill-low { + background: #ef4444; +} + +.score-progress-pct { + font-size: 0.75rem; + color: var(--text-muted); + min-width: 32px; + text-align: right; +} + +/* Topic Weakness View */ +.weakness-loading-state, +.modal-loading-state { + padding: 30px; + text-align: center; + color: var(--text-muted); + font-size: 0.875rem; +} + +.weakness-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 12px; + padding-top: 6px; +} + +.weakness-card { + background: white; + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 6px; +} + +.weakness-card-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; +} + +.weakness-subject { + font-size: 0.75rem; + font-weight: 700; + color: var(--primary); + text-transform: uppercase; +} + +.weakness-topic { + font-size: 0.85rem; + font-weight: 600; + color: var(--text-main); +} + +.weakness-stats { + display: flex; + gap: 12px; + font-size: 0.75rem; + color: var(--text-muted); +} + +/* ==================================================== */ +/* Mistake Review Modal */ +/* ==================================================== */ + +.modal-overlay { + position: fixed; + inset: 0; + background: rgba(15, 23, 42, 0.55); + display: flex; + align-items: center; + justify-content: center; + z-index: 1050; + padding: 16px; + backdrop-filter: blur(2px); +} + +.modal-dialog.modal-xl { + background: white; + border-radius: 12px; + width: 100%; + max-width: 980px; + max-height: 90vh; + display: flex; + flex-direction: column; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + overflow: hidden; +} + +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 14px 20px; + border-bottom: 1px solid var(--border); + background: white; +} + +.modal-title-group { + display: flex; + flex-direction: column; + gap: 2px; +} + +.modal-title { + font-size: 1.15rem; + font-weight: 700; + margin: 0; + color: var(--text-main); +} + +.modal-subtitle { + font-size: 0.75rem; + color: var(--text-muted); +} + +.modal-close-btn { + background: transparent; + border: none; + font-size: 1.5rem; + line-height: 1; + color: var(--text-muted); + cursor: pointer; + padding: 4px 8px; + border-radius: 4px; +} + +.modal-close-btn:hover { + color: var(--text-main); + background: #f1f5f9; +} + +.modal-filter-bar { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 20px; + background: #f8fafc; + border-bottom: 1px solid var(--border); + gap: 12px; + flex-wrap: wrap; +} + +.modal-lesson-pills { + display: flex; + gap: 6px; + overflow-x: auto; + max-width: 65%; + padding-bottom: 2px; +} + +.modal-lesson-btn { + background: white; + border: 1px solid var(--border); + color: var(--text-muted); + padding: 4px 10px; + border-radius: var(--radius); + font-size: 0.775rem; + font-weight: 500; + white-space: nowrap; + cursor: pointer; + transition: all 0.15s ease; +} + +.modal-lesson-btn:hover { + background: #f1f5f9; + color: var(--text-main); +} + +.modal-lesson-btn.active { + background: var(--primary); + border-color: var(--primary); + color: white; + font-weight: 600; +} + +.modal-type-toggles { + display: flex; + gap: 4px; +} + +.modal-type-btn { + background: white; + border: 1px solid var(--border); + color: var(--text-muted); + padding: 4px 8px; + border-radius: var(--radius); + font-size: 0.75rem; + cursor: pointer; +} + +.modal-type-btn.active { + background: #0f172a; + color: white; + border-color: #0f172a; + font-weight: 600; +} + +.modal-body { + padding: 20px; + overflow-y: auto; + flex: 1; + background: #f8fafc; +} + +.questions-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(420px, 1fr)); + gap: 16px; +} + +.question-card { + background: white; + border: 1px solid var(--border); + border-radius: 8px; + padding: 14px; + display: flex; + flex-direction: column; + gap: 10px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); +} + +.question-card-header { + display: flex; + justify-content: space-between; + align-items: center; +} + +.question-no-badge { + font-size: 0.8rem; + font-weight: 700; + color: var(--text-main); +} + +.question-subject-badge { + font-size: 0.75rem; + color: var(--text-muted); + font-weight: 500; +} + +.question-card-answers { + display: flex; + align-items: center; + gap: 10px; + font-size: 0.8rem; +} + +.answer-pill { + padding: 2px 8px; + border-radius: 4px; + font-weight: 600; + display: inline-flex; + align-items: center; + gap: 4px; +} + +.answer-correct { + background: #ecfdf5; + color: #047857; + border: 1px solid #a7f3d0; +} + +.answer-student-wrong { + background: #fef2f2; + color: #b91c1c; + border: 1px solid #fecaca; +} + +.answer-student-empty { + background: #f1f5f9; + color: #475569; + border: 1px solid #e2e8f0; +} + +.question-img-wrapper { + background: #fafafa; + border: 1px solid #f1f5f9; + border-radius: 6px; + padding: 8px; + text-align: center; + cursor: zoom-in; + overflow: hidden; + display: flex; + justify-content: center; +} + +.question-img { + max-width: 100%; + max-height: 480px; + height: auto; + object-fit: contain; + transition: transform 0.15s ease; +} + +.question-img-wrapper:hover .question-img { + transform: scale(1.015); +} + +/* Lightbox Overlay */ +.lightbox-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.85); + display: flex; + align-items: center; + justify-content: center; + z-index: 1100; + padding: 20px; + cursor: zoom-out; +} + +.lightbox-content { + position: relative; + max-width: 95vw; + max-height: 95vh; +} + +.lightbox-content img { + max-width: 95vw; + max-height: 90vh; + object-fit: contain; + border-radius: 6px; + background: white; + padding: 6px; +} + +.lightbox-close-btn { + position: absolute; + top: -40px; + right: 0; + background: transparent; + border: none; + color: white; + font-size: 2rem; + cursor: pointer; + line-height: 1; +} + +@media (max-width: 768px) { + .exam-cards-strip { + grid-template-columns: 1fr; + } + .questions-grid { + grid-template-columns: 1fr; + } + .modal-filter-bar { + flex-direction: column; + align-items: stretch; + } + .modal-lesson-pills { + max-width: 100%; + } +} + diff --git a/public/js/exams.js b/public/js/exams.js new file mode 100644 index 0000000..9049e92 --- /dev/null +++ b/public/js/exams.js @@ -0,0 +1,500 @@ +document.addEventListener('DOMContentLoaded', () => { + // ---------------------------------------------------- + // Elements + // ---------------------------------------------------- + const categoryFilterPills = document.getElementById('categoryFilterPills'); + const examCardsStrip = document.getElementById('examCardsStrip'); + const btnSyncExams = document.getElementById('btnSyncExams'); + const btnEmptySync = document.getElementById('btnEmptySync'); + const examsAlert = document.getElementById('examsAlert'); + + // Subtabs + const subtabBreakdown = document.getElementById('subtabBreakdown'); + const subtabWeakness = document.getElementById('subtabWeakness'); + const breakdownView = document.getElementById('breakdownView'); + const weaknessView = document.getElementById('weaknessView'); + const weaknessContainer = document.getElementById('weaknessContainer'); + const weaknessLoading = document.getElementById('weaknessLoading'); + + // Mistake Review Modal + const btnReviewMistakes = document.getElementById('btnReviewMistakes'); + const mistakeModal = document.getElementById('mistakeModal'); + const btnMistakeModalClose = document.getElementById('btnMistakeModalClose'); + const modalLessonPills = document.getElementById('modalLessonPills'); + const modalTypeBtns = document.querySelectorAll('.modal-type-btn'); + const questionsGrid = document.getElementById('questionsGrid'); + const mistakeLoading = document.getElementById('mistakeLoading'); + const mistakeModalTitle = document.getElementById('mistakeModalTitle'); + const mistakeModalSubtitle = document.getElementById('mistakeModalSubtitle'); + + // Lightbox + const imageLightbox = document.getElementById('imageLightbox'); + const lightboxImg = document.getElementById('lightboxImg'); + const btnLightboxClose = document.getElementById('btnLightboxClose'); + + // State + let currentExamId = btnReviewMistakes ? btnReviewMistakes.getAttribute('data-exam-id') : null; + let cachedQuestions = null; // raw fetched questions by subject + let activeLessonFilter = 'ALL'; + let activeTypeFilter = 'all'; // 'all' | 'wrong' | 'empty' + let cachedWeaknesses = null; + + // ---------------------------------------------------- + // Helper: Show Alert + // ---------------------------------------------------- + function showAlert(msg, type = 'info') { + if (!examsAlert) return; + examsAlert.className = `alert alert-${type}`; + examsAlert.textContent = msg; + examsAlert.classList.remove('hidden'); + setTimeout(() => { + examsAlert.classList.add('hidden'); + }, 4000); + } + + // ---------------------------------------------------- + // Category Filter (All / TYT / AYT) + // ---------------------------------------------------- + if (categoryFilterPills && examCardsStrip) { + categoryFilterPills.addEventListener('click', (e) => { + const btn = e.target.closest('.filter-pill'); + if (!btn) return; + + categoryFilterPills.querySelectorAll('.filter-pill').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + + const category = btn.getAttribute('data-category'); + const cards = examCardsStrip.querySelectorAll('.exam-pill-card'); + + cards.forEach(card => { + const cardCat = card.getAttribute('data-category'); + if (category === 'ALL' || cardCat === category) { + card.style.display = ''; + } else { + card.style.display = 'none'; + } + }); + }); + } + + // ---------------------------------------------------- + // Exam Card Switching + // ---------------------------------------------------- + if (examCardsStrip) { + examCardsStrip.addEventListener('click', (e) => { + const card = e.target.closest('.exam-pill-card'); + if (!card) return; + + const examId = card.getAttribute('data-id'); + if (examId && examId !== currentExamId) { + window.location.href = `/exams?id=${encodeURIComponent(examId)}`; + } + }); + } + + // ---------------------------------------------------- + // Sync Exams Action + // ---------------------------------------------------- + async function handleSync() { + const triggerBtn = btnSyncExams || btnEmptySync; + if (triggerBtn) { + triggerBtn.disabled = true; + triggerBtn.textContent = 'Syncing...'; + } + + try { + const res = await fetch('/api/exams/sync', { + method: 'POST', + headers: { 'Content-Type': 'application/json' } + }); + const data = await res.json(); + + if (data.success) { + window.location.reload(); + } else { + showAlert(data.error || 'Failed to sync exams', 'danger'); + if (triggerBtn) { + triggerBtn.disabled = false; + triggerBtn.textContent = 'Sync Exams'; + } + } + } catch (err) { + showAlert('Connection error while syncing exams.', 'danger'); + if (triggerBtn) { + triggerBtn.disabled = false; + triggerBtn.textContent = 'Sync Exams'; + } + } + } + + if (btnSyncExams) btnSyncExams.addEventListener('click', handleSync); + if (btnEmptySync) btnEmptySync.addEventListener('click', handleSync); + + // ---------------------------------------------------- + // Subtabs Toggle (Breakdown vs Weaknesses) + // ---------------------------------------------------- + if (subtabBreakdown && subtabWeakness) { + subtabBreakdown.addEventListener('click', () => { + subtabBreakdown.classList.add('active'); + subtabWeakness.classList.remove('active'); + breakdownView.classList.remove('hidden'); + weaknessView.classList.add('hidden'); + }); + + subtabWeakness.addEventListener('click', async () => { + subtabWeakness.classList.add('active'); + subtabBreakdown.classList.remove('active'); + weaknessView.classList.remove('hidden'); + breakdownView.classList.add('hidden'); + + if (!cachedWeaknesses && currentExamId) { + await loadTopicWeaknesses(currentExamId); + } + }); + } + + async function loadTopicWeaknesses(examId) { + weaknessLoading.classList.remove('hidden'); + weaknessContainer.innerHTML = ''; + + try { + const res = await fetch(`/api/exams/${encodeURIComponent(examId)}/weaknesses`); + const data = await res.json(); + weaknessLoading.classList.add('hidden'); + + if (data.success && data.weaknesses && data.weaknesses.length > 0) { + cachedWeaknesses = data.weaknesses; + renderTopicWeaknesses(data.weaknesses); + } else { + weaknessContainer.innerHTML = ` +
+

Bu sınav için henüz zayıf konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.

+
+ `; + } + } catch (err) { + weaknessLoading.classList.add('hidden'); + weaknessContainer.innerHTML = ` +
Zayıf konu raporu yüklenirken bir hata oluştu.
+ `; + } + } + + function renderTopicWeaknesses(weaknesses) { + // Sort weaknesses by most wrong answers, then lowest success rate + const sorted = [...weaknesses].sort((a, b) => { + if (b.wrongCount !== a.wrongCount) return b.wrongCount - a.wrongCount; + return a.successRate - b.successRate; + }); + + let html = '
'; + sorted.forEach(item => { + const fillClass = item.successRate >= 70 ? 'fill-high' : item.successRate >= 40 ? 'fill-mid' : 'fill-low'; + html += ` +
+
+ ${escapeHtml(item.subjectName)} + ${item.successRate}% +
+
${escapeHtml(item.topicName)}
+
+
+
+
+ Toplam: ${item.totalCount} + Doğru: ${item.correctCount} + Yanlış: ${item.wrongCount} + Boş: ${item.emptyCount} +
+
+ `; + }); + html += '
'; + weaknessContainer.innerHTML = html; + } + + // ---------------------------------------------------- + // Inline Mistake Review Modal + // ---------------------------------------------------- + function openReviewModal(targetSubjectName = null) { + if (!mistakeModal || !currentExamId) return; + mistakeModal.classList.remove('hidden'); + document.body.style.overflow = 'hidden'; + + if (!cachedQuestions) { + loadExamQuestions(targetSubjectName); + } else { + if (targetSubjectName) { + activeLessonFilter = targetSubjectName; + } + updateModalLessonPills(); + renderQuestions(); + } + } + + function closeReviewModal() { + if (!mistakeModal) return; + mistakeModal.classList.add('hidden'); + document.body.style.overflow = ''; + } + + if (btnReviewMistakes) { + btnReviewMistakes.addEventListener('click', () => openReviewModal()); + } + + if (btnMistakeModalClose) { + btnMistakeModalClose.addEventListener('click', closeReviewModal); + } + + // Clicking clickable mistake badge in table + document.querySelectorAll('.clickable-mistake-btn').forEach(btn => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const subjectName = btn.getAttribute('data-subject-name'); + openReviewModal(subjectName); + }); + }); + + // Close modal when clicking outside dialog + if (mistakeModal) { + mistakeModal.addEventListener('click', (e) => { + if (e.target === mistakeModal) { + closeReviewModal(); + } + }); + } + + // Escape key closes modal & lightbox + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + if (imageLightbox && !imageLightbox.classList.contains('hidden')) { + closeLightbox(); + } else if (mistakeModal && !mistakeModal.classList.contains('hidden')) { + closeReviewModal(); + } + } + }); + + async function loadExamQuestions(initialSubjectFilter = null) { + mistakeLoading.classList.remove('hidden'); + questionsGrid.innerHTML = ''; + modalLessonPills.innerHTML = ''; + + try { + // Fetch both Wrong (Y) and Empty (B) questions + const [wrongRes, emptyRes] = await Promise.all([ + fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=Y`).then(r => r.json()), + fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=B`).then(r => r.json()) + ]); + + mistakeLoading.classList.add('hidden'); + + const subjectsMap = {}; + + if (wrongRes.success && wrongRes.subjects) { + wrongRes.subjects.forEach(s => { + if (!subjectsMap[s.subjectName]) { + subjectsMap[s.subjectName] = { subjectName: s.subjectName, subjectId: s.subjectId, questions: [] }; + } + s.questions.forEach(q => { + q.subjectName = s.subjectName; + subjectsMap[s.subjectName].questions.push(q); + }); + }); + } + + if (emptyRes.success && emptyRes.subjects) { + emptyRes.subjects.forEach(s => { + if (!subjectsMap[s.subjectName]) { + subjectsMap[s.subjectName] = { subjectName: s.subjectName, subjectId: s.subjectId, questions: [] }; + } + s.questions.forEach(q => { + q.subjectName = s.subjectName; + subjectsMap[s.subjectName].questions.push(q); + }); + }); + } + + cachedQuestions = Object.values(subjectsMap); + + if (initialSubjectFilter && subjectsMap[initialSubjectFilter]) { + activeLessonFilter = initialSubjectFilter; + } else { + activeLessonFilter = 'ALL'; + } + + updateModalLessonPills(); + renderQuestions(); + } catch (err) { + mistakeLoading.classList.add('hidden'); + questionsGrid.innerHTML = ` +
Sorular yüklenirken bir hata oluştu.
+ `; + } + } + + function updateModalLessonPills() { + if (!modalLessonPills || !cachedQuestions) return; + + let totalAll = 0; + cachedQuestions.forEach(s => { + totalAll += s.questions.length; + }); + + let html = ` + + `; + + cachedQuestions.forEach(s => { + const count = s.questions.length; + html += ` + + `; + }); + + modalLessonPills.innerHTML = html; + } + + if (modalLessonPills) { + modalLessonPills.addEventListener('click', (e) => { + const btn = e.target.closest('.modal-lesson-btn'); + if (!btn) return; + + modalLessonPills.querySelectorAll('.modal-lesson-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + + activeLessonFilter = btn.getAttribute('data-lesson'); + renderQuestions(); + }); + } + + // Type filter inside modal (all / wrong / empty) + modalTypeBtns.forEach(btn => { + btn.addEventListener('click', () => { + modalTypeBtns.forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + activeTypeFilter = btn.getAttribute('data-type'); + renderQuestions(); + }); + }); + + function renderQuestions() { + if (!questionsGrid || !cachedQuestions) return; + + let filteredList = []; + + cachedQuestions.forEach(s => { + if (activeLessonFilter === 'ALL' || activeLessonFilter === s.subjectName) { + s.questions.forEach(q => { + if (activeTypeFilter === 'all') { + filteredList.push(q); + } else if (activeTypeFilter === 'wrong' && q.status === 'wrong') { + filteredList.push(q); + } else if (activeTypeFilter === 'empty' && q.status === 'empty') { + filteredList.push(q); + } + }); + } + }); + + // Sort by question number ascending + filteredList.sort((a, b) => a.questionNumber - b.questionNumber); + + if (filteredList.length === 0) { + questionsGrid.innerHTML = ` +
+

Seçili filtrelere uygun soru bulunamadı.

+
+ `; + return; + } + + let html = ''; + filteredList.forEach(q => { + const isWrong = q.status === 'wrong'; + const studentClass = isWrong ? 'answer-student-wrong' : 'answer-student-empty'; + const studentText = isWrong ? q.studentAnswer : 'Boş'; + + html += ` +
+
+ Soru #${q.questionNumber} + ${escapeHtml(q.subjectName || '')} +
+ +
+ + Doğru: ${escapeHtml(q.correctAnswer)} + + + Öğrenci: ${escapeHtml(studentText)} + +
+ + ${ + q.imageUrl + ? ` +
+ Soru ${q.questionNumber} +
+ ` + : `
Soru görseli bulunamadı.
` + } +
+ `; + }); + + questionsGrid.innerHTML = html; + + // Attach click-to-zoom on images + questionsGrid.querySelectorAll('.question-img').forEach(img => { + img.addEventListener('click', () => { + openLightbox(img.src); + }); + }); + } + + // ---------------------------------------------------- + // Lightbox Zoom + // ---------------------------------------------------- + function openLightbox(src) { + if (!imageLightbox || !lightboxImg) return; + lightboxImg.src = src; + imageLightbox.classList.remove('hidden'); + } + + function closeLightbox() { + if (!imageLightbox) return; + imageLightbox.classList.add('hidden'); + if (lightboxImg) lightboxImg.src = ''; + } + + if (btnLightboxClose) { + btnLightboxClose.addEventListener('click', closeLightbox); + } + + if (imageLightbox) { + imageLightbox.addEventListener('click', (e) => { + if (e.target === imageLightbox || e.target === btnLightboxClose) { + closeLightbox(); + } + }); + } + + // ---------------------------------------------------- + // Utility: Escape HTML + // ---------------------------------------------------- + function escapeHtml(str) { + if (!str) return ''; + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } +}); diff --git a/src/server.ts b/src/server.ts index 2bf9df9..b79fdbb 100644 --- a/src/server.ts +++ b/src/server.ts @@ -7,6 +7,7 @@ import { ScraperService } from './services/scraper'; import { LocalDatabase } from './services/db'; import { InsightService } from './services/insight'; import { SyllabusService, DAY_NAMES } from './services/syllabus'; +import { ExamService } from './services/exam'; import { Assignment } from './types'; dotenv.config(); @@ -772,6 +773,259 @@ app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Res } }); +// ---------------------------------------------------- +// Exam Reports (Sınav Rapor) Routes +// ---------------------------------------------------- + +/** + * Helper to ensure active portal cookies + */ +async function getOrRefreshPortalCookies(req: Request, studentId: string): Promise { + if (req.session.portalCookies) { + return req.session.portalCookies; + } + const creds = db.getRememberedCredentials(studentId); + if (creds) { + const loginRes = await ScraperService.login(creds.studentId, creds.password); + if (loginRes.success) { + req.session.portalCookies = loginRes.cookies; + return loginRes.cookies; + } + } + return undefined; +} + +/** + * GET /rapor/sinav + * Official portal alias redirect + */ +app.get('/rapor/sinav', (req: Request, res: Response) => { + res.redirect('/exams'); +}); + +/** + * GET /exams + * Main Exam Reports Dashboard + */ +app.get('/exams', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + let examStore = db.getExamReports(studentId); + + // If no cached exams or empty, sync now + if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) { + const cookies = await getOrRefreshPortalCookies(req, studentId); + if (cookies) { + try { + const examList = await ScraperService.scrapeExamList(cookies); + if (examList.length > 0) { + const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id)); + const details = (await Promise.all(detailPromises)).filter( + (d): d is NonNullable => d !== null + ); + db.saveExamReports(studentId, details); + examStore = db.getExamReports(studentId); + } + } catch (err: any) { + console.error('Initial exam scrape error:', err.message); + } + } + } + + const rawDetails = examStore?.reports ? Object.values(examStore.reports) : []; + const processedExams = ExamService.computeDeltasAndRatings(rawDetails); + + const tytExams = processedExams.filter(e => e.summary.examType === 'TYT'); + const aytExams = processedExams.filter(e => e.summary.examType === 'AYT'); + + const requestedId = (req.query.id as string) || ''; + const selectedExam = + (requestedId ? processedExams.find(e => e.summary.id === requestedId) : null) || + processedExams[0] || + null; + + const kpis = ExamService.calculateKPIs(processedExams); + + res.render('exams', { + title: 'Sınav Raporları - BeKultur', + studentId, + studentName: req.session.studentName || '', + allExams: processedExams, + tytExams, + aytExams, + selectedExam, + kpis, + lastSynced: examStore?.lastSynced || null + }); +}); + +/** + * GET /api/exams/:id + * Retrieve specific exam scorecard and subject breakdown + */ +app.get('/api/exams/:id', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const examId = req.params.id; + + let examStore = db.getExamReports(studentId); + let exam = examStore?.reports?.[examId]; + + if (!exam) { + const cookies = await getOrRefreshPortalCookies(req, studentId); + if (cookies) { + const fetched = await ScraperService.scrapeExamDetail(cookies, examId); + if (fetched) { + db.saveExamReports(studentId, [fetched]); + examStore = db.getExamReports(studentId); + } + } + } + + const rawDetails = examStore?.reports ? Object.values(examStore.reports) : []; + const processed = ExamService.computeDeltasAndRatings(rawDetails); + const matched = processed.find(e => e.summary.id === examId); + + if (!matched) { + return res.status(404).json({ success: false, error: 'Exam not found' }); + } + + res.json({ success: true, exam: matched }); +}); + +/** + * GET /api/exams/:id/questions + * Retrieve question review items (mistakes / empty questions) + */ +app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const examId = req.params.id; + const dersId = (req.query.dersId as string) || ''; + const ogrenciDonemId = (req.query.ogrenciDonemId as string) || ''; + const tip = ((req.query.tip as string) || 'Y').toUpperCase() as 'D' | 'Y' | 'B'; + + const cookies = await getOrRefreshPortalCookies(req, studentId); + if (!cookies) { + return res.status(401).json({ success: false, error: 'Session expired' }); + } + + // If specific subject requested, fetch directly + if (dersId && ogrenciDonemId) { + const questions = await ScraperService.scrapeExamQuestions(cookies, examId, ogrenciDonemId, dersId, tip); + return res.json({ success: true, questions }); + } + + // Otherwise, inspect exam details and fetch questions for all subjects with mistakes + const examStore = db.getExamReports(studentId); + const exam = examStore?.reports?.[examId]; + + if (!exam) { + return res.status(404).json({ success: false, error: 'Exam detail not cached' }); + } + + const subjectQuestionsList: Array<{ + subjectName: string; + subjectId: string; + questions: any[]; + }> = []; + + for (const subject of exam.subjects) { + const shouldFetch = tip === 'Y' ? subject.wrongCount > 0 : tip === 'B' ? subject.emptyCount > 0 : true; + if (shouldFetch && subject.subjectId && subject.ogrenciDonemId) { + const q = await ScraperService.scrapeExamQuestions( + cookies, + examId, + subject.ogrenciDonemId, + subject.subjectId, + tip + ); + if (q.length > 0) { + subjectQuestionsList.push({ + subjectName: subject.subjectName, + subjectId: subject.subjectId, + questions: q + }); + } + } + } + + res.json({ + success: true, + totalMistakes: subjectQuestionsList.reduce((acc, s) => acc + s.questions.length, 0), + subjects: subjectQuestionsList + }); +}); + +/** + * GET /api/exams/:id/weaknesses + * Retrieve topic weakness breakdown + */ +app.get('/api/exams/:id/weaknesses', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const examId = req.params.id; + + const cached = db.getTopicWeaknesses(studentId, examId); + if (cached && cached.length > 0) { + return res.json({ success: true, weaknesses: cached }); + } + + const cookies = await getOrRefreshPortalCookies(req, studentId); + if (!cookies) { + return res.status(401).json({ success: false, error: 'Session expired' }); + } + + const weaknesses = await ScraperService.scrapeTopicWeaknesses(cookies, examId); + db.saveTopicWeaknesses(studentId, examId, weaknesses); + + res.json({ success: true, weaknesses }); +}); + +/** + * POST /api/exams/sync + * Manually refresh all exam data from portal + */ +app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) => { + const studentId = req.session.studentId!; + const cookies = await getOrRefreshPortalCookies(req, studentId); + + if (!cookies) { + return res.status(401).json({ + success: false, + error: 'Session expired. Please log in again to sync exams.' + }); + } + + try { + const examList = await ScraperService.scrapeExamList(cookies); + if (!examList || examList.length === 0) { + return res.json({ success: true, count: 0, message: 'No exams found on portal.' }); + } + + const detailPromises = examList.map(item => ScraperService.scrapeExamDetail(cookies, item.id)); + const details = (await Promise.all(detailPromises)).filter( + (d): d is NonNullable => d !== null + ); + + db.saveExamReports(studentId, details); + const updatedStore = db.getExamReports(studentId); + const rawDetails = updatedStore?.reports ? Object.values(updatedStore.reports) : []; + const processed = ExamService.computeDeltasAndRatings(rawDetails); + const kpis = ExamService.calculateKPIs(processed); + + res.json({ + success: true, + count: processed.length, + lastSynced: updatedStore?.lastSynced, + kpis, + exams: processed + }); + } catch (err: any) { + console.error('API exams sync error:', err.message); + res.status(500).json({ + success: false, + error: `Exams 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 ac71ee1..b27eeba 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -1,6 +1,16 @@ import fs from 'fs'; import path from 'path'; -import { DatabaseSchema, StudentStore, Assignment, PrivateLesson, PrivateLessonFormMeta, PrivateLessonsStore } from '../types'; +import { + DatabaseSchema, + StudentStore, + Assignment, + PrivateLesson, + PrivateLessonFormMeta, + PrivateLessonsStore, + ExamReportDetail, + ExamStore, + ExamTopicWeakness +} from '../types'; const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json'); @@ -227,4 +237,52 @@ export class LocalDatabase { const student = this.cache.students[studentId]; return student?.advisoryTeacher || student?.privateLessons?.detectedAdvisor || null; } + + // ---------------------------------------------------- + // Exam Reports (Sınav Rapor) Store + // ---------------------------------------------------- + + public saveExamReports(studentId: string, reports: ExamReportDetail[]): void { + const student = this.getStudentStore(studentId); + const existing = student.exams; + const reportsMap: Record = existing?.reports ? { ...existing.reports } : {}; + + reports.forEach(r => { + reportsMap[r.summary.id] = r; + }); + + student.exams = { + lastSynced: new Date().toISOString(), + reports: reportsMap, + topicWeaknesses: existing?.topicWeaknesses || {} + }; + + this.save(); + } + + public getExamReports(studentId: string): ExamStore | null { + const student = this.cache.students[studentId]; + return student?.exams || null; + } + + public saveTopicWeaknesses(studentId: string, examId: string, weaknesses: ExamTopicWeakness[]): void { + const student = this.getStudentStore(studentId); + if (!student.exams) { + student.exams = { + lastSynced: new Date().toISOString(), + reports: {}, + topicWeaknesses: {} + }; + } + if (!student.exams.topicWeaknesses) { + student.exams.topicWeaknesses = {}; + } + student.exams.topicWeaknesses[examId] = weaknesses; + this.save(); + } + + public getTopicWeaknesses(studentId: string, examId: string): ExamTopicWeakness[] | null { + const student = this.cache.students[studentId]; + return student?.exams?.topicWeaknesses?.[examId] || null; + } } diff --git a/src/services/exam.ts b/src/services/exam.ts new file mode 100644 index 0000000..a3d910c --- /dev/null +++ b/src/services/exam.ts @@ -0,0 +1,253 @@ +import { + ExamReportDetail, + ExamReportSummary, + ExamType, + ExamRating, + ExamKPIs +} from '../types'; + +export class ExamService { + /** + * Determine exam category (TYT vs AYT) based on title and question volume + */ + public static categorizeExam(name: string, totalQuestions?: number): ExamType { + const upper = name.toUpperCase(); + if (upper.includes('AYT')) { + return 'AYT'; + } + if (upper.includes('TYT') || upper.includes('YKS')) { + return 'TYT'; + } + if (totalQuestions !== undefined) { + return totalQuestions <= 80 ? 'AYT' : 'TYT'; + } + return 'TYT'; + } + + /** + * Extract sequence number from exam name (e.g. "12 YKS-04 MF" -> 4) + */ + public static getExamOrder(name: string, id: string): number { + const match = name.match(/[-_](\d+)/); + if (match) { + return parseInt(match[1], 10); + } + const anyDigit = name.match(/\b\d+\b/); + if (anyDigit) { + return parseInt(anyDigit[0], 10); + } + return parseInt(id, 10) || 0; + } + + /** + * Compute Net and Rank Deltas and Difficulty-Adjusted Composite Ratings + */ + public static computeDeltasAndRatings(details: ExamReportDetail[]): ExamReportDetail[] { + if (!details || details.length === 0) return []; + + // Group by ExamType + const byType: Record = { + TYT: [], + AYT: [], + OTHER: [] + }; + + details.forEach(d => { + const type = d.summary.examType || this.categorizeExam(d.summary.name, d.summary.totalQuestions); + d.summary.examType = type; + if (!byType[type]) byType[type] = []; + byType[type].push(d); + }); + + const processedList: ExamReportDetail[] = []; + + // Process each category chronologically + (Object.keys(byType) as ExamType[]).forEach(type => { + const group = byType[type]; + if (group.length === 0) return; + + // Sort ascending chronologically for delta calculation + group.sort((a, b) => { + const orderA = this.getExamOrder(a.summary.name, a.summary.id); + const orderB = this.getExamOrder(b.summary.name, b.summary.id); + return orderA - orderB; + }); + + for (let i = 0; i < group.length; i++) { + const curr = group[i]; + + if (i === 0) { + // Baseline exam in category + curr.summary.deltaNet = undefined; + curr.summary.deltaRank = undefined; + const rank = curr.summary.generalRank; + if (rank !== undefined && rank <= 10) { + curr.summary.rating = { + label: 'Top 10 Baseline', + icon: 'bi-award-fill', + badgeClass: 'badge-soft-primary' + }; + } else { + curr.summary.rating = { + label: 'Baseline Exam', + icon: 'bi-flag-fill', + badgeClass: 'badge-soft-secondary' + }; + } + } else { + const prev = group[i - 1]; + + // 1. Net Delta + const deltaNet = Math.round((curr.summary.totalNet - prev.summary.totalNet) * 100) / 100; + curr.summary.deltaNet = deltaNet; + + // 2. Rank Delta (places climbed; positive means improved rank) + let deltaRank: number | undefined; + if (curr.summary.generalRank !== undefined && prev.summary.generalRank !== undefined) { + deltaRank = prev.summary.generalRank - curr.summary.generalRank; + curr.summary.deltaRank = deltaRank; + } + + // 3. Multi-Dimensional Performance Rating + curr.summary.rating = this.determineRating(deltaNet, deltaRank, curr.summary.generalRank); + + // 4. Subject-level Net Deltas + curr.subjects.forEach(currSub => { + const prevSub = prev.subjects.find( + s => + s.subjectName.trim().toLowerCase() === currSub.subjectName.trim().toLowerCase() || + (s.subjectId && currSub.subjectId && s.subjectId === currSub.subjectId) + ); + if (prevSub) { + currSub.deltaNet = Math.round((currSub.net - prevSub.net) * 100) / 100; + } + }); + } + + processedList.push(curr); + } + }); + + // Sort descending (latest exam first) for intuitive user display + processedList.sort((a, b) => { + // First by type (TYT first, then AYT) + if (a.summary.examType !== b.summary.examType) { + return a.summary.examType === 'TYT' ? -1 : 1; + } + // Then descending order + const orderA = this.getExamOrder(a.summary.name, a.summary.id); + const orderB = this.getExamOrder(b.summary.name, b.summary.id); + return orderB - orderA; + }); + + return processedList; + } + + /** + * Determine rating badge cross-referencing Net Delta and Rank Delta + */ + private static determineRating( + deltaNet: number, + deltaRank: number | undefined, + currentRank: number | undefined + ): ExamRating { + // 1. Breakthrough: Both net improved and rank improved + if (deltaNet > 0 && deltaRank !== undefined && deltaRank > 0) { + return { + label: 'Breakthrough', + icon: 'bi-stars', + badgeClass: 'badge-soft-success' + }; + } + + // 2. Outperformed Curve: Net dropped (harder exam), but rank improved or held strong + if (deltaNet < 0 && ((deltaRank !== undefined && deltaRank >= 0) || (currentRank !== undefined && currentRank <= 10))) { + return { + label: 'Outperformed Curve', + icon: 'bi-shield-check', + badgeClass: 'badge-soft-info' + }; + } + + // 3. Net Growth: Net increased + if (deltaNet > 0) { + return { + label: 'Net Growth', + icon: 'bi-graph-up-arrow', + badgeClass: 'badge-soft-success' + }; + } + + // 4. Rank Climb: Rank improved even if net stayed flat + if (deltaRank !== undefined && deltaRank > 0) { + return { + label: 'Rank Climb', + icon: 'bi-trophy-fill', + badgeClass: 'badge-soft-primary' + }; + } + + // 5. Consistent Top 10 Standing + if (currentRank !== undefined && currentRank <= 10) { + return { + label: 'Top 10 Consistency', + icon: 'bi-award-fill', + badgeClass: 'badge-soft-primary' + }; + } + + // 6. Needs Review: Both net and rank slipped + if (deltaNet < 0 && deltaRank !== undefined && deltaRank < 0) { + return { + label: 'Needs Review', + icon: 'bi-exclamation-triangle-fill', + badgeClass: 'badge-soft-danger' + }; + } + + return { + label: 'Stable Performance', + icon: 'bi-check-circle-fill', + badgeClass: 'badge-soft-secondary' + }; + } + + /** + * Compute aggregate performance KPIs + */ + public static calculateKPIs(details: ExamReportDetail[]): ExamKPIs { + if (!details || details.length === 0) { + return { + latestNet: 0, + bestNet: 0, + averageNet: 0, + totalExams: 0 + }; + } + + const nets = details.map(d => d.summary.totalNet); + const validRanks = details + .map(d => d.summary.generalRank) + .filter((r): r is number => r !== undefined && r > 0); + + const latestNet = details[0].summary.totalNet; + const bestNet = Math.max(...nets); + const averageNet = Math.round((nets.reduce((sum, n) => sum + n, 0) / nets.length) * 100) / 100; + + const latestRank = details[0].summary.generalRank; + const bestRank = validRanks.length ? Math.min(...validRanks) : undefined; + const averageRank = validRanks.length + ? Math.round(validRanks.reduce((sum, r) => sum + r, 0) / validRanks.length) + : undefined; + + return { + latestNet, + bestNet, + averageNet, + latestRank, + bestRank, + averageRank, + totalExams: details.length + }; + } +} diff --git a/src/services/scraper.ts b/src/services/scraper.ts index 4f6290b..8a1bb2f 100644 --- a/src/services/scraper.ts +++ b/src/services/scraper.ts @@ -1,7 +1,17 @@ import axios from 'axios'; import * as cheerio from 'cheerio'; import crypto from 'crypto'; -import { Assignment, Lesson, PrivateLesson, PrivateLessonFormMeta } from '../types'; +import { + Assignment, + Lesson, + PrivateLesson, + PrivateLessonFormMeta, + ExamReportSummary, + ExamReportDetail, + ExamSubjectScore, + ExamQuestionItem, + ExamTopicWeakness +} from '../types'; import { InsightService } from './insight'; import { DAY_NAMES } from './syllabus'; @@ -661,4 +671,367 @@ export class ScraperService { return { success: false, message: err.message || 'Submission failed' }; } } + + // ---------------------------------------------------- + // Exam Reports (Sınav Rapor) Scrapers + // ---------------------------------------------------- + + /** + * Scrape list of all available exam reports from /rapor/sinav + */ + public static async scrapeExamList(cookies: string): Promise> { + try { + const res = await axios.get(`${BASE_URL}/rapor/sinav`, { + headers: { + 'Cookie': cookies, + 'User-Agent': USER_AGENT + }, + maxRedirects: 5, + validateStatus: () => true + }); + + if (res.status < 200 || res.status >= 400) { + console.error(`GET /rapor/sinav returned status ${res.status}`); + return []; + } + + const $ = cheerio.load(res.data); + const exams: Array<{ id: string; name: string }> = []; + + $('a[href*="/rapor/sinavkarne/"]').each((_, el) => { + const href = $(el).attr('href') || ''; + const match = href.match(/\/rapor\/sinavkarne\/(\d+)/); + if (match) { + const id = match[1]; + const name = $(el).clone().children().remove().end().text().trim() || $(el).text().trim(); + exams.push({ id, name }); + } + }); + + return exams; + } catch (err: any) { + console.error('Failed to scrape exam list:', err.message); + return []; + } + } + + /** + * Scrape exam scorecard, rankings, and subject breakdown from /rapor/sinavkarne/:id + */ + public static async scrapeExamDetail(cookies: string, examId: string): Promise { + try { + const res = await axios.get(`${BASE_URL}/rapor/sinavkarne/${encodeURIComponent(examId)}`, { + headers: { + 'Cookie': cookies, + 'User-Agent': USER_AGENT + }, + maxRedirects: 5, + validateStatus: () => true + }); + + if (res.status < 200 || res.status >= 400) { + console.error(`GET /rapor/sinavkarne/${examId} returned status ${res.status}`); + return null; + } + + const $ = cheerio.load(res.data); + + // 1. Extract Ranks + let generalRank: number | undefined; + let schoolRank: number | undefined; + $('.kltr-card .badge, .badge').each((_, el) => { + const text = $(el).text().trim(); + const genelMatch = text.match(/Genel\s*Sıra\s*:\s*(\d+)/i); + if (genelMatch) generalRank = parseInt(genelMatch[1], 10); + const okulMatch = text.match(/Okul\s*Sıra\s*:\s*(\d+)/i); + if (okulMatch) schoolRank = parseInt(okulMatch[1], 10); + }); + + // 2. Extract Exam Title & Answer Key link + const caption = $('table caption'); + let examName = caption.find('.text-primary').text().trim(); + if (!examName) { + examName = caption.text().replace(/Sınav\s*-\s*/i, '').replace(/Cevap Anahtarı/i, '').trim(); + } + if (!examName) { + examName = `Sınav ${examId}`; + } + + const answerKeyHref = caption.find('a[href*="/rapor/sinavcevapanahtari/"]').attr('href'); + const hasAnswerKey = !!answerKeyHref; + const answerKeyUrl = answerKeyHref ? `${BASE_URL}${answerKeyHref}` : undefined; + + // 3. Parse Subject Rows + const subjects: ExamSubjectScore[] = []; + let totalQuestions = 0; + let totalCorrect = 0; + let totalWrong = 0; + let totalEmpty = 0; + let totalNet = 0; + let totalScore = 0; + + $('table tbody tr').each((_, tr) => { + const tds = $(tr).find('td'); + if (tds.length < 7) return; + + const subjectName = $(tds[0]).text().trim(); + const questionCount = parseInt($(tds[1]).text().trim(), 10) || 0; + + const correctBtn = $(tds[2]).find('a'); + const correctCount = parseInt(correctBtn.text().trim(), 10) || 0; + const correctAnalysisUrl = correctBtn.attr('href') || undefined; + + const wrongBtn = $(tds[3]).find('a'); + const wrongCount = parseInt(wrongBtn.text().trim(), 10) || 0; + const wrongAnalysisUrl = wrongBtn.attr('href') || undefined; + + const emptyBtn = $(tds[4]).find('a'); + const emptyCount = parseInt(emptyBtn.text().trim(), 10) || 0; + const emptyAnalysisUrl = emptyBtn.attr('href') || undefined; + + const netText = $(tds[5]).text().trim().replace(',', '.'); + const net = parseFloat(netText) || 0; + + const scoreText = $(tds[6]).text().trim().replace(',', '.'); + const score = parseFloat(scoreText) || 0; + + let percentage = 0; + const progressBar = $(tds[7]).find('.progress-bar'); + if (progressBar.length) { + percentage = parseInt(progressBar.attr('aria-valuenow') || '0', 10) || 0; + } else if (questionCount > 0) { + percentage = Math.round((correctCount / questionCount) * 100); + } + + let subjectId = ''; + let ogrenciDonemId = ''; + const sampleUrl = wrongAnalysisUrl || correctAnalysisUrl || emptyAnalysisUrl; + if (sampleUrl) { + const dMatch = sampleUrl.match(/dersId=(\d+)/i); + if (dMatch) subjectId = dMatch[1]; + const odMatch = sampleUrl.match(/ogrenciDonemId=(\d+)/i); + if (odMatch) ogrenciDonemId = odMatch[1]; + } + + totalQuestions += questionCount; + totalCorrect += correctCount; + totalWrong += wrongCount; + totalEmpty += emptyCount; + totalNet += net; + totalScore += score; + + subjects.push({ + subjectId, + subjectName, + questionCount, + correctCount, + wrongCount, + emptyCount, + net: Math.round(net * 100) / 100, + score: Math.round(score * 100) / 100, + percentage, + ogrenciDonemId: ogrenciDonemId || undefined, + correctAnalysisUrl, + wrongAnalysisUrl, + emptyAnalysisUrl + }); + }); + + // Classify Exam Type: TYT vs AYT + let examType: 'TYT' | 'AYT' | 'OTHER' = 'TYT'; + const upperName = examName.toUpperCase(); + if (upperName.includes('AYT')) { + examType = 'AYT'; + } else if (upperName.includes('YKS') || upperName.includes('TYT')) { + examType = 'TYT'; + } else { + examType = totalQuestions <= 80 ? 'AYT' : 'TYT'; + } + + const summary: ExamReportSummary = { + id: examId, + name: examName, + examType, + totalQuestions, + totalCorrect, + totalWrong, + totalEmpty, + totalNet: Math.round(totalNet * 100) / 100, + totalScore: Math.round(totalScore * 100) / 100, + generalRank, + schoolRank, + answerKeyUrl + }; + + return { + summary, + subjects, + hasAnswerKey, + answerKeyUrl + }; + } catch (err: any) { + console.error(`Failed to scrape exam detail ${examId}:`, err.message); + return null; + } + } + + /** + * Scrape question items (images, choices, correct/student answers) from bilgi.ozelbursakulturokullari.com + */ + public static async scrapeExamQuestions( + cookies: string, + sinavId: string, + ogrenciDonemId: string, + dersId: string, + tip: 'D' | 'Y' | 'B' + ): Promise { + try { + const url = `${BILGI_BASE_URL}/ogrencisoruanaliz?sinavId=${encodeURIComponent(sinavId)}&ogrenciDonemId=${encodeURIComponent(ogrenciDonemId)}&dersId=${encodeURIComponent(dersId)}&tip=${encodeURIComponent(tip)}`; + + const res = await axios.get(url, { + headers: { + 'Cookie': cookies, + 'User-Agent': USER_AGENT + }, + maxRedirects: 5, + validateStatus: () => true + }); + + if (res.status < 200 || res.status >= 400) { + console.error(`GET ogrencisoruanaliz returned status ${res.status}`); + return []; + } + + const $ = cheerio.load(res.data); + const items: ExamQuestionItem[] = []; + + $('.row > div').each((_, el) => { + const text = $(el).find('p.small').text().replace(/\s+/g, ' '); + if (!text) return; + + const noMatch = text.match(/SoruNo:\s*(\d+)/i); + const dogruMatch = text.match(/Doğru\s*Cevap:\s*([A-E\-]+)/i); + const ogrenciMatch = text.match(/Öğrenci\s*Cevap:\s*([A-E\-]+)/i); + + let imgUrl = $(el).find('img').attr('src') || ''; + if (imgUrl.startsWith('//')) { + imgUrl = `https:${imgUrl}`; + } else if (imgUrl.startsWith('/')) { + imgUrl = `https://panel.ozelbursakulturokullari.com${imgUrl}`; + } + + const questionNumber = noMatch ? parseInt(noMatch[1], 10) : 0; + const correctAnswer = dogruMatch ? dogruMatch[1].trim() : '-'; + const studentAnswer = ogrenciMatch ? ogrenciMatch[1].trim() : (tip === 'B' ? 'Boş' : '-'); + + const status: 'correct' | 'wrong' | 'empty' = + tip === 'Y' ? 'wrong' : tip === 'B' ? 'empty' : 'correct'; + + items.push({ + questionNumber, + correctAnswer, + studentAnswer, + imageUrl: imgUrl, + status, + subjectId: dersId + }); + }); + + return items; + } catch (err: any) { + console.error('Failed to scrape exam questions:', err.message); + return []; + } + } + + /** + * Scrape topic weakness breakdown from /rapor/yanliskonu + */ + public static async scrapeTopicWeaknesses( + cookies: string, + sinavId: string, + dersId?: string + ): Promise { + try { + // 1. Obtain verification token + const getRes = await axios.get(`${BASE_URL}/rapor/yanliskonu`, { + headers: { + 'Cookie': cookies, + 'User-Agent': USER_AGENT + }, + maxRedirects: 5, + validateStatus: () => true + }); + + const $get = cheerio.load(getRes.data); + const token = $get('input[name="__RequestVerificationToken"]').val() as string; + + // Merge any new cookies + const updatedCookies = this.mergeCookies(cookies, getRes.headers['set-cookie']); + + // 2. POST to /rapor/yanliskonu + const formData = new URLSearchParams(); + formData.append('SinavId', sinavId); + formData.append('DersId', dersId || ''); + if (token) { + formData.append('__RequestVerificationToken', token); + } + + const postRes = await axios.post(`${BASE_URL}/rapor/yanliskonu`, formData.toString(), { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Referer': `${BASE_URL}/rapor/yanliskonu`, + 'Cookie': updatedCookies, + 'User-Agent': USER_AGENT + }, + maxRedirects: 5, + validateStatus: () => true + }); + + if (postRes.status < 200 || postRes.status >= 400) { + return []; + } + + const $ = cheerio.load(postRes.data); + const weaknesses: ExamTopicWeakness[] = []; + + $('table tbody tr').each((_, tr) => { + const tds = $(tr).find('td'); + if (tds.length < 8) return; + + const examName = $(tds[0]).text().trim(); + const subjectName = $(tds[1]).text().trim(); + const topicName = $(tds[2]).text().trim(); + const totalCount = parseInt($(tds[3]).text().trim(), 10) || 0; + const correctCount = parseInt($(tds[4]).text().trim(), 10) || 0; + const wrongCount = parseInt($(tds[5]).text().trim(), 10) || 0; + const emptyCount = parseInt($(tds[6]).text().trim(), 10) || 0; + + let successRate = 0; + const progressBar = $(tds[7]).find('.progress-bar'); + if (progressBar.length) { + successRate = parseInt(progressBar.attr('aria-valuenow') || '0', 10) || 0; + } else if (totalCount > 0) { + successRate = Math.round((correctCount / totalCount) * 100); + } + + weaknesses.push({ + examId: sinavId, + examName, + subjectName, + topicName, + totalCount, + correctCount, + wrongCount, + emptyCount, + successRate + }); + }); + + return weaknesses; + } catch (err: any) { + console.error('Failed to scrape topic weaknesses:', err.message); + return []; + } + } } diff --git a/src/types/index.ts b/src/types/index.ts index b6b4f29..2ad8a4b 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -102,6 +102,98 @@ export interface PrivateLessonsStore { detectedAdvisor?: string; } +// ---------------------------------------------------- +// Exam Reports (Sınav Rapor) Types +// ---------------------------------------------------- +export type ExamType = 'TYT' | 'AYT' | 'OTHER'; + +export interface ExamRating { + label: string; // e.g. "Breakthrough", "Outperformed Curve", "Consistent Top 10" + icon: string; // e.g. "bi-star-fill", "bi-shield-check", "bi-graph-up-arrow" + badgeClass: string; // e.g. "badge-soft-success", "badge-soft-primary", "badge-soft-info" +} + +export interface ExamReportSummary { + id: string; // e.g. "3366" + name: string; // e.g. "12 YKS-04 MF" + examType: ExamType; // 'TYT' | 'AYT' | 'OTHER' + totalQuestions: number; + totalCorrect: number; + totalWrong: number; + totalEmpty: number; + totalNet: number; + totalScore: number; + generalRank?: number; // e.g. 9 + schoolRank?: number; // e.g. 9 + deltaNet?: number; // compared to previous exam of same type + deltaRank?: number; // places gained (>0 means improved standing) + rating?: ExamRating; + date?: string; + answerKeyUrl?: string; +} + +export interface ExamSubjectScore { + subjectId: string; + subjectName: string; + questionCount: number; + correctCount: number; + wrongCount: number; + emptyCount: number; + net: number; + score: number; + percentage: number; + deltaNet?: number; + ogrenciDonemId?: string; + correctAnalysisUrl?: string; + wrongAnalysisUrl?: string; + emptyAnalysisUrl?: string; +} + +export interface ExamReportDetail { + summary: ExamReportSummary; + subjects: ExamSubjectScore[]; + hasAnswerKey: boolean; + answerKeyUrl?: string; +} + +export interface ExamQuestionItem { + questionNumber: number; + correctAnswer: string; + studentAnswer: string; + imageUrl: string; + status: 'correct' | 'wrong' | 'empty'; + subjectId?: string; + subjectName?: string; +} + +export interface ExamTopicWeakness { + examId: string; + examName: string; + subjectName: string; + topicName: string; + totalCount: number; + correctCount: number; + wrongCount: number; + emptyCount: number; + successRate: number; +} + +export interface ExamKPIs { + latestNet: number; + bestNet: number; + averageNet: number; + latestRank?: number; + bestRank?: number; + averageRank?: number; + totalExams: number; +} + +export interface ExamStore { + lastSynced: string; + reports: Record; + topicWeaknesses?: Record; +} + export interface StudentStore { studentId: string; lastSynced: string | null; @@ -113,6 +205,7 @@ export interface StudentStore { syllabus?: SyllabusStore; advisoryTeacher?: string | null; privateLessons?: PrivateLessonsStore; + exams?: ExamStore; } export interface DatabaseSchema { diff --git a/test/run-tests.ts b/test/run-tests.ts index 43c61a6..16a4979 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -3,7 +3,8 @@ import { LocalDatabase } from '../src/services/db'; import { InsightService } from '../src/services/insight'; import { ScraperService } from '../src/services/scraper'; import { SyllabusService } from '../src/services/syllabus'; -import { Assignment, Lesson } from '../src/types'; +import { ExamService } from '../src/services/exam'; +import { Assignment, Lesson, ExamReportDetail } from '../src/types'; async function runAllTests() { console.log('========================================================'); @@ -430,6 +431,217 @@ async function runAllTests() { assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'SEVGİ BİKİL'); }); + // 6. 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, // Net dropped due to harder test + totalScore: 82.50, + generalRank: 9 // Held single-digit rank #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); + + // Map by ID for assertion + 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')!; + + // Exam 1: Baseline + assert.strictEqual(yks1.summary.deltaNet, undefined); + assert.strictEqual(yks1.summary.deltaRank, undefined); + + // Exam 2: Net +11.00, Rank improved from 16 to 14 (+2 places climbed) -> Breakthrough + 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); // 34.5 - 28.5 + + // Exam 3: Net +4.50, Rank improved from 14 to 8 (+6 places climbed) -> Breakthrough + assert.strictEqual(yks3.summary.deltaNet, 4.50); + assert.strictEqual(yks3.summary.deltaRank, 6); + assert.strictEqual(yks3.summary.rating?.label, 'Breakthrough'); + + // Exam 4: Net -5.50 (harder exam), but rank held in top 10 (#9) -> Outperformed Curve! + 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'); + + // Topic weaknesses + 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'); + }); + // 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/exams.ejs b/views/exams.ejs new file mode 100644 index 0000000..da8c4e2 --- /dev/null +++ b/views/exams.ejs @@ -0,0 +1,384 @@ +<%- include('partials/header') %> + +
+ +
+
+

Exam Reports

+

+ Sınav Raporları, Gelişim Analizi & Soru İnceleme + <% if (lastSynced) { %> + • Synced: <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %> + <% } %> +

+
+ +
+ +
+
+ + + + <% if (allExams && allExams.length > 0) { %> + +
+
+ Latest Net + <%= kpis.latestNet.toFixed(2) %> + + <% if (allExams[0].summary.deltaNet !== undefined) { %> + + <%= allExams[0].summary.deltaNet >= 0 ? '+' : '' %><%= allExams[0].summary.deltaNet.toFixed(2) %> net vs prior + + <% } else { %> + Baseline exam + <% } %> + +
+ +
+ Personal Best Net + <%= kpis.bestNet.toFixed(2) %> + Across all <%= kpis.totalExams %> exams +
+ +
+ Average Net + <%= kpis.averageNet.toFixed(2) %> + Overall student mean +
+ +
+ Current Rank + + <%= kpis.latestRank ? '#' + kpis.latestRank : '-' %> + + + <% if (kpis.bestRank) { %> + Best standing: #<%= kpis.bestRank %> + <% } else { %> + General standing + <% } %> + +
+
+ + +
+
+ + + +
+
+ + +
+ <% allExams.forEach(function(exam, index) { %> +
+
+ + <%= exam.summary.examType %> + + <%= exam.summary.name %> +
+ +
+
+ <%= exam.summary.totalNet.toFixed(2) %> Net + <% if (exam.summary.deltaNet !== undefined) { %> + + <%= exam.summary.deltaNet >= 0 ? '+' : '' %><%= exam.summary.deltaNet.toFixed(2) %> + + <% } %> +
+ + <% if (exam.summary.generalRank) { %> +
+ #<%= exam.summary.generalRank %> + <% if (exam.summary.deltaRank !== undefined && exam.summary.deltaRank !== 0) { %> + + <%= exam.summary.deltaRank > 0 ? '+' : '' %><%= exam.summary.deltaRank %> + + <% } %> +
+ <% } %> +
+ + <% if (exam.summary.rating) { %> +
+ + <%= exam.summary.rating.label %> + +
+ <% } %> +
+ <% }); %> +
+ + + <% if (selectedExam) { %> +
+
+
+
+ + <%= selectedExam.summary.examType %> + +

<%= selectedExam.summary.name %>

+ <% if (selectedExam.hasAnswerKey && selectedExam.answerKeyUrl) { %> + + Cevap Anahtarı + + <% } %> +
+ +
+ <% if (selectedExam.summary.generalRank) { %> + + Genel Sıra : <%= selectedExam.summary.generalRank %> + <% if (selectedExam.summary.deltaRank !== undefined && selectedExam.summary.deltaRank !== 0) { %> + (<%= selectedExam.summary.deltaRank > 0 ? '+' : '' %><%= selectedExam.summary.deltaRank %> sıra) + <% } %> + + <% } %> + + <% if (selectedExam.summary.schoolRank) { %> + + Okul Sıra : <%= selectedExam.summary.schoolRank %> + + <% } %> + + <% if (selectedExam.summary.rating) { %> + + <%= selectedExam.summary.rating.label %> + + <% } %> +
+
+ +
+ +
+
+ + +
+ + +
+ + +
+
+ + + + + + + + + + + + + + + <% selectedExam.subjects.forEach(function(sub) { %> + + + + + + + + + + + <% }); %> + + + + + + + + + + + + + +
DersSoruDoğruYanlışBoşNetNet Değişim (Δ)Başarı Oranı
<%= sub.subjectName %><%= sub.questionCount %> + <%= sub.correctCount %> + + <% if (sub.wrongCount > 0) { %> + + <% } else { %> + 0 + <% } %> + + <% if (sub.emptyCount > 0) { %> + + <% } else { %> + 0 + <% } %> + + <%= sub.net.toFixed(2) %> + + <% if (sub.deltaNet !== undefined) { %> + + <%= sub.deltaNet >= 0 ? '+' : '' %><%= sub.deltaNet.toFixed(2) %> + + <% } else { %> + - + <% } %> + +
+
+
+
+ <%= sub.percentage %>% +
+
TOPLAM<%= selectedExam.summary.totalQuestions %><%= selectedExam.summary.totalCorrect %><%= selectedExam.summary.totalWrong %><%= selectedExam.summary.totalEmpty %><%= selectedExam.summary.totalNet.toFixed(2) %> + <% if (selectedExam.summary.deltaNet !== undefined) { %> + + <%= selectedExam.summary.deltaNet >= 0 ? '+' : '' %><%= selectedExam.summary.deltaNet.toFixed(2) %> + + <% } else { %> + - + <% } %> + +
+ <% + const totalPct = selectedExam.summary.totalQuestions > 0 + ? Math.round((selectedExam.summary.totalCorrect / selectedExam.summary.totalQuestions) * 100) + : 0; + %> +
+
+
+ <%= totalPct %>% +
+
+
+
+ + + +
+ <% } %> + + <% } else { %> + +
+
📊
+

Henüz Sınav Raporu Bulunmuyor

+

Öğrenci portalındaki sınav verilerini içe aktarmak için "Sync Exams" butonuna tıklayınız.

+ +
+ <% } %> +
+ + + + + + + + + + +<%- include('partials/footer') %> diff --git a/views/partials/header.ejs b/views/partials/header.ejs index d69cf74..ad9d082 100644 --- a/views/partials/header.ejs +++ b/views/partials/header.ejs @@ -18,6 +18,7 @@ Homework Syllabus Private Lessons + Exams <% } %>