Add Private Lessons (Özel Ders İstek) page and advisory teacher filtering in Syllabus

This commit is contained in:
tyuXX 2026-10-21 19:22:21 +00:00
parent 573a249580
commit 455baa6aa4
11 changed files with 1489 additions and 9 deletions

View file

@ -444,17 +444,18 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
// Selected station (default to İst-4 if not chosen yet)
const selectedStation = syllabusStore?.selectedStation || 'İst-4';
const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId);
// Active day: 1 = Mon .. 5 = Fri (if weekend, default to Mon)
const todayDay = new Date().getDay();
const defaultDay = todayDay >= 1 && todayDay <= 5 ? todayDay : 1;
const activeDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay;
// Compute filtered schedule for selected station
// Compute filtered schedule for selected station & advisory teacher
const rawSchedule = syllabusStore?.schedule || {};
const filteredSchedule: Record<number, any[]> = {};
for (let d = 1; d <= 5; d++) {
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation);
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], selectedStation, advisoryTeacher);
}
const currentStatus = SyllabusService.getCurrentLessonStatus(
@ -468,6 +469,7 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
weekId: currentWeek.weekId,
weekRange: currentWeek.weekRange,
selectedStation,
advisoryTeacher,
activeDay,
filteredSchedule,
currentStatus,
@ -486,16 +488,43 @@ app.post('/api/syllabus/station', requireAuth, (req: Request, res: Response) =>
db.setStudentStation(studentId, station || null);
const syllabusStore = db.getSyllabus(studentId);
const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId);
const rawSchedule = syllabusStore?.schedule || {};
const filteredSchedule: Record<number, any[]> = {};
for (let d = 1; d <= 5; d++) {
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null);
filteredSchedule[d] = SyllabusService.filterLessonsForStation(rawSchedule[d] || [], station || null, advisoryTeacher);
}
res.json({
success: true,
selectedStation: station,
advisoryTeacher,
filteredSchedule
});
});
/**
* POST /api/syllabus/advisory-teacher
* Update assigned advisory (Danışmanlık) teacher
*/
app.post('/api/syllabus/advisory-teacher', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { teacher } = req.body;
db.setStudentAdvisoryTeacher(studentId, teacher || null);
const syllabusStore = db.getSyllabus(studentId);
const selectedStation = syllabusStore?.selectedStation || 'İst-4';
const rawSchedule = syllabusStore?.schedule || {};
const filteredSchedule: Record<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
});
});
@ -533,10 +562,11 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
const store = db.getSyllabus(studentId);
const selectedStation = store?.selectedStation || 'İst-4';
const advisoryTeacher = db.getStudentAdvisoryTeacher(studentId);
const filteredSchedule: Record<number, any[]> = {};
for (let d = 1; d <= 5; d++) {
filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation);
filteredSchedule[d] = SyllabusService.filterLessonsForStation(schedule[d] || [], selectedStation, advisoryTeacher);
}
res.json({
@ -544,6 +574,7 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
weekId: currentWeek.weekId,
weekRange: currentWeek.weekRange,
lastSynced: store?.lastSynced,
advisoryTeacher,
filteredSchedule
});
} catch (err: any) {
@ -555,6 +586,192 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
}
});
// ----------------------------------------------------
// Private Lessons (Özel Ders & İstek) Routes
// ----------------------------------------------------
/**
* GET /private-lessons
* Private lessons overview (application form + scheduled lessons)
*/
app.get('/private-lessons', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let store = db.getPrivateLessons(studentId);
// If not yet synced or formMeta missing, try auto-syncing
if (!store || !store.lessons || !store.formMeta) {
let cookies = req.session.portalCookies;
if (!cookies) {
const creds = db.getRememberedCredentials(studentId);
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (cookies) {
try {
const [privateRes, formMeta] = await Promise.all([
ScraperService.scrapePrivateLessons(cookies),
ScraperService.fetchPrivateLessonFormMeta(studentId)
]);
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
store = db.getPrivateLessons(studentId);
} catch (err: any) {
console.error('Error auto-syncing private lessons:', err.message);
}
}
}
const allLessons = store?.lessons || [];
const upcomingLessons = allLessons.filter(l => l.isUpcoming);
const pastLessons = allLessons.filter(l => !l.isUpcoming);
// Unique subjects for filter
const subjects = Array.from(new Set(allLessons.map(l => l.subject))).sort();
res.render('private-lessons', {
title: 'Private Lessons - BeKultur',
studentId,
studentName: req.session.studentName || store?.formMeta?.studentName || `Student ${studentId}`,
formMeta: store?.formMeta || null,
detectedAdvisor: store?.detectedAdvisor || db.getStudentAdvisoryTeacher(studentId) || null,
lastSynced: store?.lastSynced || null,
allLessons,
upcomingLessons,
pastLessons,
subjects
});
});
/**
* Redirect shortcuts
*/
app.get('/ozelders', (req: Request, res: Response) => res.redirect('/private-lessons'));
app.get('/ozeldersistek', (req: Request, res: Response) => res.redirect('/private-lessons'));
/**
* GET /api/private-lessons/units
* Dynamic units for course
*/
app.get('/api/private-lessons/units', requireAuth, async (req: Request, res: Response) => {
const dersId = req.query.dersId as string;
const sinifId = req.query.sinifId as string;
if (!dersId || !sinifId) {
return res.status(400).json({ success: false, error: 'dersId and sinifId are required' });
}
try {
const units = await ScraperService.fetchUnits(dersId, sinifId);
res.json({ success: true, units });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
/**
* GET /api/private-lessons/topics
* Dynamic topics for unit
*/
app.get('/api/private-lessons/topics', requireAuth, async (req: Request, res: Response) => {
const uniteId = req.query.uniteId as string;
if (!uniteId) {
return res.status(400).json({ success: false, error: 'uniteId is required' });
}
try {
const topics = await ScraperService.fetchTopics(uniteId);
res.json({ success: true, topics });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
/**
* POST /api/private-lessons/request
* Submit request to bilgi portal
*/
app.post('/api/private-lessons/request', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { ogrenciDonemId, okulId, sinifId, dersId, uniteId, konuId } = req.body;
if (!dersId || !uniteId || !konuId) {
return res.status(400).json({ success: false, message: 'Lütfen ders, ünite ve konu seçiniz.' });
}
try {
const result = await ScraperService.submitPrivateLessonRequest(studentId, {
ogrenciDonemId: ogrenciDonemId || '',
okulId: okulId || '',
sinifId: sinifId || '',
dersId,
uniteId,
konuId
});
res.json(result);
} catch (err: any) {
res.status(500).json({ success: false, message: err.message || 'Başvuru gönderilemedi.' });
}
});
/**
* POST /api/private-lessons/sync
* Manually refresh private lessons and form meta
*/
app.post('/api/private-lessons/sync', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let cookies = req.session.portalCookies;
try {
if (!cookies) {
const creds = db.getRememberedCredentials(studentId);
if (creds) {
const loginRes = await ScraperService.login(creds.studentId, creds.password);
if (loginRes.success) {
cookies = loginRes.cookies;
req.session.portalCookies = cookies;
}
}
}
if (!cookies) {
return res.status(401).json({
success: false,
error: 'Session expired. Please log in again to sync private lessons.'
});
}
const [privateRes, formMeta] = await Promise.all([
ScraperService.scrapePrivateLessons(cookies),
ScraperService.fetchPrivateLessonFormMeta(studentId)
]);
db.savePrivateLessons(studentId, privateRes.lessons, formMeta || undefined, privateRes.detectedAdvisor);
const store = db.getPrivateLessons(studentId);
res.json({
success: true,
count: privateRes.lessons.length,
detectedAdvisor: privateRes.detectedAdvisor,
lastSynced: store?.lastSynced,
lessons: privateRes.lessons
});
} catch (err: any) {
console.error('API private-lessons sync error:', err.message);
res.status(500).json({
success: false,
error: `Private lessons sync failed: ${err.message}`
});
}
});
// Start Server
if (process.env.NODE_ENV !== 'test') {
app.listen(PORT, () => {

View file

@ -1,6 +1,6 @@
import fs from 'fs';
import path from 'path';
import { DatabaseSchema, StudentStore, Assignment } from '../types';
import { DatabaseSchema, StudentStore, Assignment, PrivateLesson, PrivateLessonFormMeta, PrivateLessonsStore } from '../types';
const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json');
@ -182,4 +182,49 @@ export class LocalDatabase {
const student = this.cache.students[studentId];
return student?.syllabus || null;
}
public savePrivateLessons(
studentId: string,
lessons: PrivateLesson[],
formMeta?: PrivateLessonFormMeta,
detectedAdvisor?: string
): void {
const student = this.getStudentStore(studentId);
const existing = student.privateLessons;
student.privateLessons = {
lastSynced: new Date().toISOString(),
lessons,
formMeta: formMeta || existing?.formMeta,
detectedAdvisor: detectedAdvisor || existing?.detectedAdvisor
};
if (detectedAdvisor && !student.advisoryTeacher) {
student.advisoryTeacher = detectedAdvisor;
if (student.syllabus) {
student.syllabus.advisoryTeacher = detectedAdvisor;
}
}
this.save();
}
public getPrivateLessons(studentId: string): PrivateLessonsStore | null {
const student = this.cache.students[studentId];
return student?.privateLessons || null;
}
public setStudentAdvisoryTeacher(studentId: string, teacher: string | null): void {
const student = this.getStudentStore(studentId);
student.advisoryTeacher = teacher;
if (student.syllabus) {
student.syllabus.advisoryTeacher = teacher;
}
this.save();
}
public getStudentAdvisoryTeacher(studentId: string): string | null {
const student = this.cache.students[studentId];
return student?.advisoryTeacher || student?.privateLessons?.detectedAdvisor || null;
}
}

View file

@ -1,11 +1,12 @@
import axios from 'axios';
import * as cheerio from 'cheerio';
import crypto from 'crypto';
import { Assignment, Lesson } from '../types';
import { Assignment, Lesson, PrivateLesson, PrivateLessonFormMeta } from '../types';
import { InsightService } from './insight';
import { DAY_NAMES } from './syllabus';
const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com';
const BILGI_BASE_URL = 'https://bilgi.ozelbursakulturokullari.com';
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
export interface LoginResult {
@ -391,4 +392,273 @@ export class ScraperService {
return weeklySchedule;
}
/**
* Scrape scheduled private lessons (Özel Ders) and detect assigned advisor teacher
*/
public static async scrapePrivateLessons(
cookies: string
): Promise<{ lessons: PrivateLesson[]; detectedAdvisor?: string }> {
const lessons: PrivateLesson[] = [];
const seenLessonKeys = new Set<string>();
let detectedAdvisor: string | undefined;
const client = axios.create({
baseURL: BASE_URL,
headers: {
'User-Agent': USER_AGENT,
'Cookie': cookies
},
validateStatus: () => true
});
let currentPage = 1;
let maxPages = 1;
const visitedPages = new Set<number>();
while (currentPage <= maxPages && !visitedPages.has(currentPage)) {
visitedPages.add(currentPage);
const url = currentPage === 1 ? '/ozelders' : `/OzelDers?sayfa=${currentPage}`;
try {
const res = await client.get(url);
if (res.status !== 200 || !res.data) break;
const $ = cheerio.load(res.data);
// Find pagination links
$('a[href*="sayfa="]').each((_, a) => {
const href = $(a).attr('href') || '';
const match = href.match(/sayfa=(\d+)/);
if (match) {
const p = parseInt(match[1], 10);
if (p > maxPages) maxPages = p;
}
});
// Each private lesson is in .kltr-card inside .col-md-8
$('.col-md-8 .kltr-card').each((_, cardEl) => {
const card = $(cardEl);
const subject = card.find('h5.my-1').text().trim();
const pElements = card.find('p.my-1');
const teacherName = pElements.eq(0).text().trim();
const dateStr = pElements.eq(1).text().trim(); // e.g. "26.10.2026"
const teacherPhoto = card.find('img.profil-resmi').attr('src') || '';
if (!subject || !teacherName || !dateStr) return;
const key = `${subject}|${teacherName}|${dateStr}`;
if (seenLessonKeys.has(key)) return;
seenLessonKeys.add(key);
const parsedObj = InsightService.parsePortalDate(dateStr);
const parsedDate = InsightService.toISODate(parsedObj) || '';
// Check if upcoming: has border-success class OR date is in future/today
const hasSuccessBorder = card.hasClass('border-success') || (card.attr('class') || '').includes('border-success');
const isDateUpcoming = parsedObj ? parsedObj.getTime() >= new Date().setHours(0, 0, 0, 0) : false;
const isUpcoming = hasSuccessBorder || isDateUpcoming;
const id = crypto.createHash('sha256').update(key).digest('hex').slice(0, 16);
lessons.push({
id,
subject,
teacherName,
teacherPhoto,
date: dateStr,
parsedDate,
isUpcoming
});
// Check if Danışmanlık to detect assigned advisor
if (/dan[ıi]şmanl[ıi]k/i.test(subject) && !detectedAdvisor) {
detectedAdvisor = teacherName;
}
});
currentPage++;
} catch (err: any) {
console.error(`Error scraping private lessons page ${currentPage}:`, err.message);
break;
}
}
return { lessons, detectedAdvisor };
}
/**
* Fetch form metadata and course options for Private Lesson Request from bilgi portal
*/
public static async fetchPrivateLessonFormMeta(studentId: string): Promise<PrivateLessonFormMeta | null> {
try {
const client = axios.create({
headers: { 'User-Agent': USER_AGENT },
validateStatus: () => true
});
const res = await client.get(`${BILGI_BASE_URL}/ozeldersistek?Id=${encodeURIComponent(studentId)}`);
if (res.status !== 200 || !res.data) return null;
const $ = cheerio.load(res.data);
const studentName = $('.alert-info h5').text().trim();
const pTags = $('.alert-info p');
const schoolName = pTags.eq(1).text().trim();
const className = pTags.eq(2).text().trim();
const photoUrl = $('.alert-info img.profil-resmi').attr('src') || undefined;
const ogrenciDonemId = ($('input#OgrenciDonemId').val() as string) || '';
const okulId = ($('input#OkulId').val() as string) || '';
const sinifId = ($('input#SinifId').val() as string) || '';
const courses: Array<{ id: string; name: string }> = [];
$('select#DersId option').each((_, opt) => {
const val = $(opt).attr('value');
const text = $(opt).text().trim();
if (val) {
courses.push({ id: val, name: text });
}
});
return {
studentName,
schoolName,
className,
photoUrl,
ogrenciDonemId,
okulId,
sinifId,
courses
};
} catch (err: any) {
console.error('Failed to fetch private lesson form meta:', err.message);
return null;
}
}
/**
* Fetch units for a course and class from bilgi portal over HTTPS
*/
public static async fetchUnits(dersId: string, sinifId: string): Promise<Array<{ id: string; name: string }>> {
try {
const res = await axios.post(
`${BILGI_BASE_URL}/ortak/dersuniteler`,
new URLSearchParams({ id: dersId, sinifId }).toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': USER_AGENT
}
}
);
const $ = cheerio.load(res.data || '');
const units: Array<{ id: string; name: string }> = [];
$('option').each((_, opt) => {
const val = $(opt).attr('value');
const text = $(opt).text().trim();
if (val) {
units.push({ id: val, name: text });
}
});
return units;
} catch (err: any) {
console.error('Failed to fetch units:', err.message);
return [];
}
}
/**
* Fetch topics for a unit from bilgi portal over HTTPS
*/
public static async fetchTopics(uniteId: string): Promise<Array<{ id: string; name: string }>> {
try {
const res = await axios.post(
`${BILGI_BASE_URL}/ortak/unitekonular`,
new URLSearchParams({ id: uniteId }).toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': USER_AGENT
}
}
);
const $ = cheerio.load(res.data || '');
const topics: Array<{ id: string; name: string }> = [];
$('option').each((_, opt) => {
const val = $(opt).attr('value');
const text = $(opt).text().trim();
if (val) {
topics.push({ id: val, name: text });
}
});
return topics;
} catch (err: any) {
console.error('Failed to fetch topics:', err.message);
return [];
}
}
/**
* Submit Private Lesson Request to bilgi portal
*/
public static async submitPrivateLessonRequest(
studentId: string,
payload: {
ogrenciDonemId: string;
okulId: string;
sinifId: string;
dersId: string;
uniteId: string;
konuId: string;
}
): Promise<{ success: boolean; message: string }> {
try {
const formData = new URLSearchParams();
formData.append('OgrenciDonemId', payload.ogrenciDonemId);
formData.append('OkulId', payload.okulId);
formData.append('SinifId', payload.sinifId);
formData.append('DersId', payload.dersId);
formData.append('UniteId', payload.uniteId);
formData.append('KonuId', payload.konuId);
const res = await axios.post(
`${BILGI_BASE_URL}/ozeldersistek?Id=${encodeURIComponent(studentId)}`,
formData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': USER_AGENT
},
maxRedirects: 5,
validateStatus: () => true
}
);
if (res.status >= 200 && res.status < 400) {
const $ = cheerio.load(res.data || '');
const alertDanger = $('.alert-danger, .text-danger').text().trim();
if (alertDanger && !alertDanger.includes('ÖĞRENCİ ÖZEL DERS BAŞVURU')) {
return { success: false, message: alertDanger };
}
return {
success: true,
message: 'Talebiniz başarıyla iletildi.'
};
}
return {
success: false,
message: `Portal returned status code ${res.status}`
};
} catch (err: any) {
console.error('Failed to submit private lesson request:', err.message);
return { success: false, message: err.message || 'Submission failed' };
}
}
}

