feat: implement modern Sınav Rapor dashboard with dual-metric delta tracking and inline mistake review
This commit is contained in:
parent
455baa6aa4
commit
f138403918
10 changed files with 2838 additions and 3 deletions
254
src/server.ts
254
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<string | undefined> {
|
||||
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<typeof d> => 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<typeof d> => 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, () => {
|
||||
|
|
|
|||
|
|
@ -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<string, ExamReportDetail> = 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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
253
src/services/exam.ts
Normal file
253
src/services/exam.ts
Normal file
|
|
@ -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<ExamType, ExamReportDetail[]> = {
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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<Array<{ id: string; name: string }>> {
|
||||
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<ExamReportDetail | null> {
|
||||
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<ExamQuestionItem[]> {
|
||||
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<ExamTopicWeakness[]> {
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string, ExamReportDetail>;
|
||||
topicWeaknesses?: Record<string, ExamTopicWeakness[]>;
|
||||
}
|
||||
|
||||
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 {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue