1053 lines
31 KiB
TypeScript
1053 lines
31 KiB
TypeScript
import express, { Request, Response, NextFunction } from 'express';
|
||
import session from 'express-session';
|
||
import cookieParser from 'cookie-parser';
|
||
import path from 'path';
|
||
import dotenv from 'dotenv';
|
||
import { ScraperService } from './services/scraper';
|
||
import { LocalDatabase } from './services/db';
|
||
import { InsightService } from './services/insight';
|
||
import { SyllabusService, DAY_NAMES } from './services/syllabus';
|
||
import { ExamService } from './services/exam';
|
||
import { Assignment } from './types';
|
||
|
||
dotenv.config();
|
||
|
||
const app = express();
|
||
const PORT = process.env.PORT || 3000;
|
||
const SESSION_SECRET = process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
|
||
|
||
// View engine setup
|
||
app.set('view engine', 'ejs');
|
||
// Support running from both ts-node (src/../views) and dist (dist/views)
|
||
const viewsPath = path.resolve(__dirname, '../views');
|
||
const publicPath = path.resolve(__dirname, '../public');
|
||
app.set('views', viewsPath);
|
||
|
||
// Middleware
|
||
app.use(express.urlencoded({ extended: true }));
|
||
app.use(express.json());
|
||
app.use(cookieParser());
|
||
|
||
// Custom Service Worker route with proper scope and no-cache headers
|
||
app.get('/sw.js', (req: Request, res: Response) => {
|
||
res.setHeader('Service-Worker-Allowed', '/');
|
||
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
||
res.sendFile(path.resolve(publicPath, 'sw.js'));
|
||
});
|
||
|
||
// Lightweight network / connectivity health probe
|
||
app.get('/api/health', (req: Request, res: Response) => {
|
||
res.json({ status: 'ok', timestamp: Date.now() });
|
||
});
|
||
|
||
app.use(express.static(publicPath));
|
||
|
||
app.use(
|
||
session({
|
||
secret: SESSION_SECRET,
|
||
resave: false,
|
||
saveUninitialized: false,
|
||
cookie: {
|
||
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days
|
||
}
|
||
})
|
||
);
|
||
|
||
// Augment express-session
|
||
declare module 'express-session' {
|
||
interface SessionData {
|
||
studentId?: string;
|
||
portalCookies?: string;
|
||
studentName?: string;
|
||
}
|
||
}
|
||
|
||
const db = LocalDatabase.getInstance();
|
||
|
||
// Auth guard helper
|
||
function requireAuth(req: Request, res: Response, next: NextFunction) {
|
||
if (req.session && req.session.studentId) {
|
||
return next();
|
||
}
|
||
// Check if studentId remembered in cookie
|
||
const rememberedId = req.cookies.bekultur_student_id;
|
||
if (rememberedId) {
|
||
const creds = db.getRememberedCredentials(rememberedId);
|
||
if (creds) {
|
||
// Auto re-login in background
|
||
ScraperService.login(creds.studentId, creds.password).then(loginRes => {
|
||
if (loginRes.success) {
|
||
req.session.studentId = creds.studentId;
|
||
req.session.portalCookies = loginRes.cookies;
|
||
req.session.studentName = loginRes.studentName;
|
||
return next();
|
||
} else {
|
||
res.clearCookie('bekultur_student_id');
|
||
return res.redirect('/');
|
||
}
|
||
}).catch(() => {
|
||
return res.redirect('/');
|
||
});
|
||
return;
|
||
}
|
||
}
|
||
res.redirect('/');
|
||
}
|
||
|
||
// ----------------------------------------------------
|
||
// Routes
|
||
// ----------------------------------------------------
|
||
|
||
/**
|
||
* GET /
|
||
* Login Page
|
||
*/
|
||
app.get('/', (req: Request, res: Response) => {
|
||
if (req.session && req.session.studentId) {
|
||
return res.redirect('/dashboard');
|
||
}
|
||
|
||
const rememberedId = req.cookies.bekultur_student_id || '';
|
||
const error = (req.query.error as string) || null;
|
||
|
||
res.render('login', {
|
||
error,
|
||
rememberedId,
|
||
title: 'Login - BeKultur (Better E-Kultur)'
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /login
|
||
* Authenticate against portal and scrape recent assignments
|
||
*/
|
||
app.post('/login', async (req: Request, res: Response) => {
|
||
const { studentId, password, rememberMe } = req.body;
|
||
|
||
if (!studentId || !password) {
|
||
return res.render('login', {
|
||
error: 'Please enter both Student ID and Password.',
|
||
rememberedId: studentId || '',
|
||
title: 'Login - BeKultur'
|
||
});
|
||
}
|
||
|
||
try {
|
||
const loginRes = await ScraperService.login(studentId, password);
|
||
|
||
if (!loginRes.success) {
|
||
return res.render('login', {
|
||
error: loginRes.error || 'Authentication failed. Please check your credentials.',
|
||
rememberedId: studentId,
|
||
title: 'Login - BeKultur'
|
||
});
|
||
}
|
||
|
||
req.session.studentId = studentId;
|
||
req.session.portalCookies = loginRes.cookies;
|
||
req.session.studentName = loginRes.studentName;
|
||
|
||
// Handle "Remember Me"
|
||
if (rememberMe) {
|
||
db.saveCredentials(studentId, password);
|
||
res.cookie('bekultur_student_id', studentId, {
|
||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||
httpOnly: true
|
||
});
|
||
} else {
|
||
db.clearCredentials(studentId);
|
||
res.clearCookie('bekultur_student_id');
|
||
}
|
||
|
||
// Scrape recent pages (1-2)
|
||
try {
|
||
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, studentId, 2);
|
||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||
} catch (scrapeErr: any) {
|
||
console.warn('Initial scrape warning (cached data will be used if available):', scrapeErr.message);
|
||
}
|
||
|
||
res.redirect('/dashboard');
|
||
} catch (err: any) {
|
||
console.error('Login route error:', err);
|
||
res.render('login', {
|
||
error: 'An unexpected server error occurred during login.',
|
||
rememberedId: studentId,
|
||
title: 'Login - BeKultur'
|
||
});
|
||
}
|
||
});
|
||
|
||
/**
|
||
* POST /logout
|
||
*/
|
||
app.post('/logout', (req: Request, res: Response) => {
|
||
req.session.destroy(() => {
|
||
res.redirect('/');
|
||
});
|
||
});
|
||
|
||
/**
|
||
* GET /logout (convenience)
|
||
*/
|
||
app.get('/logout', (req: Request, res: Response) => {
|
||
req.session.destroy(() => {
|
||
res.redirect('/');
|
||
});
|
||
});
|
||
|
||
/**
|
||
* GET /dashboard
|
||
* English dashboard with stats and checkable assignments
|
||
*/
|
||
app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const studentStore = db.getStudentStore(studentId);
|
||
|
||
// Recalculate status for each assignment relative to current date
|
||
const rawList = Object.values(studentStore.assignments);
|
||
const updatedAssignments: Assignment[] = rawList.map(item => {
|
||
const status = InsightService.computeStatus(item);
|
||
return {
|
||
...item,
|
||
status
|
||
};
|
||
});
|
||
|
||
// Calculate statistics
|
||
const stats = InsightService.calculateStats(updatedAssignments);
|
||
|
||
// Unique list of subjects for filter
|
||
const subjects = Array.from(new Set(updatedAssignments.map(a => a.subject))).sort();
|
||
|
||
// Sort assignments:
|
||
// 1. Not completed first
|
||
// 2. Priority: next-week & due-soon first, then active, then overdue, then completed
|
||
const statusPriority: Record<string, number> = {
|
||
'due-soon': 1,
|
||
'next-week': 2,
|
||
'active': 3,
|
||
'future': 4,
|
||
'overdue': 5,
|
||
'completed': 6
|
||
};
|
||
|
||
updatedAssignments.sort((a, b) => {
|
||
const pA = statusPriority[a.status] || 99;
|
||
const pB = statusPriority[b.status] || 99;
|
||
if (pA !== pB) return pA - pB;
|
||
// secondary sort by end date descending
|
||
return (b.parsedEndDate || '').localeCompare(a.parsedEndDate || '');
|
||
});
|
||
|
||
res.render('dashboard', {
|
||
title: 'Dashboard - BeKultur',
|
||
studentId,
|
||
studentName: req.session.studentName || `Student ${studentId}`,
|
||
lastSynced: studentStore.lastSynced,
|
||
stats,
|
||
assignments: updatedAssignments,
|
||
subjects
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /api/toggle
|
||
* Toggle assignment completion state
|
||
*/
|
||
app.post('/api/toggle', requireAuth, (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const { assignmentId, completed } = req.body;
|
||
|
||
if (!assignmentId) {
|
||
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
|
||
}
|
||
|
||
const updated = db.toggleAssignment(studentId, assignmentId, completed);
|
||
if (!updated) {
|
||
return res.status(404).json({ success: false, error: 'Assignment not found' });
|
||
}
|
||
|
||
// Recalculate fresh stats
|
||
const studentStore = db.getStudentStore(studentId);
|
||
const list = Object.values(studentStore.assignments).map(a => ({
|
||
...a,
|
||
status: InsightService.computeStatus(a)
|
||
}));
|
||
const stats = InsightService.calculateStats(list);
|
||
|
||
res.json({
|
||
success: true,
|
||
assignment: updated,
|
||
stats
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /api/exclude
|
||
* Toggle assignment disinclude/exclude state
|
||
*/
|
||
app.post('/api/exclude', requireAuth, (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const { assignmentId, excluded } = req.body;
|
||
|
||
if (!assignmentId) {
|
||
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
|
||
}
|
||
|
||
const updated = db.toggleExcludeAssignment(studentId, assignmentId, excluded);
|
||
if (!updated) {
|
||
return res.status(404).json({ success: false, error: 'Assignment not found' });
|
||
}
|
||
|
||
const studentStore = db.getStudentStore(studentId);
|
||
const list = Object.values(studentStore.assignments).map(a => ({
|
||
...a,
|
||
status: InsightService.computeStatus(a)
|
||
}));
|
||
const stats = InsightService.calculateStats(list);
|
||
|
||
res.json({
|
||
success: true,
|
||
assignment: updated,
|
||
stats
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /api/sync
|
||
* Sync recent pages (1-2)
|
||
*/
|
||
app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
let cookies = req.session.portalCookies;
|
||
|
||
try {
|
||
// If session cookies missing, attempt re-login using remembered credentials
|
||
if (!cookies) {
|
||
const creds = db.getRememberedCredentials(studentId);
|
||
if (creds) {
|
||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||
if (loginRes.success) {
|
||
cookies = loginRes.cookies;
|
||
req.session.portalCookies = cookies;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!cookies) {
|
||
return res.status(401).json({
|
||
success: false,
|
||
error: 'Session expired. Please log in again to sync.'
|
||
});
|
||
}
|
||
|
||
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2);
|
||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||
|
||
const store = db.getStudentStore(studentId);
|
||
const list = Object.values(store.assignments).map(a => ({
|
||
...a,
|
||
status: InsightService.computeStatus(a)
|
||
}));
|
||
const stats = InsightService.calculateStats(list);
|
||
|
||
res.json({
|
||
success: true,
|
||
count: scrapeRes.assignments.length,
|
||
lastSynced: store.lastSynced,
|
||
stats
|
||
});
|
||
} catch (err: any) {
|
||
console.error('API sync error:', err.message);
|
||
res.status(500).json({
|
||
success: false,
|
||
error: `Sync failed: ${err.message}`
|
||
});
|
||
}
|
||
});
|
||
|
||
/**
|
||
* POST /api/sync-all
|
||
* Sync all historical pages (pages 1 to 7+)
|
||
*/
|
||
app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
let cookies = req.session.portalCookies;
|
||
|
||
try {
|
||
if (!cookies) {
|
||
const creds = db.getRememberedCredentials(studentId);
|
||
if (creds) {
|
||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||
if (loginRes.success) {
|
||
cookies = loginRes.cookies;
|
||
req.session.portalCookies = cookies;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!cookies) {
|
||
return res.status(401).json({
|
||
success: false,
|
||
error: 'Session expired. Please log in again to sync full history.'
|
||
});
|
||
}
|
||
|
||
// Scrape up to 20 pages (portal currently has ~7 pages)
|
||
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 20);
|
||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||
|
||
const store = db.getStudentStore(studentId);
|
||
const list = Object.values(store.assignments).map(a => ({
|
||
...a,
|
||
status: InsightService.computeStatus(a)
|
||
}));
|
||
const stats = InsightService.calculateStats(list);
|
||
|
||
res.json({
|
||
success: true,
|
||
count: scrapeRes.assignments.length,
|
||
totalPages: scrapeRes.totalPages,
|
||
lastSynced: store.lastSynced,
|
||
stats
|
||
});
|
||
} catch (err: any) {
|
||
console.error('API sync-all error:', err.message);
|
||
res.status(500).json({
|
||
success: false,
|
||
error: `Full history sync failed: ${err.message}`
|
||
});
|
||
}
|
||
});
|
||
|
||
/**
|
||
* GET /syllabus
|
||
* Syllabus (Ders Programı) View with station filtering & weekly updates
|
||
*/
|
||
app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const currentWeek = SyllabusService.getWeekMetadata();
|
||
|
||
let syllabusStore = db.getSyllabus(studentId);
|
||
|
||
// If syllabus missing or belongs to an older week, auto-sync from portal!
|
||
if (!syllabusStore || !syllabusStore.weekId || syllabusStore.weekId !== currentWeek.weekId) {
|
||
let cookies = req.session.portalCookies;
|
||
if (!cookies) {
|
||
const creds = db.getRememberedCredentials(studentId);
|
||
if (creds) {
|
||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||
if (loginRes.success) {
|
||
cookies = loginRes.cookies;
|
||
req.session.portalCookies = cookies;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (cookies) {
|
||
try {
|
||
const schedule = await ScraperService.scrapeSyllabus(cookies);
|
||
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
|
||
syllabusStore = db.getSyllabus(studentId);
|
||
} catch (err: any) {
|
||
console.error('Failed auto-syncing weekly syllabus:', err.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Selected station (default to İst-4 if not chosen yet)
|
||
const selectedStation = syllabusStore?.selectedStation || 'İst-4';
|
||
const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId);
|
||
|
||
// Active day: 1 = Mon .. 5 = Fri (if weekend, default to Mon)
|
||
const todayDay = new Date().getDay();
|
||
const defaultDay = todayDay >= 1 && todayDay <= 5 ? todayDay : 1;
|
||
const activeDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay;
|
||
|
||
// Compute filtered schedule for selected station & advisory teacher
|
||
const rawSchedule = syllabusStore?.schedule || {};
|
||
const filteredSchedule: Record<number, any[]> = {};
|
||
for (let d = 1; d <= 5; d++) {
|
||
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation, advisoryTeacher);
|
||
}
|
||
|
||
const currentStatus = SyllabusService.getCurrentLessonStatus(
|
||
filteredSchedule[activeDay] || [],
|
||
activeDay
|
||
);
|
||
|
||
res.render('syllabus', {
|
||
title: 'Syllabus - BeKultur',
|
||
studentId,
|
||
weekId: currentWeek.weekId,
|
||
weekRange: currentWeek.weekRange,
|
||
selectedStation,
|
||
advisoryTeacher,
|
||
activeDay,
|
||
filteredSchedule,
|
||
currentStatus,
|
||
lastSynced: syllabusStore?.lastSynced || null,
|
||
DAY_NAMES
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /api/syllabus/station
|
||
* Update selected station
|
||
*/
|
||
app.post('/api/syllabus/station', requireAuth, (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const { station } = req.body;
|
||
|
||
db.setStudentStation(studentId, station || null);
|
||
const syllabusStore = db.getSyllabus(studentId);
|
||
const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId);
|
||
|
||
const rawSchedule = syllabusStore?.schedule || {};
|
||
const filteredSchedule: Record<number, any[]> = {};
|
||
for (let d = 1; d <= 5; d++) {
|
||
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null, advisoryTeacher);
|
||
}
|
||
|
||
res.json({
|
||
success: true,
|
||
selectedStation: station,
|
||
advisoryTeacher,
|
||
filteredSchedule
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /api/syllabus/advisory-teacher
|
||
* Update assigned advisory (Danışmanlık) teacher
|
||
*/
|
||
app.post('/api/syllabus/advisory-teacher', requireAuth, (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const { teacher } = req.body;
|
||
|
||
db.setStudentAdvisoryTeacher(studentId, teacher || null);
|
||
const syllabusStore = db.getSyllabus(studentId);
|
||
const selectedStation = syllabusStore?.selectedStation || 'İst-4';
|
||
|
||
const rawSchedule = syllabusStore?.schedule || {};
|
||
const filteredSchedule: Record<number, any[]> = {};
|
||
for (let d = 1; d <= 5; d++) {
|
||
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation, teacher || null);
|
||
}
|
||
|
||
res.json({
|
||
success: true,
|
||
advisoryTeacher: teacher,
|
||
filteredSchedule
|
||
});
|
||
});
|
||
|
||
/**
|
||
* POST /api/syllabus/sync
|
||
* Manually refresh syllabus across all 5 days from portal
|
||
*/
|
||
app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
let cookies = req.session.portalCookies;
|
||
|
||
try {
|
||
if (!cookies) {
|
||
const creds = db.getRememberedCredentials(studentId);
|
||
if (creds) {
|
||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||
if (loginRes.success) {
|
||
cookies = loginRes.cookies;
|
||
req.session.portalCookies = cookies;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!cookies) {
|
||
return res.status(401).json({
|
||
success: false,
|
||
error: 'Session expired. Please log in again to sync syllabus.'
|
||
});
|
||
}
|
||
|
||
const currentWeek = SyllabusService.getWeekMetadata();
|
||
const schedule = await ScraperService.scrapeSyllabus(cookies);
|
||
db.saveSyllabus(studentId, currentWeek.weekId, currentWeek.weekRange, schedule);
|
||
|
||
const store = db.getSyllabus(studentId);
|
||
const selectedStation = store?.selectedStation || 'İst-4';
|
||
const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId);
|
||
|
||
const filteredSchedule: Record<number, any[]> = {};
|
||
for (let d = 1; d <= 5; d++) {
|
||
filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation, advisoryTeacher);
|
||
}
|
||
|
||
res.json({
|
||
success: true,
|
||
weekId: currentWeek.weekId,
|
||
weekRange: currentWeek.weekRange,
|
||
lastSynced: store?.lastSynced,
|
||
advisoryTeacher,
|
||
filteredSchedule
|
||
});
|
||
} catch (err: any) {
|
||
console.error('API syllabus sync error:', err.message);
|
||
res.status(500).json({
|
||
success: false,
|
||
error: `Syllabus sync failed: ${err.message}`
|
||
});
|
||
}
|
||
});
|
||
|
||
// ----------------------------------------------------
|
||
// Private Lessons (Özel Ders & İstek) Routes
|
||
// ----------------------------------------------------
|
||
|
||
/**
|
||
* GET /private-lessons
|
||
* Private lessons overview (application form + scheduled lessons)
|
||
*/
|
||
app.get('/private-lessons', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
let store = db.getPrivateLessons(studentId);
|
||
|
||
// If not yet synced or formMeta missing, try auto-syncing
|
||
if (!store || !store.lessons || !store.formMeta) {
|
||
let cookies = req.session.portalCookies;
|
||
if (!cookies) {
|
||
const creds = db.getRememberedCredentials(studentId);
|
||
if (creds) {
|
||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||
if (loginRes.success) {
|
||
cookies = loginRes.cookies;
|
||
req.session.portalCookies = cookies;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (cookies) {
|
||
try {
|
||
const [privateRes, formMeta] = await Promise.all([
|
||
ScraperService.scrapePrivateLessons(cookies),
|
||
ScraperService.fetchPrivateLessonFormMeta(studentId)
|
||
]);
|
||
|
||
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
|
||
store = db.getPrivateLessons(studentId);
|
||
} catch (err: any) {
|
||
console.error('Error auto-syncing private lessons:', err.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
const allLessons = store?.lessons || [];
|
||
const upcomingLessons = allLessons.filter(l => l.isUpcoming);
|
||
const pastLessons = allLessons.filter(l => !l.isUpcoming);
|
||
|
||
// Unique subjects for filter
|
||
const subjects = Array.from(new Set(allLessons.map(l => l.subject))).sort();
|
||
|
||
res.render('private-lessons', {
|
||
title: 'Private Lessons - BeKultur',
|
||
studentId,
|
||
studentName: req.session.studentName || store?.formMeta?.studentName || `Student ${studentId}`,
|
||
formMeta: store?.formMeta || null,
|
||
detectedAdvisor: store?.detectedAdvisor || db.getStudentAdvisoryTeacher(studentId) || null,
|
||
lastSynced: store?.lastSynced || null,
|
||
allLessons,
|
||
upcomingLessons,
|
||
pastLessons,
|
||
subjects
|
||
});
|
||
});
|
||
|
||
/**
|
||
* Redirect shortcuts
|
||
*/
|
||
app.get('/ozelders', (req: Request, res: Response) => res.redirect('/private-lessons'));
|
||
app.get('/ozeldersistek', (req: Request, res: Response) => res.redirect('/private-lessons'));
|
||
|
||
/**
|
||
* GET /api/private-lessons/units
|
||
* Dynamic units for course
|
||
*/
|
||
app.get('/api/private-lessons/units', requireAuth, async (req: Request, res: Response) => {
|
||
const dersId = req.query.dersId as string;
|
||
const sinifId = req.query.sinifId as string;
|
||
|
||
if (!dersId || !sinifId) {
|
||
return res.status(400).json({ success: false, error: 'dersId and sinifId are required' });
|
||
}
|
||
|
||
try {
|
||
const units = await ScraperService.fetchUnits(dersId, sinifId);
|
||
res.json({ success: true, units });
|
||
} catch (err: any) {
|
||
res.status(500).json({ success: false, error: err.message });
|
||
}
|
||
});
|
||
|
||
/**
|
||
* GET /api/private-lessons/topics
|
||
* Dynamic topics for unit
|
||
*/
|
||
app.get('/api/private-lessons/topics', requireAuth, async (req: Request, res: Response) => {
|
||
const uniteId = req.query.uniteId as string;
|
||
|
||
if (!uniteId) {
|
||
return res.status(400).json({ success: false, error: 'uniteId is required' });
|
||
}
|
||
|
||
try {
|
||
const topics = await ScraperService.fetchTopics(uniteId);
|
||
res.json({ success: true, topics });
|
||
} catch (err: any) {
|
||
res.status(500).json({ success: false, error: err.message });
|
||
}
|
||
});
|
||
|
||
/**
|
||
* POST /api/private-lessons/request
|
||
* Submit request to bilgi portal
|
||
*/
|
||
app.post('/api/private-lessons/request', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
const { ogrenciDonemId, okulId, sinifId, dersId, uniteId, konuId } = req.body;
|
||
|
||
if (!dersId || !uniteId || !konuId) {
|
||
return res.status(400).json({ success: false, message: 'Lütfen ders, ünite ve konu seçiniz.' });
|
||
}
|
||
|
||
try {
|
||
const result = await ScraperService.submitPrivateLessonRequest(studentId, {
|
||
ogrenciDonemId: ogrenciDonemId || '',
|
||
okulId: okulId || '',
|
||
sinifId: sinifId || '',
|
||
dersId,
|
||
uniteId,
|
||
konuId
|
||
});
|
||
|
||
res.json(result);
|
||
} catch (err: any) {
|
||
res.status(500).json({ success: false, message: err.message || 'Başvuru gönderilemedi.' });
|
||
}
|
||
});
|
||
|
||
/**
|
||
* POST /api/private-lessons/sync
|
||
* Manually refresh private lessons and form meta
|
||
*/
|
||
app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Response) => {
|
||
const studentId = req.session.studentId!;
|
||
let cookies = req.session.portalCookies;
|
||
|
||
try {
|
||
if (!cookies) {
|
||
const creds = db.getRememberedCredentials(studentId);
|
||
if (creds) {
|
||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||
if (loginRes.success) {
|
||
cookies = loginRes.cookies;
|
||
req.session.portalCookies = cookies;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!cookies) {
|
||
return res.status(401).json({
|
||
success: false,
|
||
error: 'Session expired. Please log in again to sync private lessons.'
|
||
});
|
||
}
|
||
|
||
const [privateRes, formMeta] = await Promise.all([
|
||
ScraperService.scrapePrivateLessons(cookies),
|
||
ScraperService.fetchPrivateLessonFormMeta(studentId)
|
||
]);
|
||
|
||
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
|
||
const store = db.getPrivateLessons(studentId);
|
||
|
||
res.json({
|
||
success: true,
|
||
count: privateRes.lessons.length,
|
||
detectedAdvisor: privateRes.detectedAdvisor,
|
||
lastSynced: store?.lastSynced,
|
||
lessons: privateRes.lessons
|
||
});
|
||
} catch (err: any) {
|
||
console.error('API private-lessons sync error:', err.message);
|
||
res.status(500).json({
|
||
success: false,
|
||
error: `Private lessons sync failed: ${err.message}`
|
||
});
|
||
}
|
||
});
|
||
|
||
// ----------------------------------------------------
|
||
// 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, () => {
|
||
console.log(`=========================================`);
|
||
console.log(` BeKultur (Better E-Kultur) Server`);
|
||
console.log(` Running at: http://localhost:${PORT}`);
|
||
console.log(`=========================================`);
|
||
});
|
||
}
|
||
|
||
export default app;
|