View file

@ -1,4 +1,5 @@
import { Lesson } from '../types';
import { InsightService } from './insight';
export const DAY_NAMES: Record<number, string> = {
1: 'Pazartesi',
@ -66,8 +67,13 @@ export class SyllabusService {
/**
* Filter lessons for a specific station (or show all stations without portal duplicate garbage)
* and filter advisory (Danışmanlık) lessons if an assigned advisory teacher is provided.
*/
public static filterLessonsForStation(rawLessons: Lesson[], selectedStation: string | null): Lesson[] {
public static filterLessonsForStation(
rawLessons: Lesson[],
selectedStation: string | null,
advisoryTeacher?: string | null
): Lesson[] {
if (!rawLessons || !rawLessons.length) return [];
const normTarget = this.normalizeStation(selectedStation);
@ -112,9 +118,37 @@ export class SyllabusService {
}
}
} else {
// Whole-class lesson (no stations): deduplicate if portal printed multiple copies
// Whole-class / unstationed lessons
const seenKeys = new Set<string>();
for (const cl of periodGroup) {
// Check if this period contains advisory (Danışmanlık) lessons
const advisoryLessons = periodGroup.filter(l => /dan[ıi]şmanl[ıi]k/i.test(l.subject));
const nonAdvisoryLessons = periodGroup.filter(l => !/dan[ıi]şmanl[ıi]k/i.test(l.subject));
if (advisoryLessons.length > 1 && advisoryTeacher && advisoryTeacher.trim().length > 0) {
const normAdvisor = InsightService.normalizeTurkish(advisoryTeacher.trim()).toLowerCase();
const advisorMatch = advisoryLessons.find(l => {
const normTeacher = InsightService.normalizeTurkish(l.teacher).toLowerCase();
return normTeacher.includes(normAdvisor) || normAdvisor.includes(normTeacher);
});
if (advisorMatch) {
result.push(advisorMatch);
} else {
// If student's advisor not matched, keep first unique advisory card
result.push(advisoryLessons[0]);
}
} else {
for (const al of advisoryLessons) {
const key = `${al.periodNumber}|${al.subject}|${al.teacher}|${al.time}`;
if (!seenKeys.has(key)) {
seenKeys.add(key);
result.push(al);
}
}
}
// Add non-advisory lessons for this period (deduplicating identical cards)
for (const cl of nonAdvisoryLessons) {
const key = `${cl.periodNumber}|${cl.subject}|${cl.teacher}|${cl.time}`;
if (!seenKeys.has(key)) {
seenKeys.add(key);

View file

@ -66,10 +66,42 @@ export interface SyllabusStore {
weekId: string; // e.g. "2026-W43"
weekRange: string; // e.g. "19.10.2026 - 23.10.2026"
selectedStation: string | null; // e.g. "İst-4" or null/all
advisoryTeacher?: string | null; // e.g. "CAN TÜRKOĞLU"
lastSynced: string | null;
schedule: Record<number, Lesson[]>; // day (1..5) -> raw lessons
}
// ----------------------------------------------------
// Private Lessons (Özel Ders & İstek) Types
// ----------------------------------------------------
export interface PrivateLesson {
id: string; // deterministic ID or hash
subject: string; // e.g. "Coğrafya", "Danışmanlık"
teacherName: string; // e.g. "SEVDA KILIÇOĞLU"
teacherPhoto: string; // photo URL
date: string; // e.g. "26.10.2026"
parsedDate: string; // e.g. "2026-10-26"
isUpcoming: boolean; // true if border-success / active upcoming
}
export interface PrivateLessonFormMeta {
studentName: string;
schoolName: string;
className: string;
photoUrl?: string;
ogrenciDonemId: string;
okulId: string;
sinifId: string;
courses: Array<{ id: string; name: string }>;
}
export interface PrivateLessonsStore {
lastSynced: string;
lessons: PrivateLesson[];
formMeta?: PrivateLessonFormMeta;
detectedAdvisor?: string;
}
export interface StudentStore {
studentId: string;
lastSynced: string | null;
@ -79,6 +111,8 @@ export interface StudentStore {
};
assignments: Record<string, Assignment>;
syllabus?: SyllabusStore;
advisoryTeacher?: string | null;
privateLessons?: PrivateLessonsStore;
}
export interface DatabaseSchema {