diff --git a/public/css/style.css b/public/css/style.css index 6d0e818..6498e5d 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -2241,3 +2241,84 @@ code { } } +/* ==================================================== */ +/* PWA & Offline Indicator Banner */ +/* ==================================================== */ + +.offline-banner { + width: 100%; + padding: 6px 16px; + font-size: 0.8rem; + font-weight: 500; + text-align: center; + position: sticky; + top: 0; + z-index: 200; + transition: all 0.25s ease-in-out; + display: flex; + justify-content: center; + align-items: center; +} + +.offline-banner.active { + background: #fef3c7; + color: #92400e; + border-bottom: 1px solid #fde68a; +} + +.offline-banner.online { + background: #dcfce7; + color: #166534; + border-bottom: 1px solid #bbf7d0; +} + +.offline-banner.hidden { + display: none !important; +} + +.offline-banner-content { + display: inline-flex; + align-items: center; + gap: 10px; +} + +.offline-badge-pill { + background: #fde047; + color: #713f12; + font-size: 0.7rem; + font-weight: 700; + padding: 1px 7px; + border-radius: 9999px; + text-transform: uppercase; + letter-spacing: 0.03em; +} + +.online-badge-pill { + background: #86efac; + color: #14532d; + font-size: 0.7rem; + font-weight: 700; + padding: 1px 7px; + border-radius: 9999px; + text-transform: uppercase; + letter-spacing: 0.03em; +} + +.offline-banner-text { + font-size: 0.825rem; +} + +/* Offline state modifications on buttons and checkboxes */ +.btn-offline-disabled { + opacity: 0.55 !important; + cursor: not-allowed !important; + pointer-events: none; + filter: grayscale(40%); +} + +.assignment-toggle:disabled { + cursor: not-allowed; + opacity: 0.6; +} + + diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png new file mode 100644 index 0000000..20f11bb Binary files /dev/null and b/public/icons/icon-192.png differ diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png new file mode 100644 index 0000000..2340f3a Binary files /dev/null and b/public/icons/icon-512.png differ diff --git a/public/icons/icon.svg b/public/icons/icon.svg new file mode 100644 index 0000000..8fc21ba --- /dev/null +++ b/public/icons/icon.svg @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/js/app.js b/public/js/app.js index 0599eb9..e1dcdbf 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -25,6 +25,10 @@ document.addEventListener('DOMContentLoaded', () => { // Exclude / Restore button if (target.classList.contains('btn-exclude') || target.classList.contains('btn-disinclude')) { + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + alert('Çevrimdışı moddasınız. Ödev gizleme/geri alma işlemi için internet bağlantısı gereklidir.'); + return; + } const assignmentId = target.dataset.id; const card = target.closest('.assignment-card'); if (!card) return; @@ -78,6 +82,12 @@ document.addEventListener('DOMContentLoaded', () => { const target = e.target; if (!target.classList.contains('assignment-toggle')) return; + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + target.checked = !target.checked; + alert('Çevrimdışı moddasınız. Ödev durumu internet bağlantısı olmadan değiştirilemez.'); + return; + } + const assignmentId = target.dataset.id; const isChecked = target.checked; const card = target.closest('.assignment-card'); @@ -303,6 +313,10 @@ document.addEventListener('DOMContentLoaded', () => { // Sync actions if (btnSyncRecent) { btnSyncRecent.addEventListener('click', async () => { + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + showAlert('Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.', 'danger'); + return; + } btnSyncRecent.disabled = true; btnSyncRecent.textContent = 'Syncing...'; showAlert('Fetching recent assignments...', 'info'); @@ -327,6 +341,10 @@ document.addEventListener('DOMContentLoaded', () => { if (btnSyncAll) { btnSyncAll.addEventListener('click', async () => { + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + showAlert('Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.', 'danger'); + return; + } btnSyncAll.disabled = true; btnSyncAll.textContent = 'Syncing all...'; showAlert('Syncing full history from portal...', 'info'); diff --git a/public/js/exams.js b/public/js/exams.js index 9049e92..d412d26 100644 --- a/public/js/exams.js +++ b/public/js/exams.js @@ -96,6 +96,11 @@ document.addEventListener('DOMContentLoaded', () => { // Sync Exams Action // ---------------------------------------------------- async function handleSync() { + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + showAlert('Çevrimdışı moddasınız. Sınav senkronizasyonu için internet bağlantısı gereklidir.', 'danger'); + return; + } + const triggerBtn = btnSyncExams || btnEmptySync; if (triggerBtn) { triggerBtn.disabled = true; diff --git a/public/js/private-lessons.js b/public/js/private-lessons.js index 208643a..361bcf9 100644 --- a/public/js/private-lessons.js +++ b/public/js/private-lessons.js @@ -123,6 +123,11 @@ document.addEventListener('DOMContentLoaded', () => { e.preventDefault(); hideFeedback(); + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + showFeedback('Çevrimdışı moddasınız. Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.', 'error'); + return; + } + const ogrenciDonemId = document.getElementById('ogrenciDonemId')?.value || ''; const okulId = document.getElementById('okulId')?.value || ''; const sinifId = document.getElementById('sinifId')?.value || ''; diff --git a/public/js/pwa.js b/public/js/pwa.js new file mode 100644 index 0000000..0ddc7ea --- /dev/null +++ b/public/js/pwa.js @@ -0,0 +1,209 @@ +/** + * BeKultur - PWA & Offline State Manager + */ +(function () { + let isOffline = !navigator.onLine; + + // 1. Service Worker Registration + if ('serviceWorker' in navigator) { + window.addEventListener('load', () => { + navigator.serviceWorker + .register('/sw.js', { scope: '/' }) + .then((reg) => { + // If updated service worker found + reg.addEventListener('updatefound', () => { + const installing = reg.installing; + if (installing) { + installing.addEventListener('statechange', () => { + if (installing.state === 'installed' && navigator.serviceWorker.controller) { + console.log('New BeKultur version available.'); + } + }); + } + }); + }) + .catch((err) => { + console.warn('ServiceWorker registration failed:', err); + }); + }); + } + + // 2. Offline Banner Component + function getOrCreateBanner() { + let banner = document.getElementById('offlineBanner'); + if (!banner) { + banner = document.createElement('div'); + banner.id = 'offlineBanner'; + banner.className = 'offline-banner hidden'; + document.body.prepend(banner); + } + return banner; + } + + function showOfflineBanner() { + const banner = getOrCreateBanner(); + banner.className = 'offline-banner active'; + banner.innerHTML = ` +
+ ⚡ Offline + Showing locally cached data. Actions requiring connection are paused. +
+ `; + } + + function showOnlineBanner() { + const banner = getOrCreateBanner(); + banner.className = 'offline-banner online'; + banner.innerHTML = ` +
+ ✓ Online + Connection restored. Live features re-enabled. +
+ `; + setTimeout(() => { + banner.className = 'offline-banner hidden'; + }, 2800); + } + + // 3. Apply Offline Safeguards to UI + function applyOfflineState(offline) { + isOffline = offline; + + if (offline) { + showOfflineBanner(); + } else { + showOnlineBanner(); + } + + // --- A. Homework Checkboxes & Exclude Buttons --- + const assignmentToggles = document.querySelectorAll('.assignment-toggle'); + assignmentToggles.forEach((checkbox) => { + const card = checkbox.closest('.assignment-card'); + const isExcluded = card && card.dataset.excluded === 'true'; + + if (offline) { + checkbox.disabled = true; + checkbox.title = 'Offline mode: Homework status cannot be changed without connection.'; + } else { + // Only re-enable if not excluded + checkbox.disabled = isExcluded; + checkbox.title = ''; + } + }); + + const excludeButtons = document.querySelectorAll('.btn-exclude, .btn-disinclude'); + excludeButtons.forEach((btn) => { + if (offline) { + btn.disabled = true; + btn.title = 'Offline mode: Homework cannot be excluded without connection.'; + } else { + btn.disabled = false; + btn.title = btn.textContent.trim() === 'Restore' ? 'Restore homework' : 'Exclude homework'; + } + }); + + // --- B. Private Lesson Request Form --- + const lessonForm = document.getElementById('privateLessonForm'); + const btnSubmitLesson = document.getElementById('btnSubmitLessonRequest'); + const formSelects = document.querySelectorAll('#privateLessonForm select, #privateLessonForm button[type="submit"]'); + + let noticeEl = document.getElementById('privateLessonOfflineNotice'); + if (!noticeEl && lessonForm) { + noticeEl = document.createElement('div'); + noticeEl.id = 'privateLessonOfflineNotice'; + noticeEl.className = 'alert alert-warning hidden'; + noticeEl.style.marginBottom = '12px'; + noticeEl.innerHTML = '⚡ Çevrimdışı mod: Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.'; + lessonForm.prepend(noticeEl); + } + + if (formSelects.length > 0) { + formSelects.forEach((el) => { + el.disabled = offline; + }); + if (noticeEl) { + if (offline) { + noticeEl.classList.remove('hidden'); + } else { + noticeEl.classList.add('hidden'); + } + } + } + + // --- C. Sync Buttons Across All Pages --- + const syncButtonSelectors = [ + '#btnSyncRecent', + '#btnSyncAll', + '#btnSyncSyllabus', + '#btnSyncPrivateLessons', + '#btnSyncExams', + '#btnEmptySync' + ]; + + syncButtonSelectors.forEach((sel) => { + const btn = document.querySelector(sel); + if (!btn) return; + + if (offline) { + if (!btn.dataset.onlineLabel) { + btn.dataset.onlineLabel = btn.textContent.trim(); + } + btn.disabled = true; + btn.classList.add('btn-offline-disabled'); + btn.title = 'Offline mode: Sync requires internet connection.'; + btn.textContent = `${btn.dataset.onlineLabel} (Offline)`; + } else { + btn.disabled = false; + btn.classList.remove('btn-offline-disabled'); + btn.title = ''; + if (btn.dataset.onlineLabel) { + btn.textContent = btn.dataset.onlineLabel; + } + } + }); + } + + // 4. Click interceptor on homework checkboxes when offline + document.addEventListener( + 'click', + (e) => { + if (!isOffline) return; + + const target = e.target; + if (target.classList && target.classList.contains('assignment-toggle')) { + e.preventDefault(); + e.stopPropagation(); + alert('Çevrimdışı moddasınız. Ödev durumu internet bağlantısı olmadan değiştirilemez.'); + } + }, + true + ); + + // 5. Connection Listeners + window.addEventListener('online', () => { + applyOfflineState(false); + }); + + window.addEventListener('offline', () => { + applyOfflineState(true); + }); + + // 6. Initial Application on DOM Ready + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', () => { + if (!navigator.onLine) { + applyOfflineState(true); + } + }); + } else { + if (!navigator.onLine) { + applyOfflineState(true); + } + } + + // Export helper globally + window.BeKulturPWA = { + isOffline: () => isOffline, + refreshState: () => applyOfflineState(!navigator.onLine) + }; +})(); diff --git a/public/js/syllabus.js b/public/js/syllabus.js index 47817e6..be318cc 100644 --- a/public/js/syllabus.js +++ b/public/js/syllabus.js @@ -74,6 +74,10 @@ document.addEventListener('DOMContentLoaded', () => { // 4. Sync Syllabus if (btnSyncSyllabus) { btnSyncSyllabus.addEventListener('click', async () => { + if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { + showAlert('Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.', 'danger'); + return; + } btnSyncSyllabus.disabled = true; btnSyncSyllabus.textContent = 'Syncing...'; showAlert('Fetching weekly timetable across all 5 days...', 'info'); diff --git a/public/manifest.json b/public/manifest.json new file mode 100644 index 0000000..e4cb353 --- /dev/null +++ b/public/manifest.json @@ -0,0 +1,31 @@ +{ + "name": "BeKultur", + "short_name": "BeKultur", + "description": "Convenient student portal client for Kültür Okulları", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#f8fafc", + "theme_color": "#2563eb", + "orientation": "portrait-primary", + "icons": [ + { + "src": "/icons/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any maskable" + }, + { + "src": "/icons/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any maskable" + }, + { + "src": "/icons/icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any" + } + ] +} diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..a89b167 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,122 @@ +const CACHE_NAME = 'bekultur-v1'; + +const STATIC_ASSETS = [ + '/', + '/css/style.css', + '/js/pwa.js', + '/js/app.js', + '/js/syllabus.js', + '/js/private-lessons.js', + '/js/exams.js', + '/manifest.json', + '/icons/icon.svg', + '/icons/icon-192.png', + '/icons/icon-512.png' +]; + +// Pre-cache core assets +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => { + return cache.addAll(STATIC_ASSETS).catch((err) => { + console.warn('Some static assets failed to pre-cache:', err); + }); + }) + ); + self.skipWaiting(); +}); + +// Clean up old caches on activation +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then((keys) => { + return Promise.all( + keys.map((key) => { + if (key !== CACHE_NAME) { + return caches.delete(key); + } + }) + ); + }) + ); + self.clients.claim(); +}); + +// Fetch handler +self.addEventListener('fetch', (event) => { + const req = event.request; + + // Only handle GET requests + if (req.method !== 'GET') { + return; + } + + const url = new URL(req.url); + + // Ignore cross-origin external analytics or fonts + if (url.origin !== self.location.origin) { + return; + } + + // 1. Static Assets (CSS, JS, Icons, Images) -> Cache-First + const isStatic = + url.pathname.startsWith('/css/') || + url.pathname.startsWith('/js/') || + url.pathname.startsWith('/icons/') || + url.pathname === '/manifest.json' || + url.pathname.endsWith('.png') || + url.pathname.endsWith('.svg') || + url.pathname.endsWith('.ico'); + + if (isStatic) { + event.respondWith( + caches.match(req).then((cachedResponse) => { + if (cachedResponse) { + return cachedResponse; + } + return fetch(req).then((networkResponse) => { + if (networkResponse && networkResponse.status === 200) { + const clone = networkResponse.clone(); + caches.open(CACHE_NAME).then((cache) => cache.put(req, clone)); + } + return networkResponse; + }); + }) + ); + return; + } + + // 2. Navigation Pages & API GETs -> Network-First with Cache Fallback + event.respondWith( + fetch(req) + .then((networkResponse) => { + if (networkResponse && networkResponse.status === 200) { + const clone = networkResponse.clone(); + caches.open(CACHE_NAME).then((cache) => cache.put(req, clone)); + } + return networkResponse; + }) + .catch(async () => { + // Network failed (Offline) -> Look in CacheStorage + const cached = await caches.match(req); + if (cached) { + return cached; + } + + // If it was a navigation request, try fallback to cached dashboard or root + if (req.mode === 'navigate') { + const fallbackDashboard = await caches.match('/dashboard'); + if (fallbackDashboard) return fallbackDashboard; + + const fallbackRoot = await caches.match('/'); + if (fallbackRoot) return fallbackRoot; + } + + return new Response('Offline: Content not available in cache.', { + status: 503, + statusText: 'Service Unavailable', + headers: { 'Content-Type': 'text/plain; charset=utf-8' } + }); + }) + ); +}); diff --git a/src/server.ts b/src/server.ts index b79fdbb..258d25b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -27,6 +27,20 @@ app.set('views', viewsPath); 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( diff --git a/test/run-tests.ts b/test/run-tests.ts index 16a4979..abc2993 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -642,6 +642,58 @@ async function runAllTests() { assert.strictEqual(retrieved[0].topicName, 'Paragraf'); }); + // 7. PWA & Offline Support Tests + await test('PWA: manifest.json is valid and contains standard required PWA fields and icons', () => { + const fs = require('fs'); + const path = require('path'); + const manifestPath = path.resolve(__dirname, '../public/manifest.json'); + assert(fs.existsSync(manifestPath), 'manifest.json must exist in public directory'); + + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')); + assert.strictEqual(manifest.name, 'BeKultur'); + assert.strictEqual(manifest.short_name, 'BeKultur'); + assert.strictEqual(manifest.display, 'standalone'); + assert.strictEqual(manifest.start_url, '/'); + assert(Array.isArray(manifest.icons) && manifest.icons.length >= 2, 'manifest must declare icons'); + + // Verify all referenced icons physically exist + manifest.icons.forEach((ic: { src: string }) => { + const iconPath = path.resolve(__dirname, '../public', ic.src.replace(/^\//, '')); + assert(fs.existsSync(iconPath), `Icon file ${ic.src} must exist at ${iconPath}`); + }); + }); + + await test('PWA: sw.js contains static asset pre-caching and offline cache fallback strategies', () => { + const fs = require('fs'); + const path = require('path'); + const swPath = path.resolve(__dirname, '../public/sw.js'); + assert(fs.existsSync(swPath), 'sw.js must exist in public directory'); + + const swContent = fs.readFileSync(swPath, 'utf-8'); + assert(swContent.includes('CACHE_NAME'), 'sw.js must define cache name'); + assert(swContent.includes('STATIC_ASSETS'), 'sw.js must define static assets array'); + assert(swContent.includes("addEventListener('install'"), 'sw.js must have install event listener'); + assert(swContent.includes("addEventListener('activate'"), 'sw.js must have activate event listener'); + assert(swContent.includes("addEventListener('fetch'"), 'sw.js must have fetch event listener'); + assert(swContent.includes('caches.match'), 'sw.js must contain cache match fallback'); + }); + + await test('PWA: pwa.js contains offline detection and UI safeguard handlers', () => { + const fs = require('fs'); + const path = require('path'); + const pwaPath = path.resolve(__dirname, '../public/js/pwa.js'); + assert(fs.existsSync(pwaPath), 'pwa.js must exist in public/js directory'); + + const pwaContent = fs.readFileSync(pwaPath, 'utf-8'); + assert(pwaContent.includes(".register('/sw.js'"), 'pwa.js must register service worker'); + assert(pwaContent.includes("addEventListener('online'"), 'pwa.js must listen for online event'); + assert(pwaContent.includes("addEventListener('offline'"), 'pwa.js must listen for offline event'); + assert(pwaContent.includes('offlineBanner'), 'pwa.js must manage offline banner'); + assert(pwaContent.includes('assignment-toggle'), 'pwa.js must manage homework checkboxes in offline mode'); + assert(pwaContent.includes('privateLessonForm'), 'pwa.js must manage private lesson request form in offline mode'); + assert(pwaContent.includes('btnSync'), 'pwa.js must manage sync buttons in offline mode'); + }); + // 6. Optional Live Portal Test (via environment variables only) const testStudentId = process.env.TEST_STUDENT_ID; const testPassword = process.env.TEST_PASSWORD; diff --git a/views/partials/footer.ejs b/views/partials/footer.ejs index 03e2498..e2aad25 100644 --- a/views/partials/footer.ejs +++ b/views/partials/footer.ejs @@ -4,6 +4,7 @@ BeKultur + diff --git a/views/partials/header.ejs b/views/partials/header.ejs index ad9d082..3f7842b 100644 --- a/views/partials/header.ejs +++ b/views/partials/header.ejs @@ -4,9 +4,23 @@ <%= typeof title !== 'undefined' ? title : 'BeKultur' %> + + + + + + + + + + + + + +