diff --git a/.dockerignore b/.dockerignore
index 74de09b..f1fab13 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -3,5 +3,10 @@ dist
.git
.env
*.log
+.DS_Store
data/*.json
+data/*.bak
+data/*.db
+data/*.db-*
+data/.secrets.json
!data/.gitkeep
diff --git a/.gitignore b/.gitignore
index 979a024..71fcd62 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,10 @@ node_modules/
dist/
.env
data/*.json
+data/*.bak
+data/*.db
+data/*.db-*
+data/.secrets.json
!data/.gitkeep
*.log
.DS_Store
diff --git a/Dockerfile b/Dockerfile
index bf52b37..d3ae1fd 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,12 +1,14 @@
# ----------------------------------------------------
-# Stage 1: Build TypeScript Application
+# Stage 1: Build TypeScript Application & Native Addons
# ----------------------------------------------------
FROM node:18-alpine AS builder
WORKDIR /app
+RUN apk add --no-cache python3 make g++
+
COPY package*.json ./
-RUN npm install
+RUN npm ci
COPY tsconfig.json ./
COPY src/ ./src/
@@ -14,6 +16,7 @@ COPY views/ ./views/
COPY public/ ./public/
RUN npm run build
+RUN npm prune --omit=dev
# ----------------------------------------------------
# Stage 2: Production Runtime
@@ -26,16 +29,17 @@ ENV NODE_ENV=production
ENV PORT=3000
COPY package*.json ./
-RUN npm install --omit=dev
-
-# Copy compiled code and assets from builder
+COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY views/ ./views
COPY public/ ./public
-# Ensure local data directory exists for persistent JSON db
-RUN mkdir -p /app/data
+# Ensure local data directory exists for persistent SQLite db & secrets
+RUN mkdir -p /app/data && chown -R node:node /app
EXPOSE 3000
+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
+ CMD wget -qO- http://localhost:3000/login > /dev/null || exit 1
+
CMD ["node", "dist/server.js"]
diff --git a/docker-compose.yml b/docker-compose.yml
index 4fb6813..06c6613 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -9,7 +9,8 @@ services:
restart: unless-stopped
environment:
- PORT=3000
- - SESSION_SECRET=${SESSION_SECRET:-bekultur_default_secret_key_change_me}
+ - SESSION_SECRET=${SESSION_SECRET:-}
+ - ENCRYPTION_SECRET=${ENCRYPTION_SECRET:-}
- NODE_ENV=production
volumes:
- ./data:/app/data
diff --git a/package-lock.json b/package-lock.json
index e0c26ee..a1f1549 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,15 +10,19 @@
"license": "ISC",
"dependencies": {
"axios": "^1.7.7",
+ "better-sqlite3": "^11.10.0",
"cheerio": "^1.0.0-rc.12",
"cookie-parser": "^1.4.7",
"dotenv": "^16.4.5",
"ejs": "^3.1.10",
"express": "^4.21.1",
- "express-session": "^1.18.1"
+ "express-rate-limit": "^8.7.3",
+ "express-session": "^1.18.1",
+ "helmet": "^8.3.0"
},
"devDependencies": {
"@resvg/resvg-js": "^2.6.2",
+ "@types/better-sqlite3": "^9.6.0",
"@types/cookie-parser": "^1.4.7",
"@types/ejs": "^3.1.5",
"@types/express": "^4.17.21",
@@ -306,6 +310,15 @@
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
"dev": true
},
+ "node_modules/@types/better-sqlite3": {
+ "version": "9.6.0",
+ "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-9.6.0.tgz",
+ "integrity": "sha512-ZEEwBSgMu7GYJOynoagg5X9JbxfL6dTJDsgViJIqh67jV44kyOr9RXfmFjLK5rzC4MWssP06t9hu/JwGDnUbCg==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/body-parser": {
"version": "1.19.6",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
@@ -566,6 +579,35 @@
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
+ "node_modules/better-sqlite3": {
+ "version": "11.10.0",
+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
+ "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
+ "hasInstallScript": true,
+ "dependencies": {
+ "bindings": "^1.5.0",
+ "prebuild-install": "^7.1.1"
+ }
+ },
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -578,6 +620,24 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/bindings": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
+ "dependencies": {
+ "file-uri-to-path": "1.0.0"
+ }
+ },
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
"node_modules/body-parser": {
"version": "1.20.8",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",
@@ -637,6 +697,29 @@
"node": ">=8"
}
},
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -738,6 +821,11 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/chownr": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="
+ },
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -839,6 +927,28 @@
"ms": "2.0.0"
}
},
+ "node_modules/decompress-response": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
+ "dependencies": {
+ "mimic-response": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/deep-extend": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
+ "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -864,6 +974,14 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/diff": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz",
@@ -984,6 +1102,14 @@
"node": ">= 0.8"
}
},
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
@@ -1049,6 +1175,14 @@
"node": ">= 0.6"
}
},
+ "node_modules/expand-template": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
+ "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/express": {
"version": "4.22.3",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
@@ -1094,6 +1228,45 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/express-rate-limit": {
+ "version": "8.7.3",
+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.3.tgz",
+ "integrity": "sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "ip-address": "^10.2.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/express-rate-limit"
+ },
+ "peerDependencies": {
+ "express": ">= 4.11"
+ }
+ },
+ "node_modules/express-rate-limit/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/express-rate-limit/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
+ },
"node_modules/express-session": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz",
@@ -1121,6 +1294,11 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="
},
+ "node_modules/file-uri-to-path": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="
+ },
"node_modules/filelist": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
@@ -1208,6 +1386,11 @@
"node": ">= 0.6"
}
},
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="
+ },
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
@@ -1271,6 +1454,11 @@
"node": ">= 0.4"
}
},
+ "node_modules/github-from-package": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
+ "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="
+ },
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -1373,6 +1561,17 @@
"node": ">= 0.4"
}
},
+ "node_modules/helmet": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz",
+ "integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==",
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/EvanHahn"
+ }
+ },
"node_modules/htmlparser2": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",
@@ -1443,6 +1642,25 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -1459,6 +1677,19 @@
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
+ "node_modules/ini": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+ "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
+ },
+ "node_modules/ip-address": {
+ "version": "10.7.6",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz",
+ "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -1608,6 +1839,17 @@
"node": ">= 0.6"
}
},
+ "node_modules/mimic-response": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/minimatch": {
"version": "5.1.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
@@ -1623,7 +1865,6 @@
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
- "dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@@ -1640,11 +1881,21 @@
"node": ">=10"
}
},
+ "node_modules/mkdirp-classic": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
+ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="
+ },
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
+ "node_modules/napi-build-utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
+ "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="
+ },
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -1653,6 +1904,17 @@
"node": ">= 0.6"
}
},
+ "node_modules/node-abi": {
+ "version": "3.101.0",
+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.101.0.tgz",
+ "integrity": "sha512-bkb/RkuWCE64eWu1PCh3Fu2pGc9mKRs+kOE+FU2bGHRYlQa86/D321DSATV54AsCQMKz3/xSt9sRgraZTpqdhQ==",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@@ -1707,7 +1969,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
- "dev": true,
"dependencies": {
"wrappy": "1"
}
@@ -1800,6 +2061,32 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/prebuild-install": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+ "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
+ "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
+ "dependencies": {
+ "detect-libc": "^2.0.0",
+ "expand-template": "^2.0.3",
+ "github-from-package": "0.0.0",
+ "minimist": "^1.2.3",
+ "mkdirp-classic": "^0.5.3",
+ "napi-build-utils": "^2.0.0",
+ "node-abi": "^3.3.0",
+ "pump": "^3.0.0",
+ "rc": "^1.2.7",
+ "simple-get": "^4.0.0",
+ "tar-fs": "^2.0.0",
+ "tunnel-agent": "^0.6.0"
+ },
+ "bin": {
+ "prebuild-install": "bin.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/proxy-addr": {
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
@@ -1824,6 +2111,15 @@
"node": ">=10"
}
},
+ "node_modules/pump": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
"node_modules/qs": {
"version": "6.16.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz",
@@ -1880,6 +2176,33 @@
"node": ">=0.10.0"
}
},
+ "node_modules/rc": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
+ "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
+ "dependencies": {
+ "deep-extend": "^0.6.0",
+ "ini": "~1.3.0",
+ "minimist": "^1.2.0",
+ "strip-json-comments": "~2.0.1"
+ },
+ "bin": {
+ "rc": "cli.js"
+ }
+ },
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -1950,6 +2273,17 @@
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
+ "node_modules/semver": {
+ "version": "7.8.6",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
@@ -2065,6 +2399,49 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/simple-concat": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
+ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+ },
+ "node_modules/simple-get": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
+ "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "dependencies": {
+ "decompress-response": "^6.0.0",
+ "once": "^1.3.1",
+ "simple-concat": "^1.0.0"
+ }
+ },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
@@ -2092,6 +2469,14 @@
"node": ">= 0.8"
}
},
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
"node_modules/strip-bom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
@@ -2105,7 +2490,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
- "dev": true,
"engines": {
"node": ">=0.10.0"
}
@@ -2122,6 +2506,32 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/tar-fs": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
+ "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
+ "dependencies": {
+ "chownr": "^1.1.1",
+ "mkdirp-classic": "^0.5.2",
+ "pump": "^3.0.0",
+ "tar-stream": "^2.1.4"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -2240,6 +2650,17 @@
"strip-json-comments": "^2.0.0"
}
},
+ "node_modules/tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
@@ -2290,6 +2711,11 @@
"node": ">= 0.8"
}
},
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
+ },
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -2315,8 +2741,7 @@
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
- "dev": true
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/xtend": {
"version": "4.0.2",
diff --git a/package.json b/package.json
index 52587d8..6a02db0 100644
--- a/package.json
+++ b/package.json
@@ -20,15 +20,19 @@
"license": "ISC",
"dependencies": {
"axios": "^1.7.7",
+ "better-sqlite3": "^11.10.0",
"cheerio": "^1.0.0-rc.12",
"cookie-parser": "^1.4.7",
"dotenv": "^16.4.5",
"ejs": "^3.1.10",
"express": "^4.21.1",
- "express-session": "^1.18.1"
+ "express-rate-limit": "^8.7.3",
+ "express-session": "^1.18.1",
+ "helmet": "^8.3.0"
},
"devDependencies": {
"@resvg/resvg-js": "^2.6.2",
+ "@types/better-sqlite3": "^9.6.0",
"@types/cookie-parser": "^1.4.7",
"@types/ejs": "^3.1.5",
"@types/express": "^4.17.21",
diff --git a/public/css/style.css b/public/css/style.css
index 070a40f..53c9a61 100644
--- a/public/css/style.css
+++ b/public/css/style.css
@@ -1,21 +1,145 @@
:root {
+ color-scheme: light dark;
+
--primary: #2563eb;
--primary-hover: #1d4ed8;
+ --primary-soft-bg: #eff6ff;
+ --primary-soft-text: #1e40af;
+ --primary-soft-border: #bfdbfe;
+
--text-main: #1e293b;
--text-muted: #64748b;
--text-light: #94a3b8;
+
--bg-page: #f8fafc;
--bg-card: #ffffff;
+ --bg-subtle: #f8fafc;
+ --bg-muted: #f1f5f9;
+ --bg-hover: #e2e8f0;
+ --bg-input: #ffffff;
+
--border: #e2e8f0;
-
+ --border-strong: #cbd5e1;
+
--success: #16a34a;
--warning: #d97706;
--urgent: #ea580c;
--danger: #dc2626;
+ /* Semantic Soft Badges & Alerts (Light) */
+ --badge-active-bg: #e0f2fe;
+ --badge-active-text: #0369a1;
+ --badge-warning-bg: #fef3c7;
+ --badge-warning-text: #b45309;
+ --badge-warning-border: #fde68a;
+ --badge-urgent-bg: #ffedd5;
+ --badge-urgent-text: #c2410c;
+ --badge-danger-bg: #fee2e2;
+ --badge-danger-text: #b91c1c;
+ --badge-danger-border: #fecaca;
+ --badge-success-bg: #dcfce7;
+ --badge-success-text: #15803d;
+ --badge-success-border: #bbf7d0;
+ --badge-purple-bg: #f3e8ff;
+ --badge-purple-text: #7e22ce;
+ --badge-purple-border: #e9d5ff;
+
--radius: 6px;
}
+/* System Dark Mode (when not explicitly overridden to light) */
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]):not(:has(> head > meta[name="color-scheme"][content="light"])) {
+ --primary: #3b82f6;
+ --primary-hover: #2563eb;
+ --primary-soft-bg: rgba(59, 130, 246, 0.16);
+ --primary-soft-text: #93c5fd;
+ --primary-soft-border: rgba(59, 130, 246, 0.35);
+
+ --text-main: #f1f5f9;
+ --text-muted: #94a3b8;
+ --text-light: #64748b;
+
+ --bg-page: #0b1120;
+ --bg-card: #111827;
+ --bg-subtle: #172033;
+ --bg-muted: #1e293b;
+ --bg-hover: #334155;
+ --bg-input: #0f172a;
+
+ --border: #1e293b;
+ --border-strong: #334155;
+
+ --success: #22c55e;
+ --warning: #f59e0b;
+ --urgent: #fb923c;
+ --danger: #f87171;
+
+ --badge-active-bg: rgba(14, 165, 233, 0.18);
+ --badge-active-text: #7dd3fc;
+ --badge-warning-bg: rgba(245, 158, 11, 0.18);
+ --badge-warning-text: #fcd34d;
+ --badge-warning-border: rgba(245, 158, 11, 0.35);
+ --badge-urgent-bg: rgba(249, 115, 22, 0.18);
+ --badge-urgent-text: #fdba74;
+ --badge-danger-bg: rgba(239, 68, 68, 0.18);
+ --badge-danger-text: #fca5a5;
+ --badge-danger-border: rgba(239, 68, 68, 0.35);
+ --badge-success-bg: rgba(34, 197, 94, 0.18);
+ --badge-success-text: #86efac;
+ --badge-success-border: rgba(34, 197, 94, 0.35);
+ --badge-purple-bg: rgba(168, 85, 247, 0.18);
+ --badge-purple-text: #d8b4fe;
+ --badge-purple-border: rgba(168, 85, 247, 0.35);
+ }
+}
+
+/* Explicit User Dark Mode Override */
+:root[data-theme="dark"],
+:root:has(> head > meta[name="color-scheme"][content="dark"]) {
+ --primary: #3b82f6;
+ --primary-hover: #2563eb;
+ --primary-soft-bg: rgba(59, 130, 246, 0.16);
+ --primary-soft-text: #93c5fd;
+ --primary-soft-border: rgba(59, 130, 246, 0.35);
+
+ --text-main: #f1f5f9;
+ --text-muted: #94a3b8;
+ --text-light: #64748b;
+
+ --bg-page: #0b1120;
+ --bg-card: #111827;
+ --bg-subtle: #172033;
+ --bg-muted: #1e293b;
+ --bg-hover: #334155;
+ --bg-input: #0f172a;
+
+ --border: #1e293b;
+ --border-strong: #334155;
+
+ --success: #22c55e;
+ --warning: #f59e0b;
+ --urgent: #fb923c;
+ --danger: #f87171;
+
+ --badge-active-bg: rgba(14, 165, 233, 0.18);
+ --badge-active-text: #7dd3fc;
+ --badge-warning-bg: rgba(245, 158, 11, 0.18);
+ --badge-warning-text: #fcd34d;
+ --badge-warning-border: rgba(245, 158, 11, 0.35);
+ --badge-urgent-bg: rgba(249, 115, 22, 0.18);
+ --badge-urgent-text: #fdba74;
+ --badge-danger-bg: rgba(239, 68, 68, 0.18);
+ --badge-danger-text: #fca5a5;
+ --badge-danger-border: rgba(239, 68, 68, 0.35);
+ --badge-success-bg: rgba(34, 197, 94, 0.18);
+ --badge-success-text: #86efac;
+ --badge-success-border: rgba(34, 197, 94, 0.35);
+ --badge-purple-bg: rgba(168, 85, 247, 0.18);
+ --badge-purple-text: #d8b4fe;
+ --badge-purple-border: rgba(168, 85, 247, 0.35);
+}
+
* {
box-sizing: border-box;
margin: 0;
@@ -37,12 +161,14 @@ body {
min-height: 100vh;
display: flex;
flex-direction: column;
+ transition: background-color 0.15s ease, color 0.15s ease;
}
code {
font-family: Menlo, Monaco, Consolas, monospace;
font-size: 0.9em;
- background: #f1f5f9;
+ background: var(--bg-muted);
+ color: var(--text-main);
padding: 2px 4px;
border-radius: 3px;
}
@@ -83,7 +209,7 @@ code {
.user-nav {
display: flex;
align-items: center;
- gap: 12px;
+ gap: 8px;
flex-shrink: 0;
}
@@ -93,6 +219,85 @@ code {
white-space: nowrap;
}
+/* Language Switcher & Theme Toggle */
+.lang-switcher {
+ display: inline-flex;
+ align-items: center;
+ background: var(--bg-muted);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ padding: 2px;
+ gap: 2px;
+}
+
+.lang-btn {
+ text-decoration: none;
+ font-size: 0.725rem;
+ font-weight: 700;
+ color: var(--text-muted);
+ padding: 3px 7px;
+ border-radius: 4px;
+ line-height: 1.2;
+ transition: all 0.15s ease;
+}
+
+.lang-btn:hover {
+ color: var(--text-main);
+}
+
+.lang-btn.active {
+ background: var(--bg-card);
+ color: var(--primary);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
+}
+
+.btn-icon-toggle {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ border-radius: var(--radius);
+ border: 1px solid var(--border);
+ background: var(--bg-muted);
+ color: var(--text-main);
+ cursor: pointer;
+ transition: all 0.15s ease;
+}
+
+.btn-icon-toggle:hover {
+ background: var(--bg-hover);
+ border-color: var(--border-strong);
+}
+
+.theme-icon-sun {
+ display: none;
+}
+
+.theme-icon-moon {
+ display: block;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]):not(:has(> head > meta[name="color-scheme"][content="light"])) .theme-icon-sun {
+ display: block;
+ }
+ :root:not([data-theme="light"]):not(:has(> head > meta[name="color-scheme"][content="light"])) .theme-icon-moon {
+ display: none;
+ }
+}
+
+:root[data-theme="dark"] .theme-icon-sun,
+:root:has(> head > meta[name="color-scheme"][content="dark"]) .theme-icon-sun {
+ display: block;
+}
+
+:root[data-theme="dark"] .theme-icon-moon,
+:root:has(> head > meta[name="color-scheme"][content="dark"]) .theme-icon-moon {
+ display: none;
+}
+
/* ---------------- Main Layout ---------------- */
.main-content {
flex: 1;
@@ -102,6 +307,10 @@ code {
padding: 18px 16px;
}
+.content-container {
+ width: 100%;
+}
+
/* ---------------- Buttons ---------------- */
.btn {
display: inline-flex;
@@ -114,6 +323,7 @@ code {
border: 1px solid transparent;
cursor: pointer;
text-decoration: none;
+ transition: all 0.15s ease;
}
.btn:disabled {
@@ -130,14 +340,23 @@ code {
background-color: var(--primary-hover);
}
+.btn-danger {
+ background-color: var(--danger);
+ color: white;
+}
+
+.btn-danger:hover:not(:disabled) {
+ filter: brightness(0.92);
+}
+
.btn-secondary {
- background-color: white;
+ background-color: var(--bg-card);
border-color: var(--border);
color: var(--text-main);
}
.btn-secondary:hover:not(:disabled) {
- background-color: #f1f5f9;
+ background-color: var(--bg-muted);
}
.btn-outline {
@@ -147,7 +366,7 @@ code {
}
.btn-outline:hover {
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-main);
}
@@ -156,6 +375,11 @@ code {
font-size: 0.8rem;
}
+.btn-xs {
+ padding: 3px 8px;
+ font-size: 0.75rem;
+}
+
.btn-block {
width: 100%;
}
@@ -205,6 +429,9 @@ code {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-main);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
}
.form-control {
@@ -213,7 +440,8 @@ code {
font-size: 0.9rem;
border: 1px solid var(--border);
border-radius: var(--radius);
- background: white;
+ background: var(--bg-input);
+ color: var(--text-main);
}
.form-control:focus {
@@ -246,19 +474,20 @@ code {
}
.alert-danger {
- background: #fef2f2;
- color: #991b1b;
- border: 1px solid #fecaca;
+ background: var(--badge-danger-bg);
+ color: var(--badge-danger-text);
+ border: 1px solid var(--badge-danger-border);
}
.alert-info {
- background: #eff6ff;
- color: #1e40af;
- border: 1px solid #bfdbfe;
+ background: var(--primary-soft-bg);
+ color: var(--primary-soft-text);
+ border: 1px solid var(--primary-soft-border);
}
/* ---------------- Dashboard Top Bar ---------------- */
-.dashboard-topbar {
+.dashboard-topbar,
+.dashboard-top-row {
display: flex;
align-items: center;
justify-content: space-between;
@@ -267,12 +496,15 @@ code {
margin-bottom: 18px;
}
-.dashboard-title {
+.dashboard-title,
+.page-title {
font-size: 1.4rem;
font-weight: 700;
+ color: var(--text-main);
}
-.dashboard-subtitle {
+.dashboard-subtitle,
+.page-subtitle {
font-size: 0.85rem;
color: var(--text-muted);
}
@@ -299,6 +531,8 @@ code {
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 12px 14px;
+ display: flex;
+ flex-direction: column;
}
.stat-highlight {
@@ -317,15 +551,17 @@ code {
font-size: 1.45rem;
font-weight: 700;
margin: 4px 0 2px;
+ color: var(--text-main);
}
-.stat-subtext {
+.stat-subtext,
+.stat-sub {
font-size: 0.75rem;
color: var(--text-muted);
}
.progress-bar-container {
- background: #e2e8f0;
+ background: var(--bg-hover);
height: 4px;
border-radius: 9999px;
overflow: hidden;
@@ -382,7 +618,7 @@ code {
}
.subject-item {
- background: #f8fafc;
+ background: var(--bg-subtle);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 8px 10px;
@@ -406,7 +642,7 @@ code {
}
.subject-bar {
- background: #e2e8f0;
+ background: var(--bg-hover);
height: 4px;
border-radius: 9999px;
overflow: hidden;
@@ -437,7 +673,7 @@ code {
}
.tab-btn {
- background: #f1f5f9;
+ background: var(--bg-muted);
border: 1px solid transparent;
color: var(--text-muted);
padding: 4px 10px;
@@ -448,7 +684,8 @@ code {
}
.tab-btn:hover {
- background: #e2e8f0;
+ background: var(--bg-hover);
+ color: var(--text-main);
}
.tab-btn.active {
@@ -474,6 +711,8 @@ code {
font-size: 0.85rem;
border: 1px solid var(--border);
border-radius: var(--radius);
+ background: var(--bg-input);
+ color: var(--text-main);
}
.search-input:focus {
@@ -492,12 +731,26 @@ code {
}
.form-select {
- padding: 6px 10px;
- font-size: 0.85rem;
+ padding: 8px 12px;
border: 1px solid var(--border);
border-radius: var(--radius);
- background: white;
+ background: var(--bg-input);
+ color: var(--text-main);
+ font-size: 0.875rem;
+ font-family: inherit;
cursor: pointer;
+ transition: border-color 0.15s ease;
+}
+
+.form-select:focus {
+ outline: none;
+ border-color: var(--primary);
+}
+
+.form-select:disabled {
+ background: var(--bg-subtle);
+ color: var(--text-light);
+ cursor: not-allowed;
}
.list-meta {
@@ -556,6 +809,7 @@ code {
width: 17px;
height: 17px;
cursor: pointer;
+ accent-color: var(--primary);
}
.card-content-col {
@@ -594,50 +848,64 @@ code {
.badge {
font-size: 0.725rem;
font-weight: 600;
- padding: 1px 6px;
+ padding: 2px 6px;
border-radius: 4px;
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
}
-.badge-type {
- background: #f1f5f9;
+.badge-type,
+.badge-soft-secondary,
+.badge-soft-neutral {
+ background: var(--bg-muted);
color: var(--text-muted);
}
-.badge-active {
- background: #e0f2fe;
- color: #0369a1;
+.badge-active,
+.badge-soft-info {
+ background: var(--badge-active-bg);
+ color: var(--badge-active-text);
}
-.badge-next-week {
- background: #fef3c7;
- color: #b45309;
+.badge-soft-primary {
+ background: var(--primary-soft-bg);
+ color: var(--primary-soft-text);
+}
+
+.badge-next-week,
+.badge-soft-warning {
+ background: var(--badge-warning-bg);
+ color: var(--badge-warning-text);
}
.badge-due-soon {
- background: #ffedd5;
- color: #c2410c;
+ background: var(--badge-urgent-bg);
+ color: var(--badge-urgent-text);
}
-.badge-overdue {
- background: #fee2e2;
- color: #b91c1c;
+.badge-overdue,
+.badge-soft-danger {
+ background: var(--badge-danger-bg);
+ color: var(--badge-danger-text);
}
-.badge-completed {
- background: #dcfce7;
- color: #15803d;
+.badge-completed,
+.badge-soft-success {
+ background: var(--badge-success-bg);
+ color: var(--badge-success-text);
}
.badge-check-date {
- background: #f3e8ff;
- color: #7e22ce;
- border: 1px solid #e9d5ff;
+ background: var(--badge-purple-bg);
+ color: var(--badge-purple-text);
+ border: 1px solid var(--badge-purple-border);
}
.badge-excluded {
- background: #f1f5f9;
- color: #64748b;
- border: 1px solid #cbd5e1;
+ background: var(--bg-muted);
+ color: var(--text-muted);
+ border: 1px solid var(--border-strong);
}
.btn-exclude,
@@ -650,9 +918,9 @@ code {
align-items: center;
padding: 1px 6px;
border-radius: 4px;
- background: #f1f5f9;
- color: #64748b;
- border: 1px solid #e2e8f0;
+ background: var(--bg-muted);
+ color: var(--text-muted);
+ border: 1px solid var(--border);
cursor: pointer;
transition: all 0.15s ease;
user-select: none;
@@ -660,14 +928,14 @@ code {
.btn-exclude:hover,
.btn-disinclude:hover {
- background: #e2e8f0;
- color: #334155;
- border-color: #cbd5e1;
+ background: var(--bg-hover);
+ color: var(--text-main);
+ border-color: var(--border-strong);
}
.btn-exclude:active,
.btn-disinclude:active {
- background: #cbd5e1;
+ background: var(--border-strong);
}
.btn-exclude:focus-visible,
@@ -678,8 +946,8 @@ code {
.assignment-card.is-excluded {
opacity: 0.5;
- background-color: #f8fafc;
- border-left: 3px solid #94a3b8 !important;
+ background-color: var(--bg-subtle);
+ border-left: 3px solid var(--text-light) !important;
}
.card-sub-meta {
@@ -692,10 +960,10 @@ code {
.card-description {
font-size: 0.88rem;
line-height: 1.45;
- color: #1e293b;
+ color: var(--text-main);
white-space: pre-line;
word-break: break-word;
- background: #f8fafc;
+ background: var(--bg-subtle);
padding: 6px 10px;
border-radius: 4px;
}
@@ -719,17 +987,24 @@ code {
color: var(--text-light);
}
-.empty-state {
+.empty-state,
+.empty-state-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
- padding: 24px;
+ padding: 28px 24px;
text-align: center;
color: var(--text-muted);
font-size: 0.85rem;
}
-.empty-state p {
+.empty-state p,
+.empty-state-card p {
+ margin-bottom: 12px;
+}
+
+.empty-icon {
+ font-size: 2rem;
margin-bottom: 8px;
}
@@ -746,8 +1021,33 @@ code {
display: none !important;
}
+.text-center {
+ text-align: center !important;
+}
+
+.text-muted {
+ color: var(--text-muted) !important;
+}
+
+.text-success {
+ color: var(--success) !important;
+}
+
+.text-danger {
+ color: var(--danger) !important;
+}
+
+.text-primary {
+ color: var(--primary) !important;
+}
+
+.font-semibold {
+ font-weight: 600;
+}
+
@media (max-width: 600px) {
- .dashboard-topbar {
+ .dashboard-topbar,
+ .dashboard-top-row {
flex-direction: column;
align-items: flex-start;
}
@@ -793,13 +1093,13 @@ code {
.nav-item:hover {
color: var(--text-main);
- background: #f1f5f9;
+ background: var(--bg-muted);
}
.nav-item.active {
- color: var(--primary);
+ color: var(--primary-soft-text);
font-weight: 600;
- background: #eff6ff;
+ background: var(--primary-soft-bg);
}
.station-select-row, .view-toggle-row {
@@ -823,7 +1123,7 @@ code {
}
.station-btn, .view-btn {
- background: #f1f5f9;
+ background: var(--bg-muted);
border: 1px solid var(--border);
color: var(--text-main);
font-size: 0.8rem;
@@ -834,7 +1134,7 @@ code {
}
.station-btn:hover, .view-btn:hover {
- background: #e2e8f0;
+ background: var(--bg-hover);
}
.station-btn.active, .view-btn.active {
@@ -845,9 +1145,9 @@ code {
}
.live-period-banner {
- background: #eff6ff;
- border: 1px solid #bfdbfe;
- color: #1e40af;
+ background: var(--primary-soft-bg);
+ border: 1px solid var(--primary-soft-border);
+ color: var(--primary-soft-text);
padding: 8px 12px;
border-radius: var(--radius);
font-size: 0.85rem;
@@ -859,7 +1159,7 @@ code {
}
.live-dot {
- color: #2563eb;
+ color: var(--primary);
animation: pulse 1.5s infinite;
}
@@ -892,7 +1192,7 @@ code {
}
.day-tab-btn:hover {
- background: #f8fafc;
+ background: var(--bg-subtle);
color: var(--text-main);
}
@@ -903,8 +1203,8 @@ code {
}
.today-badge {
- background: #fef3c7;
- color: #b45309;
+ background: var(--badge-warning-bg);
+ color: var(--badge-warning-text);
font-size: 0.7rem;
padding: 1px 4px;
border-radius: 3px;
@@ -917,7 +1217,7 @@ code {
}
.day-count-badge {
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-muted);
font-size: 0.7rem;
padding: 1px 5px;
@@ -992,17 +1292,17 @@ code {
}
.station-badge {
- background: #fef3c7;
- color: #b45309;
+ background: var(--badge-warning-bg);
+ color: var(--badge-warning-text);
font-size: 0.75rem;
font-weight: 700;
padding: 2px 8px;
border-radius: 4px;
- border: 1px solid #fde68a;
+ border: 1px solid var(--badge-warning-border);
}
.class-badge {
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-muted);
font-size: 0.75rem;
padding: 2px 8px;
@@ -1030,19 +1330,20 @@ code {
}
.week-grid-table th {
- background: #f8fafc;
+ background: var(--bg-subtle);
font-weight: 600;
}
.grid-today-th {
- background: #eff6ff !important;
- color: var(--primary);
+ background: var(--primary-soft-bg) !important;
+ color: var(--primary-soft-text);
}
.grid-today-pill {
font-size: 0.68rem;
- background: #dbeafe;
- color: #1e40af;
+ background: var(--primary-soft-bg);
+ color: var(--primary-soft-text);
+ border: 1px solid var(--primary-soft-border);
padding: 1px 4px;
border-radius: 3px;
margin-left: 4px;
@@ -1050,7 +1351,7 @@ code {
.grid-period-cell {
min-width: 80px;
- background: #f8fafc;
+ background: var(--bg-subtle);
}
.grid-period-title {
@@ -1067,7 +1368,7 @@ code {
}
.grid-lesson-cell.has-lesson {
- background: #ffffff;
+ background: var(--bg-card);
}
.grid-lesson-item:not(:last-child) {
@@ -1089,8 +1390,8 @@ code {
.grid-station-tag {
display: inline-block;
font-size: 0.68rem;
- background: #fef3c7;
- color: #b45309;
+ background: var(--badge-warning-bg);
+ color: var(--badge-warning-text);
padding: 1px 4px;
border-radius: 3px;
margin-top: 3px;
@@ -1111,8 +1412,8 @@ code {
display: inline-flex;
align-items: center;
gap: 6px;
- background: #f1f5f9;
- border: 1px solid #e2e8f0;
+ background: var(--bg-muted);
+ border: 1px solid var(--border);
padding: 3px 10px;
border-radius: 9999px;
font-size: 0.775rem;
@@ -1126,7 +1427,7 @@ code {
.advisor-sub {
color: var(--text-muted);
font-size: 0.7rem;
- background: #e2e8f0;
+ background: var(--bg-hover);
padding: 1px 6px;
border-radius: 4px;
}
@@ -1192,11 +1493,11 @@ code {
align-items: flex-start;
gap: 8px;
font-size: 0.775rem;
- color: #92400e;
- background: #fef3c7;
+ color: var(--badge-warning-text);
+ background: var(--badge-warning-bg);
padding: 8px 12px;
border-radius: 6px;
- border-left: 3px solid #f59e0b;
+ border-left: 3px solid var(--warning);
}
.policy-icon {
@@ -1224,8 +1525,8 @@ code {
.form-header-badge {
font-size: 0.725rem;
font-weight: 600;
- background: #e0f2fe;
- color: #0369a1;
+ background: var(--badge-active-bg);
+ color: var(--badge-active-text);
padding: 2px 8px;
border-radius: 4px;
}
@@ -1237,50 +1538,12 @@ code {
margin-bottom: 16px;
}
-.form-group {
- display: flex;
- flex-direction: column;
- gap: 6px;
-}
-
-.form-label {
- font-size: 0.8rem;
- font-weight: 600;
- color: var(--text-main);
- display: flex;
- align-items: center;
- justify-content: space-between;
-}
-
.select-loading {
font-size: 0.7rem;
font-weight: 400;
color: var(--primary);
}
-.form-select {
- padding: 8px 12px;
- border: 1px solid var(--border);
- border-radius: var(--radius);
- background: #ffffff;
- color: var(--text-main);
- font-size: 0.875rem;
- font-family: inherit;
- transition: border-color 0.15s ease;
-}
-
-.form-select:focus {
- outline: none;
- border-color: var(--primary);
- box-shadow: 0 0 0 2px rgba(15, 23, 42, 0.08);
-}
-
-.form-select:disabled {
- background: #f8fafc;
- color: var(--text-light);
- cursor: not-allowed;
-}
-
.form-actions-row {
display: flex;
justify-content: flex-end;
@@ -1295,15 +1558,15 @@ code {
}
.feedback-success {
- background: #dcfce7;
- color: #15803d;
- border: 1px solid #bbf7d0;
+ background: var(--badge-success-bg);
+ color: var(--badge-success-text);
+ border: 1px solid var(--badge-success-border);
}
.feedback-error {
- background: #fee2e2;
- color: #b91c1c;
- border: 1px solid #fecaca;
+ background: var(--badge-danger-bg);
+ color: var(--badge-danger-text);
+ border: 1px solid var(--badge-danger-border);
}
/* Lessons List & Grid */
@@ -1328,7 +1591,7 @@ code {
}
.lessons-count-badge {
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-muted);
font-size: 0.75rem;
font-weight: 700;
@@ -1349,7 +1612,7 @@ code {
font-weight: 600;
padding: 3px 10px;
border-radius: 9999px;
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-muted);
border: 1px solid transparent;
cursor: pointer;
@@ -1357,12 +1620,12 @@ code {
}
.subject-pill-btn:hover {
- background: #e2e8f0;
+ background: var(--bg-hover);
color: var(--text-main);
}
.subject-pill-btn.active {
- background: var(--text-main);
+ background: var(--primary);
color: #ffffff;
}
@@ -1407,7 +1670,7 @@ code {
.lesson-card:hover {
transform: translateY(-1px);
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.lesson-card.is-upcoming {
@@ -1444,7 +1707,7 @@ code {
width: 40px;
height: 40px;
border-radius: 50%;
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-muted);
display: flex;
align-items: center;
@@ -1509,7 +1772,7 @@ code {
}
.filter-pill:hover {
- background: #f8fafc;
+ background: var(--bg-subtle);
color: var(--text-main);
}
@@ -1541,15 +1804,15 @@ code {
}
.exam-pill-card:hover {
- border-color: #cbd5e1;
+ border-color: var(--border-strong);
transform: translateY(-1px);
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.exam-pill-card.active {
border-color: var(--primary);
box-shadow: 0 0 0 1.5px var(--primary);
- background: #fdfdfe;
+ background: var(--bg-subtle);
}
.exam-pill-header {
@@ -1568,18 +1831,18 @@ code {
}
.exam-type-tyt {
- background: #e0f2fe;
- color: #0369a1;
+ background: var(--badge-active-bg);
+ color: var(--badge-active-text);
}
.exam-type-ayt {
- background: #ede9fe;
- color: #6d28d9;
+ background: var(--badge-purple-bg);
+ color: var(--badge-purple-text);
}
.exam-type-other {
- background: #f1f5f9;
- color: #475569;
+ background: var(--bg-muted);
+ color: var(--text-muted);
}
.exam-pill-name {
@@ -1636,13 +1899,13 @@ code {
}
.delta-up {
- background: #ecfdf5;
- color: #047857;
+ background: var(--badge-success-bg);
+ color: var(--badge-success-text);
}
.delta-down {
- background: #fef2f2;
- color: #b91c1c;
+ background: var(--badge-danger-bg);
+ color: var(--badge-danger-text);
}
.delta-rank-badge {
@@ -1653,13 +1916,13 @@ code {
}
.rank-up {
- background: #eff6ff;
- color: #1d4ed8;
+ background: var(--primary-soft-bg);
+ color: var(--primary-soft-text);
}
.rank-down {
- background: #fff1f2;
- color: #be123c;
+ background: var(--badge-danger-bg);
+ color: var(--badge-danger-text);
}
.exam-pill-rating {
@@ -1782,7 +2045,7 @@ code {
}
.exam-score-table th {
- background: #f8fafc;
+ background: var(--bg-subtle);
color: var(--text-muted);
font-size: 0.75rem;
font-weight: 600;
@@ -1791,11 +2054,11 @@ code {
}
.exam-score-table tbody tr:hover {
- background: #fcfdfe;
+ background: var(--bg-subtle);
}
.table-total-row {
- background: #f8fafc;
+ background: var(--bg-subtle);
border-top: 2px solid var(--border);
border-bottom: 2px solid var(--border);
}
@@ -1830,7 +2093,7 @@ code {
.score-progress-bar {
width: 75px;
height: 6px;
- background: #e2e8f0;
+ background: var(--bg-hover);
border-radius: 9999px;
overflow: hidden;
}
@@ -1876,7 +2139,7 @@ code {
}
.weakness-card {
- background: white;
+ background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 12px 14px;
@@ -1919,7 +2182,7 @@ code {
.modal-overlay {
position: fixed;
inset: 0;
- background: rgba(15, 23, 42, 0.55);
+ background: rgba(15, 23, 42, 0.65);
display: flex;
align-items: center;
justify-content: center;
@@ -1929,14 +2192,15 @@ code {
}
.modal-dialog.modal-xl {
- background: white;
+ background: var(--bg-card);
+ border: 1px solid var(--border);
border-radius: 12px;
width: 100%;
max-width: 980px;
max-height: 90vh;
display: flex;
flex-direction: column;
- box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.35);
overflow: hidden;
}
@@ -1946,7 +2210,7 @@ code {
align-items: center;
padding: 14px 20px;
border-bottom: 1px solid var(--border);
- background: white;
+ background: var(--bg-card);
}
.modal-title-group {
@@ -1980,7 +2244,7 @@ code {
.modal-close-btn:hover {
color: var(--text-main);
- background: #f1f5f9;
+ background: var(--bg-muted);
}
.modal-filter-bar {
@@ -1988,7 +2252,7 @@ code {
justify-content: space-between;
align-items: center;
padding: 10px 20px;
- background: #f8fafc;
+ background: var(--bg-subtle);
border-bottom: 1px solid var(--border);
gap: 12px;
flex-wrap: wrap;
@@ -2003,7 +2267,7 @@ code {
}
.modal-lesson-btn {
- background: white;
+ background: var(--bg-card);
border: 1px solid var(--border);
color: var(--text-muted);
padding: 4px 10px;
@@ -2016,7 +2280,7 @@ code {
}
.modal-lesson-btn:hover {
- background: #f1f5f9;
+ background: var(--bg-muted);
color: var(--text-main);
}
@@ -2033,7 +2297,7 @@ code {
}
.modal-type-btn {
- background: white;
+ background: var(--bg-card);
border: 1px solid var(--border);
color: var(--text-muted);
padding: 4px 8px;
@@ -2043,9 +2307,9 @@ code {
}
.modal-type-btn.active {
- background: #0f172a;
+ background: var(--primary);
color: white;
- border-color: #0f172a;
+ border-color: var(--primary);
font-weight: 600;
}
@@ -2053,7 +2317,7 @@ code {
padding: 20px;
overflow-y: auto;
flex: 1;
- background: #f8fafc;
+ background: var(--bg-page);
}
.questions-grid {
@@ -2063,14 +2327,14 @@ code {
}
.question-card {
- background: white;
+ background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px;
display: flex;
flex-direction: column;
gap: 10px;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.question-card-header {
@@ -2108,26 +2372,26 @@ code {
}
.answer-correct {
- background: #ecfdf5;
- color: #047857;
- border: 1px solid #a7f3d0;
+ background: var(--badge-success-bg);
+ color: var(--badge-success-text);
+ border: 1px solid var(--badge-success-border);
}
.answer-student-wrong {
- background: #fef2f2;
- color: #b91c1c;
- border: 1px solid #fecaca;
+ background: var(--badge-danger-bg);
+ color: var(--badge-danger-text);
+ border: 1px solid var(--badge-danger-border);
}
.answer-student-empty {
- background: #f1f5f9;
- color: #475569;
- border: 1px solid #e2e8f0;
+ background: var(--bg-muted);
+ color: var(--text-muted);
+ border: 1px solid var(--border);
}
.question-img-wrapper {
- background: #fafafa;
- border: 1px solid #f1f5f9;
+ background: #ffffff;
+ border: 1px solid var(--border);
border-radius: 6px;
padding: 8px;
text-align: center;
@@ -2211,7 +2475,7 @@ code {
.user-nav {
order: 2;
flex-shrink: 0;
- gap: 8px;
+ gap: 6px;
}
.user-id {
@@ -2239,7 +2503,7 @@ code {
.nav-item {
font-size: 0.8rem;
padding: 5px 12px;
- background: #f8fafc;
+ background: var(--bg-subtle);
border: 1px solid var(--border);
}
@@ -2284,15 +2548,15 @@ code {
}
.offline-banner.active {
- background: #fef3c7;
- color: #92400e;
- border-bottom: 1px solid #fde68a;
+ background: var(--badge-warning-bg);
+ color: var(--badge-warning-text);
+ border-bottom: 1px solid var(--badge-warning-border);
}
.offline-banner.online {
- background: #dcfce7;
- color: #166534;
- border-bottom: 1px solid #bbf7d0;
+ background: var(--badge-success-bg);
+ color: var(--badge-success-text);
+ border-bottom: 1px solid var(--badge-success-border);
}
.offline-banner.hidden {
@@ -2343,5 +2607,3 @@ code {
cursor: not-allowed;
opacity: 0.6;
}
-
-
diff --git a/public/js/app.js b/public/js/app.js
index 2991f31..1569830 100644
--- a/public/js/app.js
+++ b/public/js/app.js
@@ -18,6 +18,13 @@ document.addEventListener('DOMContentLoaded', () => {
let currentSearch = '';
let currentSubject = '';
+ function t(key, params) {
+ if (typeof window.BeKulturT === 'function') {
+ return window.BeKulturT(key, params);
+ }
+ return key;
+ }
+
// Checkbox toggle
if (assignmentList) {
assignmentList.addEventListener('click', async (e) => {
@@ -26,7 +33,7 @@ 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.');
+ alert(t('dashboard.offlineExcludeAlert'));
return;
}
const assignmentId = target.dataset.id;
@@ -47,8 +54,8 @@ document.addEventListener('DOMContentLoaded', () => {
if (data.success && data.stats) {
card.dataset.excluded = newExcluded ? 'true' : 'false';
card.classList.toggle('is-excluded', newExcluded);
- target.textContent = newExcluded ? 'Restore' : 'Exclude';
- target.title = newExcluded ? 'Restore this homework to your active list' : 'Exclude this homework (e.g. from another class)';
+ target.textContent = newExcluded ? t('dashboard.btnRestore') : t('dashboard.btnExclude');
+ target.title = newExcluded ? t('dashboard.btnRestoreTitle') : t('dashboard.btnExcludeTitle');
const checkbox = card.querySelector('.assignment-toggle');
if (checkbox) checkbox.disabled = newExcluded;
@@ -59,7 +66,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (badgesContainer) {
const b = document.createElement('span');
b.className = 'badge badge-excluded';
- b.textContent = 'Excluded';
+ b.textContent = t('dashboard.badgeExcluded');
badgesContainer.insertBefore(b, target);
}
} else if (!newExcluded && badgeExcluded) {
@@ -84,7 +91,7 @@ document.addEventListener('DOMContentLoaded', () => {
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.');
+ alert(t('dashboard.offlineToggleAlert'));
return;
}
@@ -131,21 +138,21 @@ document.addEventListener('DOMContentLoaded', () => {
if (existingStatusBadge) {
if (status === 'completed') {
existingStatusBadge.className = 'badge badge-completed';
- existingStatusBadge.textContent = 'Done';
+ existingStatusBadge.textContent = t('dashboard.badgeCompleted');
} else {
const orig = card.dataset.status;
if (orig === 'next-week') {
existingStatusBadge.className = 'badge badge-next-week';
- existingStatusBadge.textContent = 'Next Week';
+ existingStatusBadge.textContent = t('dashboard.badgeNextWeek');
} else if (orig === 'due-soon') {
existingStatusBadge.className = 'badge badge-due-soon';
- existingStatusBadge.textContent = 'Due Soon';
+ existingStatusBadge.textContent = t('dashboard.badgeDueSoon');
} else if (orig === 'overdue') {
existingStatusBadge.className = 'badge badge-overdue';
- existingStatusBadge.textContent = 'Overdue';
+ existingStatusBadge.textContent = t('dashboard.badgeOverdue');
} else {
existingStatusBadge.className = 'badge badge-active';
- existingStatusBadge.textContent = 'Active';
+ existingStatusBadge.textContent = t('dashboard.badgeActive');
}
}
}
@@ -162,7 +169,7 @@ document.addEventListener('DOMContentLoaded', () => {
const statTotal = document.getElementById('statTotalCount');
if (statCompRate) statCompRate.textContent = `${stats.completionRate}%`;
- if (statCompFrac) statCompFrac.textContent = `${stats.completed} / ${stats.total} done`;
+ if (statCompFrac) statCompFrac.textContent = `${stats.completed} / ${stats.total} ${t('dashboard.statDoneUnit')}`;
if (progressBar) progressBar.style.width = `${stats.completionRate}%`;
if (statActive) statActive.textContent = stats.active;
if (statNextWeek) statNextWeek.textContent = stats.checkedNextWeek;
@@ -310,7 +317,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
if (filteredCountText) {
- filteredCountText.textContent = `Showing ${visibleCount} assignments`;
+ filteredCountText.textContent = t('dashboard.showingCount', { count: visibleCount });
}
if (noResults) {
@@ -322,12 +329,12 @@ document.addEventListener('DOMContentLoaded', () => {
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');
+ showAlert(t('dashboard.offlineSyncAlert'), 'danger');
return;
}
btnSyncRecent.disabled = true;
- btnSyncRecent.textContent = 'Syncing...';
- showAlert('Fetching recent assignments...', 'info');
+ btnSyncRecent.textContent = t('dashboard.syncing');
+ showAlert(t('dashboard.fetchingRecent'), 'info');
try {
const res = await fetch('/api/sync', { method: 'POST' });
@@ -335,14 +342,14 @@ document.addEventListener('DOMContentLoaded', () => {
if (data.success) {
window.location.reload();
} else {
- showAlert(`Sync failed: ${data.error}`, 'danger');
+ showAlert(`${t('dashboard.syncFailed')} ${data.error}`, 'danger');
btnSyncRecent.disabled = false;
- btnSyncRecent.textContent = 'Sync Recent';
+ btnSyncRecent.textContent = t('dashboard.syncRecent');
}
} catch (err) {
- showAlert('Network error while syncing.', 'danger');
+ showAlert(t('dashboard.networkError'), 'danger');
btnSyncRecent.disabled = false;
- btnSyncRecent.textContent = 'Sync Recent';
+ btnSyncRecent.textContent = t('dashboard.syncRecent');
}
});
}
@@ -350,12 +357,12 @@ 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');
+ showAlert(t('dashboard.offlineSyncAlert'), 'danger');
return;
}
btnSyncAll.disabled = true;
- btnSyncAll.textContent = 'Syncing all...';
- showAlert('Syncing full history from portal...', 'info');
+ btnSyncAll.textContent = t('dashboard.syncingAll');
+ showAlert(t('dashboard.fetchingAll'), 'info');
try {
const res = await fetch('/api/sync-all', { method: 'POST' });
@@ -363,14 +370,14 @@ document.addEventListener('DOMContentLoaded', () => {
if (data.success) {
window.location.reload();
} else {
- showAlert(`Sync all failed: ${data.error}`, 'danger');
+ showAlert(`${t('dashboard.syncFailed')} ${data.error}`, 'danger');
btnSyncAll.disabled = false;
- btnSyncAll.textContent = 'Sync Full History';
+ btnSyncAll.textContent = t('dashboard.syncAll');
}
} catch (err) {
- showAlert('Network error while syncing full history.', 'danger');
+ showAlert(t('dashboard.networkError'), 'danger');
btnSyncAll.disabled = false;
- btnSyncAll.textContent = 'Sync Full History';
+ btnSyncAll.textContent = t('dashboard.syncAll');
}
});
}
diff --git a/public/js/exams.js b/public/js/exams.js
index 54dbe01..d0ac813 100644
--- a/public/js/exams.js
+++ b/public/js/exams.js
@@ -24,8 +24,6 @@ document.addEventListener('DOMContentLoaded', () => {
const modalTypeBtns = document.querySelectorAll('.modal-type-btn');
const questionsGrid = document.getElementById('questionsGrid');
const mistakeLoading = document.getElementById('mistakeLoading');
- const mistakeModalTitle = document.getElementById('mistakeModalTitle');
- const mistakeModalSubtitle = document.getElementById('mistakeModalSubtitle');
// Lightbox
const imageLightbox = document.getElementById('imageLightbox');
@@ -39,6 +37,13 @@ document.addEventListener('DOMContentLoaded', () => {
let activeTypeFilter = 'all'; // 'all' | 'wrong' | 'empty'
let cachedWeaknesses = null;
+ function t(key, params) {
+ if (typeof window.BeKulturT === 'function') {
+ return window.BeKulturT(key, params);
+ }
+ return key;
+ }
+
// ----------------------------------------------------
// Helper: Show Alert
// ----------------------------------------------------
@@ -97,14 +102,14 @@ document.addEventListener('DOMContentLoaded', () => {
// ----------------------------------------------------
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');
+ showAlert(t('dashboard.offlineSyncAlert'), 'danger');
return;
}
const triggerBtn = btnSyncExams || btnEmptySync;
if (triggerBtn) {
triggerBtn.disabled = true;
- triggerBtn.textContent = 'Syncing...';
+ triggerBtn.textContent = t('exams.syncing');
}
try {
@@ -117,17 +122,17 @@ document.addEventListener('DOMContentLoaded', () => {
if (data.success) {
window.location.reload();
} else {
- showAlert(data.error || 'Failed to sync exams', 'danger');
+ showAlert(data.error || t('dashboard.syncFailed'), 'danger');
if (triggerBtn) {
triggerBtn.disabled = false;
- triggerBtn.textContent = 'Sync Exams';
+ triggerBtn.textContent = t('exams.syncBtn');
}
}
} catch (err) {
- showAlert('Connection error while syncing exams.', 'danger');
+ showAlert(t('dashboard.networkError'), 'danger');
if (triggerBtn) {
triggerBtn.disabled = false;
- triggerBtn.textContent = 'Sync Exams';
+ triggerBtn.textContent = t('exams.syncBtn');
}
}
}
@@ -173,14 +178,14 @@ document.addEventListener('DOMContentLoaded', () => {
} else {
weaknessContainer.innerHTML = `
-
Bu sınav için henüz zayıf konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.
+
${escapeHtml(t('exams.weaknessEmpty'))}
`;
}
} catch (err) {
weaknessLoading.classList.add('hidden');
weaknessContainer.innerHTML = `
- Zayıf konu raporu yüklenirken bir hata oluştu.
+ ${escapeHtml(t('exams.weaknessError'))}
`;
}
}
@@ -206,10 +211,10 @@ document.addEventListener('DOMContentLoaded', () => {
- Toplam: ${item.totalCount}
- Doğru: ${item.correctCount}
- Yanlış: ${item.wrongCount}
- Boş: ${item.emptyCount}
+ ${escapeHtml(t('exams.weaknessTotal'))} ${item.totalCount}
+ ${escapeHtml(t('exams.weaknessCorrect'))} ${item.correctCount}
+ ${escapeHtml(t('exams.weaknessWrong'))} ${item.wrongCount}
+ ${escapeHtml(t('exams.weaknessEmptyCount'))} ${item.emptyCount}
`;
@@ -340,7 +345,7 @@ document.addEventListener('DOMContentLoaded', () => {
} catch (err) {
mistakeLoading.classList.add('hidden');
questionsGrid.innerHTML = `
- Sorular yüklenirken bir hata oluştu.
+ ${escapeHtml(t('exams.modalError'))}
`;
}
}
@@ -355,7 +360,7 @@ document.addEventListener('DOMContentLoaded', () => {
let html = `
`;
@@ -419,7 +424,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (filteredList.length === 0) {
questionsGrid.innerHTML = `
-
Seçili filtrelere uygun soru bulunamadı.
+
${escapeHtml(t('exams.modalNoMatch'))}
`;
return;
@@ -429,32 +434,32 @@ document.addEventListener('DOMContentLoaded', () => {
filteredList.forEach(q => {
const isWrong = q.status === 'wrong';
const studentClass = isWrong ? 'answer-student-wrong' : 'answer-student-empty';
- const studentText = isWrong ? q.studentAnswer : 'Boş';
+ const studentText = isWrong ? q.studentAnswer : t('exams.emptyAnswerText');
html += `
- Doğru: ${escapeHtml(q.correctAnswer)}
+ ${escapeHtml(t('exams.correctAnswer'))} ${escapeHtml(q.correctAnswer)}
- Öğrenci: ${escapeHtml(studentText)}
+ ${escapeHtml(t('exams.studentAnswer'))} ${escapeHtml(studentText)}
${
q.imageUrl
? `
-
+
`
- : `
Soru görseli bulunamadı.
`
+ : `
${escapeHtml(t('exams.noImage'))}
`
}
`;
diff --git a/public/js/private-lessons.js b/public/js/private-lessons.js
index a73cd95..975c59e 100644
--- a/public/js/private-lessons.js
+++ b/public/js/private-lessons.js
@@ -13,6 +13,13 @@ document.addEventListener('DOMContentLoaded', () => {
const lessonCards = document.querySelectorAll('.lesson-card');
const sinifIdInput = document.getElementById('sinifId');
+ function t(key, params) {
+ if (typeof window.BeKulturT === 'function') {
+ return window.BeKulturT(key, params);
+ }
+ return key;
+ }
+
function showAlert(message, type = 'info', timeout = 4000) {
if (!alertBox) return;
alertBox.className = `alert alert-${type}`;
@@ -44,9 +51,9 @@ document.addEventListener('DOMContentLoaded', () => {
const dersId = selectCourse.value;
const sinifId = sinifIdInput ? sinifIdInput.value : '';
- selectUnit.innerHTML = '
';
+ selectUnit.innerHTML = `
`;
selectUnit.disabled = true;
- selectTopic.innerHTML = '
';
+ selectTopic.innerHTML = `
`;
selectTopic.disabled = true;
if (btnSubmit) btnSubmit.disabled = true;
@@ -59,7 +66,7 @@ document.addEventListener('DOMContentLoaded', () => {
const data = await res.json();
if (data.success && data.units && data.units.length > 0) {
- selectUnit.innerHTML = '
';
+ selectUnit.innerHTML = `
`;
data.units.forEach(u => {
const opt = document.createElement('option');
opt.value = u.id;
@@ -68,11 +75,11 @@ document.addEventListener('DOMContentLoaded', () => {
});
selectUnit.disabled = false;
} else {
- selectUnit.innerHTML = '
';
+ selectUnit.innerHTML = `
`;
}
} catch (err) {
console.error('Error fetching units:', err);
- selectUnit.innerHTML = '
';
+ selectUnit.innerHTML = `
`;
} finally {
if (unitLoading) unitLoading.classList.add('hidden');
}
@@ -85,7 +92,7 @@ document.addEventListener('DOMContentLoaded', () => {
hideFeedback();
const uniteId = selectUnit.value;
- selectTopic.innerHTML = '
';
+ selectTopic.innerHTML = `
`;
selectTopic.disabled = true;
if (btnSubmit) btnSubmit.disabled = true;
@@ -98,20 +105,20 @@ document.addEventListener('DOMContentLoaded', () => {
const data = await res.json();
if (data.success && data.topics && data.topics.length > 0) {
- selectTopic.innerHTML = '
';
- data.topics.forEach(t => {
+ selectTopic.innerHTML = `
`;
+ data.topics.forEach(tItem => {
const opt = document.createElement('option');
- opt.value = t.id;
- opt.textContent = t.name;
+ opt.value = tItem.id;
+ opt.textContent = tItem.name;
selectTopic.appendChild(opt);
});
selectTopic.disabled = false;
} else {
- selectTopic.innerHTML = '
';
+ selectTopic.innerHTML = `
`;
}
} catch (err) {
console.error('Error fetching topics:', err);
- selectTopic.innerHTML = '
';
+ selectTopic.innerHTML = `
`;
} finally {
if (topicLoading) topicLoading.classList.add('hidden');
}
@@ -134,7 +141,7 @@ document.addEventListener('DOMContentLoaded', () => {
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');
+ showFeedback(t('dashboard.offlineSyncAlert'), 'error');
return;
}
@@ -152,7 +159,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (btnSubmit) {
btnSubmit.disabled = true;
- btnSubmit.textContent = 'Gönderiliyor...';
+ btnSubmit.textContent = t('privateLessons.submittingBtn');
}
try {
@@ -167,9 +174,9 @@ document.addEventListener('DOMContentLoaded', () => {
if (data.success) {
showFeedback(data.message || 'Özel ders talebiniz başarıyla iletildi!', 'success');
// Reset select elements
- selectTopic.innerHTML = '
';
+ selectTopic.innerHTML = `
`;
selectTopic.disabled = true;
- selectUnit.innerHTML = '
';
+ selectUnit.innerHTML = `
`;
selectUnit.disabled = true;
selectCourse.value = '';
} else {
@@ -180,7 +187,7 @@ document.addEventListener('DOMContentLoaded', () => {
showFeedback('Bağlantı hatası oluştu. Lütfen tekrar deneyiniz.', 'error');
} finally {
if (btnSubmit) {
- btnSubmit.textContent = 'Submit Request (Gönder)';
+ btnSubmit.textContent = t('privateLessons.submitBtn');
}
}
});
@@ -208,26 +215,30 @@ document.addEventListener('DOMContentLoaded', () => {
// 6. Sync Lessons
if (btnSync) {
btnSync.addEventListener('click', async () => {
+ if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
+ showAlert(t('dashboard.offlineSyncAlert'), 'danger');
+ return;
+ }
btnSync.disabled = true;
- btnSync.textContent = 'Syncing...';
+ btnSync.textContent = t('privateLessons.syncing');
try {
const res = await fetch('/api/private-lessons/sync', { method: 'POST' });
const data = await res.json();
if (data.success) {
- showAlert(`Successfully refreshed ${data.count} private lesson records.`, 'success');
+ showAlert(t('privateLessons.syncSuccess', { count: data.count }), 'info');
setTimeout(() => {
window.location.reload();
}, 800);
} else {
- showAlert(data.error || 'Sync failed.', 'danger');
+ showAlert(data.error || t('dashboard.syncFailed'), 'danger');
}
} catch (err) {
- showAlert('Network error while syncing private lessons.', 'danger');
+ showAlert(t('dashboard.networkError'), 'danger');
} finally {
btnSync.disabled = false;
- btnSync.textContent = 'Sync Lessons';
+ btnSync.textContent = t('privateLessons.syncBtn');
}
});
}
diff --git a/public/js/pwa.js b/public/js/pwa.js
index 14af080..7d69c5d 100644
--- a/public/js/pwa.js
+++ b/public/js/pwa.js
@@ -1,10 +1,98 @@
/**
- * BeKultur - PWA & Offline State Manager
+ * BeKultur - PWA, Theme & Offline State Manager
*/
(function () {
let isOffline = !navigator.onLine;
let bannerTimeout = null;
+ function t(key, params) {
+ if (typeof window.BeKulturT === 'function') {
+ return window.BeKulturT(key, params);
+ }
+ return key;
+ }
+
+ // ----------------------------------------------------
+ // 0. Dark / Light Theme Manager (System-Aware + Override)
+ // ----------------------------------------------------
+ function getSystemScheme() {
+ return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
+ ? 'dark'
+ : 'light';
+ }
+
+ function getStoredScheme() {
+ try {
+ const val = localStorage.getItem('color-scheme');
+ if (val === 'dark' || val === 'light') return val;
+ } catch (e) {}
+ return null;
+ }
+
+ function getResolvedScheme() {
+ return getStoredScheme() || getSystemScheme();
+ }
+
+ function applyThemeScheme(storedOverride) {
+ const meta = document.querySelector('meta[name="color-scheme"]');
+ const resolved = storedOverride === 'dark' || storedOverride === 'light'
+ ? storedOverride
+ : getSystemScheme();
+
+ if (meta) {
+ meta.content = storedOverride === 'dark' || storedOverride === 'light'
+ ? storedOverride
+ : 'light dark';
+ }
+ document.documentElement.setAttribute('data-theme', resolved);
+ }
+
+ function initThemeToggle() {
+ // Ensure initial attribute is synced
+ applyThemeScheme(getStoredScheme());
+
+ const toggleBtn = document.getElementById('themeToggleBtn');
+ if (toggleBtn) {
+ toggleBtn.addEventListener('click', () => {
+ const currentRendered = getResolvedScheme();
+ const target = currentRendered === 'dark' ? 'light' : 'dark';
+ const sys = getSystemScheme();
+
+ try {
+ if (target === sys) {
+ // Revert to system default when target matches system preference
+ localStorage.removeItem('color-scheme');
+ applyThemeScheme(null);
+ } else {
+ localStorage.setItem('color-scheme', target);
+ applyThemeScheme(target);
+ }
+ } catch (e) {
+ applyThemeScheme(target);
+ }
+ });
+ }
+
+ // Listen for OS theme changes when following system default
+ if (window.matchMedia) {
+ const mql = window.matchMedia('(prefers-color-scheme: dark)');
+ if (mql.addEventListener) {
+ mql.addEventListener('change', () => {
+ if (!getStoredScheme()) {
+ applyThemeScheme(null);
+ }
+ });
+ }
+ }
+
+ // Keep tabs in sync
+ window.addEventListener('storage', (e) => {
+ if (e.key === 'color-scheme') {
+ applyThemeScheme(getStoredScheme());
+ }
+ });
+ }
+
// 1. Service Worker Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
@@ -50,8 +138,8 @@
banner.className = 'offline-banner active';
banner.innerHTML = `
- ⚡ Offline
- Showing locally cached data. Actions requiring connection are paused.
+ ${t('pwa.offlineBadge')}
+ ${t('pwa.offlineText')}
`;
}
@@ -65,8 +153,8 @@
banner.className = 'offline-banner online';
banner.innerHTML = `
- ✓ Online
- Connection restored. Live features re-enabled.
+ ${t('pwa.onlineBadge')}
+ ${t('pwa.onlineText')}
`;
bannerTimeout = setTimeout(() => {
@@ -93,7 +181,7 @@
if (offline) {
checkbox.disabled = true;
- checkbox.title = 'Offline mode: Homework status cannot be changed without connection.';
+ checkbox.title = t('pwa.offlineCheckboxTitle');
} else {
// Only re-enable if not excluded
checkbox.disabled = isExcluded;
@@ -105,16 +193,17 @@
excludeButtons.forEach((btn) => {
if (offline) {
btn.disabled = true;
- btn.title = 'Offline mode: Homework cannot be excluded without connection.';
+ btn.title = t('pwa.offlineExcludeTitle');
} else {
btn.disabled = false;
- btn.title = btn.textContent.trim() === 'Restore' ? 'Restore homework' : 'Exclude homework';
+ const card = btn.closest('.assignment-card');
+ const isExcl = card && card.dataset.excluded === 'true';
+ btn.title = isExcl ? t('dashboard.btnRestoreTitle') : t('dashboard.btnExcludeTitle');
}
});
// --- B. Private Lesson Request Form ---
const lessonForm = document.getElementById('privateLessonForm');
- const btnSubmitLesson = document.getElementById('btnSubmitRequest');
const formSelects = document.querySelectorAll('#privateLessonForm select, #privateLessonForm button[type="submit"]');
let noticeEl = document.getElementById('privateLessonOfflineNotice');
@@ -123,7 +212,7 @@
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.';
+ noticeEl.innerHTML = t('pwa.offlinePrivateNotice');
lessonForm.prepend(noticeEl);
}
@@ -145,7 +234,7 @@
stationButtons.forEach((btn) => {
if (offline) {
btn.classList.add('station-btn-offline');
- btn.title = 'Offline mode: Station selection requires connection.';
+ btn.title = t('pwa.offlineStationTitle');
} else {
btn.classList.remove('station-btn-offline');
btn.title = '';
@@ -172,8 +261,8 @@
}
btn.disabled = true;
btn.classList.add('btn-offline-disabled');
- btn.title = 'Offline mode: Sync requires internet connection.';
- btn.textContent = `${btn.dataset.onlineLabel} (Offline)`;
+ btn.title = t('pwa.offlineSyncTitle');
+ btn.textContent = `${btn.dataset.onlineLabel} ${t('pwa.offlineSuffix')}`;
} else {
btn.disabled = false;
btn.classList.remove('btn-offline-disabled');
@@ -195,7 +284,7 @@
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.');
+ alert(t('dashboard.offlineToggleAlert'));
}
},
true
@@ -213,11 +302,13 @@
// 6. Initial Application on DOM Ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
+ initThemeToggle();
if (!navigator.onLine) {
applyOfflineState(true);
}
});
} else {
+ initThemeToggle();
if (!navigator.onLine) {
applyOfflineState(true);
}
@@ -226,6 +317,7 @@
// Export helper globally
window.BeKulturPWA = {
isOffline: () => isOffline,
- refreshState: () => applyOfflineState(!navigator.onLine)
+ refreshState: () => applyOfflineState(!navigator.onLine),
+ getTheme: () => getResolvedScheme()
};
})();
diff --git a/public/js/syllabus.js b/public/js/syllabus.js
index 7bcfa53..a0e67a6 100644
--- a/public/js/syllabus.js
+++ b/public/js/syllabus.js
@@ -7,6 +7,13 @@ document.addEventListener('DOMContentLoaded', () => {
const btnSyncSyllabus = document.getElementById('btnSyncSyllabus');
const syllabusAlert = document.getElementById('syllabusAlert');
+ function t(key, params) {
+ if (typeof window.BeKulturT === 'function') {
+ return window.BeKulturT(key, params);
+ }
+ return key;
+ }
+
// 1. Station Pill Selection (AJAX)
if (stationPills) {
stationPills.addEventListener('click', async (e) => {
@@ -14,7 +21,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (!btn) return;
if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) {
- showAlert('Çevrimdışı moddasınız. İstasyon seçimi için internet bağlantısı gereklidir.', 'danger');
+ showAlert(t('syllabus.offlineStationAlert'), 'danger');
return;
}
@@ -80,28 +87,28 @@ document.addEventListener('DOMContentLoaded', () => {
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');
+ showAlert(t('dashboard.offlineSyncAlert'), 'danger');
return;
}
btnSyncSyllabus.disabled = true;
- btnSyncSyllabus.textContent = 'Syncing...';
- showAlert('Fetching weekly timetable across all 5 days...', 'info');
+ btnSyncSyllabus.textContent = t('syllabus.syncing');
+ showAlert(t('syllabus.fetchingAlert'), 'info');
try {
const res = await fetch('/api/syllabus/sync', { method: 'POST' });
const data = await res.json();
if (data.success) {
- showAlert('Syllabus updated successfully!', 'info');
+ showAlert(t('syllabus.updatedAlert'), 'info');
window.location.reload();
} else {
- showAlert(`Sync failed: ${data.error}`, 'danger');
+ showAlert(`${t('dashboard.syncFailed')} ${data.error}`, 'danger');
btnSyncSyllabus.disabled = false;
- btnSyncSyllabus.textContent = 'Sync Syllabus';
+ btnSyncSyllabus.textContent = t('syllabus.syncBtn');
}
} catch (err) {
- showAlert('Network error while syncing syllabus.', 'danger');
+ showAlert(t('dashboard.networkError'), 'danger');
btnSyncSyllabus.disabled = false;
- btnSyncSyllabus.textContent = 'Sync Syllabus';
+ btnSyncSyllabus.textContent = t('syllabus.syncBtn');
}
});
}
diff --git a/public/sw.js b/public/sw.js
index da60ad8..bd6063e 100644
--- a/public/sw.js
+++ b/public/sw.js
@@ -1,4 +1,4 @@
-const CACHE_NAME = 'bekultur-v2';
+const CACHE_NAME = 'bekultur-v3';
const STATIC_ASSETS = [
'/',
diff --git a/src/server.ts b/src/server.ts
index 5ca4525..e23b4b2 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -1,6 +1,8 @@
import express, { Request, Response, NextFunction } from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
+import helmet from 'helmet';
+import rateLimit from 'express-rate-limit';
import path from 'path';
import dotenv from 'dotenv';
import { ScraperService } from './services/scraper';
@@ -8,13 +10,25 @@ import { LocalDatabase } from './services/db';
import { InsightService } from './services/insight';
import { SyllabusService, DAY_NAMES } from './services/syllabus';
import { ExamService } from './services/exam';
+import { getSessionSecret } from './services/secrets';
+import { SQLiteSessionStore } from './services/session-store';
+import {
+ SupportedLocale,
+ DEFAULT_LOCALE,
+ normalizeLocale,
+ createTranslator,
+ getClientDictionary
+} from './services/i18n';
import { Assignment, ExamReportDetail } 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';
+const SESSION_SECRET = getSessionSecret();
+
+// Trust first proxy (Cloudflare Tunnel / reverse proxy) so secure cookies work over proxied HTTPS
+app.set('trust proxy', 1);
// View engine setup
app.set('view engine', 'ejs');
@@ -23,11 +37,61 @@ 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());
+// Security Headers (Helmet with CSP tailored for BeKultur & school portal question images)
+app.use(
+ helmet({
+ contentSecurityPolicy: {
+ directives: {
+ defaultSrc: ["'self'"],
+ scriptSrc: ["'self'", "'unsafe-inline'"],
+ scriptSrcAttr: ["'unsafe-inline'"],
+ styleSrc: ["'self'", "'unsafe-inline'"],
+ imgSrc: [
+ "'self'",
+ 'data:',
+ 'https://*.ozelbursakulturokullari.com',
+ 'http://*.ozelbursakulturokullari.com'
+ ],
+ connectSrc: ["'self'"],
+ fontSrc: ["'self'", 'data:'],
+ objectSrc: ["'none'"],
+ frameAncestors: ["'none'"],
+ upgradeInsecureRequests: null
+ }
+ },
+ crossOriginEmbedderPolicy: false,
+ crossOriginResourcePolicy: { policy: 'cross-origin' }
+ })
+);
+
+// Body & Cookie Parsers
+app.use(express.urlencoded({ extended: true, limit: '256kb' }));
+app.use(express.json({ limit: '256kb' }));
app.use(cookieParser(SESSION_SECRET));
+// Localization Middleware (Default: Turkish 'tr', switchable to 'en')
+app.use((req: Request, res: Response, next: NextFunction) => {
+ let lang: SupportedLocale = DEFAULT_LOCALE;
+
+ if (typeof req.query.lang === 'string' && (req.query.lang === 'tr' || req.query.lang === 'en')) {
+ lang = normalizeLocale(req.query.lang);
+ res.cookie('bekultur_lang', lang, {
+ maxAge: 365 * 24 * 60 * 60 * 1000,
+ httpOnly: false,
+ sameSite: 'lax'
+ });
+ } else if (req.cookies?.bekultur_lang) {
+ lang = normalizeLocale(req.cookies.bekultur_lang);
+ }
+
+ const t = createTranslator(lang);
+ res.locals.lang = lang;
+ res.locals.t = t;
+ res.locals.i18nJson = JSON.stringify(getClientDictionary(lang));
+ res.locals.activePage = '';
+ next();
+});
+
// Custom Service Worker route with proper scope and no-cache headers
app.get('/sw.js', (req: Request, res: Response) => {
res.setHeader('Service-Worker-Allowed', '/');
@@ -43,8 +107,17 @@ app.get('/api/health', (req: Request, res: Response) => {
app.use(express.static(publicPath));
+// Initialize SQLite Database & Persistent SQLite Session Store
+const db = LocalDatabase.getInstance();
+const sessionStore = new SQLiteSessionStore({
+ db: db.getSqliteDb(),
+ ttlMs: 14 * 24 * 60 * 60 * 1000
+});
+
app.use(
session({
+ store: sessionStore,
+ name: 'bekultur.sid',
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
@@ -52,11 +125,32 @@ app.use(
maxAge: 14 * 24 * 60 * 60 * 1000, // 14 days
httpOnly: true,
sameSite: 'lax',
- secure: process.env.NODE_ENV === 'production'
+ secure: process.env.COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'false')
}
})
);
+// Rate Limiters for Production Hardening
+const isTestEnv = process.env.NODE_ENV === 'test';
+
+const loginLimiter = rateLimit({
+ windowMs: 15 * 60 * 1000, // 15 minutes
+ max: isTestEnv ? 1000 : 20,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: 'Çok fazla giriş denemesi yapıldı. Lütfen 15 dakika sonra tekrar deneyiniz.'
+});
+
+const apiLimiter = rateLimit({
+ windowMs: 1 * 60 * 1000, // 1 minute
+ max: isTestEnv ? 5000 : 120,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: { success: false, error: 'Çok fazla istek gönderildi. Lütfen biraz bekleyiniz.' }
+});
+
+app.use('/api/', apiLimiter);
+
// Augment express-session
declare module 'express-session' {
interface SessionData {
@@ -66,7 +160,36 @@ declare module 'express-session' {
}
}
-const db = LocalDatabase.getInstance();
+// Language Switcher Endpoints
+app.get('/lang/:locale', (req: Request, res: Response) => {
+ const locale = normalizeLocale(req.params.locale);
+ res.cookie('bekultur_lang', locale, {
+ maxAge: 365 * 24 * 60 * 60 * 1000,
+ httpOnly: false,
+ sameSite: 'lax'
+ });
+ const referer = req.get('Referer') || '/';
+ // Avoid open redirect: only allow relative paths or same host
+ if (referer.startsWith('/')) {
+ return res.redirect(referer);
+ }
+ try {
+ const refUrl = new URL(referer);
+ return res.redirect(refUrl.pathname + refUrl.search);
+ } catch {
+ return res.redirect('/');
+ }
+});
+
+app.post('/api/preferences/lang', (req: Request, res: Response) => {
+ const locale = normalizeLocale(req.body?.lang);
+ res.cookie('bekultur_lang', locale, {
+ maxAge: 365 * 24 * 60 * 60 * 1000,
+ httpOnly: false,
+ sameSite: 'lax'
+ });
+ res.json({ success: true, lang: locale });
+});
// Auth guard helper
function requireAuth(req: Request, res: Response, next: NextFunction) {
@@ -176,9 +299,16 @@ async function executeWithPortalSession
(
}
// ----------------------------------------------------
-// Routes
+// Routes & Official E-Kültür Aliases
// ----------------------------------------------------
+app.get('/login', (req: Request, res: Response) => res.redirect('/'));
+app.get('/Kullanici/Giris', (req: Request, res: Response) => res.redirect('/'));
+app.get('/giris', (req: Request, res: Response) => res.redirect('/'));
+app.get('/Odev', (req: Request, res: Response) => res.redirect('/dashboard'));
+app.get('/odev', (req: Request, res: Response) => res.redirect('/dashboard'));
+app.get('/dersprogrami', (req: Request, res: Response) => res.redirect('/syllabus'));
+
/**
* GET /
* Login Page
@@ -190,11 +320,13 @@ app.get('/', (req: Request, res: Response) => {
const rememberedId = req.signedCookies?.bekultur_student_id || '';
const error = (req.query.error as string) || null;
+ const t = res.locals.t;
res.render('login', {
error,
rememberedId,
- title: 'Login - BeKultur (Better E-Kultur)'
+ activePage: 'login',
+ title: t('login.pageTitle')
});
});
@@ -202,51 +334,56 @@ app.get('/', (req: Request, res: Response) => {
* POST /login
* Authenticate against portal and scrape recent assignments
*/
-app.post('/login', async (req: Request, res: Response) => {
+app.post('/login', loginLimiter, async (req: Request, res: Response) => {
const { studentId, password, rememberMe } = req.body;
+ const t = res.locals.t;
+ const cleanStudentId = typeof studentId === 'string' ? studentId.trim() : '';
+ const cleanPassword = typeof password === 'string' ? password : '';
- if (!studentId || !password) {
+ if (!cleanStudentId || !cleanPassword) {
return res.render('login', {
- error: 'Please enter both Student ID and Password.',
- rememberedId: studentId || '',
- title: 'Login - BeKultur'
+ error: t('login.errorMissing'),
+ rememberedId: cleanStudentId,
+ activePage: 'login',
+ title: t('login.pageTitle')
});
}
try {
- const loginRes = await ScraperService.login(studentId, password);
+ const loginRes = await ScraperService.login(cleanStudentId, cleanPassword);
if (!loginRes.success) {
return res.render('login', {
- error: loginRes.error || 'Authentication failed. Please check your credentials.',
- rememberedId: studentId,
- title: 'Login - BeKultur'
+ error: loginRes.error || t('login.errorInvalid'),
+ rememberedId: cleanStudentId,
+ activePage: 'login',
+ title: t('login.pageTitle')
});
}
- req.session.studentId = studentId;
+ req.session.studentId = cleanStudentId;
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, {
+ db.saveCredentials(cleanStudentId, cleanPassword);
+ res.cookie('bekultur_student_id', cleanStudentId, {
signed: true,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true,
sameSite: 'lax',
- secure: process.env.NODE_ENV === 'production'
+ secure: process.env.COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'false')
});
} else {
- db.clearCredentials(studentId);
+ db.clearCredentials(cleanStudentId);
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);
+ const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, cleanStudentId, 2);
+ db.mergeAssignments(cleanStudentId, scrapeRes.assignments);
} catch (scrapeErr: any) {
console.warn('Initial scrape warning (cached data will be used if available):', scrapeErr.message);
}
@@ -255,9 +392,10 @@ app.post('/login', async (req: Request, res: Response) => {
} 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'
+ error: t('login.errorServer'),
+ rememberedId: cleanStudentId,
+ activePage: 'login',
+ title: t('login.pageTitle')
});
}
});
@@ -284,11 +422,12 @@ app.get('/logout', (req: Request, res: Response) => {
/**
* GET /dashboard
- * English dashboard with stats and checkable assignments
+ * Homework (Ödevler) dashboard with stats and checkable assignments
*/
app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const studentStore = db.getStudentStore(studentId);
+ const t = res.locals.t;
// Recalculate status for each assignment relative to current date
const rawList = Object.values(studentStore.assignments);
@@ -327,9 +466,10 @@ app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
});
res.render('dashboard', {
- title: 'Dashboard - BeKultur',
+ title: t('dashboard.pageTitle'),
+ activePage: 'dashboard',
studentId,
- studentName: req.session.studentName || `Student ${studentId}`,
+ studentName: req.session.studentName || `${t('dashboard.studentLabel')} ${studentId}`,
lastSynced: studentStore.lastSynced,
stats,
assignments: updatedAssignments,
@@ -345,7 +485,7 @@ app.post('/api/toggle', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { assignmentId, completed } = req.body;
- if (!assignmentId) {
+ if (!assignmentId || typeof assignmentId !== 'string') {
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
}
@@ -377,7 +517,7 @@ app.post('/api/exclude', requireAuth, (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const { assignmentId, excluded } = req.body;
- if (!assignmentId) {
+ if (!assignmentId || typeof assignmentId !== 'string') {
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
}
@@ -481,6 +621,8 @@ app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
const currentWeek = SyllabusService.getWeekMetadata();
+ const t = res.locals.t;
+ const lang = res.locals.lang as SupportedLocale;
let syllabusStore = db.getSyllabus(studentId);
@@ -504,7 +646,8 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
// 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;
+ const parsedQueryDay = req.query.day ? parseInt(req.query.day as string, 10) : defaultDay;
+ const activeDay = parsedQueryDay >= 1 && parsedQueryDay <= 5 ? parsedQueryDay : defaultDay;
// Compute filtered schedule for selected station & advisory teacher
const rawSchedule = syllabusStore?.schedule || {};
@@ -515,11 +658,14 @@ app.get('/syllabus', requireAuth, async (req: Request, res: Response) => {
const currentStatus = SyllabusService.getCurrentLessonStatus(
filteredSchedule[activeDay] || [],
- activeDay
+ activeDay,
+ new Date(),
+ lang
);
res.render('syllabus', {
- title: 'Syllabus - BeKultur',
+ title: t('syllabus.pageTitle'),
+ activePage: 'syllabus',
studentId,
weekId: currentWeek.weekId,
weekRange: currentWeek.weekRange,
@@ -636,6 +782,7 @@ app.post('/api/syllabus/sync', requireAuth, async (req: Request, res: Response)
app.get('/private-lessons', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let store = db.getPrivateLessons(studentId);
+ const t = res.locals.t;
// If not yet synced or formMeta missing, try auto-syncing
if (!store || !store.lessons || !store.formMeta) {
@@ -661,9 +808,10 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) =>
const subjects = Array.from(new Set(allLessons.map(l => l.subject))).sort();
res.render('private-lessons', {
- title: 'Private Lessons - BeKultur',
+ title: t('privateLessons.pageTitle'),
+ activePage: 'private-lessons',
studentId,
- studentName: req.session.studentName || store?.formMeta?.studentName || `Student ${studentId}`,
+ studentName: req.session.studentName || store?.formMeta?.studentName || `${t('dashboard.studentLabel')} ${studentId}`,
formMeta: store?.formMeta || null,
detectedAdvisor: store?.detectedAdvisor || db.getStudentAdvisoryTeacher(studentId) || null,
lastSynced: store?.lastSynced || null,
@@ -678,6 +826,7 @@ app.get('/private-lessons', requireAuth, async (req: Request, res: Response) =>
* Redirect shortcuts
*/
app.get('/ozelders', (req: Request, res: Response) => res.redirect('/private-lessons'));
+app.get('/OzelDers', (req: Request, res: Response) => res.redirect('/private-lessons'));
app.get('/ozeldersistek', (req: Request, res: Response) => res.redirect('/private-lessons'));
/**
@@ -801,6 +950,7 @@ app.get('/rapor/sinav', (req: Request, res: Response) => {
app.get('/exams', requireAuth, async (req: Request, res: Response) => {
const studentId = req.session.studentId!;
let examStore = db.getExamReports(studentId);
+ const t = res.locals.t;
// If no cached exams or empty, sync now
if (!examStore || !examStore.reports || Object.keys(examStore.reports).length === 0) {
@@ -842,7 +992,8 @@ app.get('/exams', requireAuth, async (req: Request, res: Response) => {
const kpis = ExamService.calculateKPIs(processedExams);
res.render('exams', {
- title: 'Sınav Raporları - BeKultur',
+ title: t('exams.pageTitle'),
+ activePage: 'exams',
studentId,
studentName: req.session.studentName || '',
allExams: processedExams,
@@ -863,7 +1014,7 @@ app.get('/api/exams/:id', requireAuth, async (req: Request, res: Response) => {
const examId = req.params.id;
let examStore = db.getExamReports(studentId);
- let exam = examStore?.reports?.[examId];
+ const exam = examStore?.reports?.[examId];
if (!exam) {
try {
@@ -917,7 +1068,7 @@ app.get('/api/exams/:id/questions', requireAuth, async (req: Request, res: Respo
}
}
- // Check if all questions for this exam and tip are cached in db.json
+ // Check if all questions for this exam and tip are cached in SQLite
const cachedQuestions = db.getExamQuestions(studentId, cacheKey);
if (cachedQuestions && cachedQuestions.length > 0) {
const subjectsMap: Record = {};
@@ -1071,14 +1222,30 @@ app.post('/api/exams/sync', requireAuth, async (req: Request, res: Response) =>
}
});
-// Start Server
+// Start Server & Graceful Shutdown
if (process.env.NODE_ENV !== 'test') {
- app.listen(PORT, () => {
+ const server = app.listen(PORT, () => {
console.log(`=========================================`);
console.log(` BeKultur (Better E-Kultur) Server`);
console.log(` Running at: http://localhost:${PORT}`);
console.log(`=========================================`);
});
+
+ const shutdown = (signal: string) => {
+ console.log(`\n[${signal}] Shutting down BeKultur server gracefully...`);
+ sessionStore.stopPruning();
+ server.close(() => {
+ db.close();
+ process.exit(0);
+ });
+ setTimeout(() => {
+ db.close();
+ process.exit(0);
+ }, 5000).unref();
+ };
+
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('SIGINT', () => shutdown('SIGINT'));
}
export default app;
diff --git a/src/services/db.ts b/src/services/db.ts
index 96ca5c7..bdc531f 100644
--- a/src/services/db.ts
+++ b/src/services/db.ts
@@ -1,6 +1,7 @@
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
+import Database from 'better-sqlite3';
import {
DatabaseSchema,
StudentStore,
@@ -11,61 +12,78 @@ import {
ExamReportDetail,
ExamStore,
ExamTopicWeakness,
- ExamQuestionItem
+ ExamQuestionItem,
+ SyllabusStore
} from '../types';
+import {
+ encryptCredential,
+ decryptCredential
+} from './secrets';
-const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json');
+const DEFAULT_DB_FILE = path.resolve(process.cwd(), 'data', 'bekultur.db');
+const DEFAULT_LEGACY_JSON_FILE = path.resolve(process.cwd(), 'data', 'db.json');
-// Derive 32-byte AES key from environment secret
-function getEncryptionKey(): Buffer {
- const secret = process.env.ENCRYPTION_SECRET || process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
- return crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
+const SYNTHETIC_TEST_ID_REGEX = /^(test_student_|audit_)/i;
+
+interface StudentRow {
+ student_id: string;
+ last_synced: string | null;
+ remembered_password: string | null;
+ advisory_teacher: string | null;
+ syllabus_json: string | null;
+ private_lessons_json: string | null;
+ exams_json: string | null;
}
-function encryptCredential(plaintext: string): string {
- try {
- const key = getEncryptionKey();
- const iv = crypto.randomBytes(12);
- const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
- let encrypted = cipher.update(plaintext, 'utf8', 'hex');
- encrypted += cipher.final('hex');
- const authTag = cipher.getAuthTag().toString('hex');
- return `enc:${iv.toString('hex')}:${authTag}:${encrypted}`;
- } catch (err) {
- console.error('Failed to encrypt credential:', err);
- return plaintext;
- }
-}
-
-function decryptCredential(stored: string): string {
- if (!stored || !stored.startsWith('enc:')) {
- // Legacy plaintext support
- return stored;
- }
- try {
- const parts = stored.split(':');
- if (parts.length !== 4) return stored;
- const [, ivHex, authTagHex, ciphertextHex] = parts;
- const key = getEncryptionKey();
- const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
- decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
- let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
- decrypted += decipher.final('utf8');
- return decrypted;
- } catch (err) {
- console.error('Failed to decrypt credential:', err);
- return '';
- }
+interface AssignmentRow {
+ student_id: string;
+ id: string;
+ subject: string;
+ type: string;
+ unit: string;
+ topic: string;
+ start_date: string;
+ end_date: string;
+ parsed_start_date: string | null;
+ parsed_end_date: string | null;
+ description: string;
+ detected_check_date: string | null;
+ status: string;
+ completed: number;
+ completed_at: string | null;
+ excluded: number;
+ page: number | null;
}
export class LocalDatabase {
- private static instance: LocalDatabase;
- private cache: DatabaseSchema = { students: {} };
- private initialized = false;
+ private static instance: LocalDatabase | null = null;
+ private sqlite: Database.Database;
+ private dbPath: string;
+ private legacyJsonPath: string;
+ private skipTestFilter: boolean;
- private constructor() {
- this.ensureDbExists();
- this.load();
+ public constructor(
+ customDbPath?: string,
+ customLegacyJsonPath?: string,
+ options?: { skipTestFilter?: boolean }
+ ) {
+ this.dbPath = customDbPath || process.env.DB_PATH || DEFAULT_DB_FILE;
+ const effectiveCustomDb = customDbPath || process.env.DB_PATH;
+ this.legacyJsonPath =
+ customLegacyJsonPath ||
+ process.env.LEGACY_JSON_DB_PATH ||
+ process.env.LEGACY_JSON_PATH ||
+ (effectiveCustomDb ? path.join(path.dirname(effectiveCustomDb), 'db.json') : DEFAULT_LEGACY_JSON_FILE);
+ this.skipTestFilter = options?.skipTestFilter ?? false;
+
+ const dir = path.dirname(this.dbPath);
+ if (!fs.existsSync(dir)) {
+ fs.mkdirSync(dir, { recursive: true });
+ }
+
+ this.sqlite = new Database(this.dbPath);
+ this.initSchema();
+ this.migrateFromLegacyJson();
}
public static getInstance(): LocalDatabase {
@@ -75,171 +93,640 @@ export class LocalDatabase {
return LocalDatabase.instance;
}
- private ensureDbExists(): void {
- const dir = path.dirname(DB_FILE);
- if (!fs.existsSync(dir)) {
- fs.mkdirSync(dir, { recursive: true });
- }
- if (!fs.existsSync(DB_FILE)) {
- const initial: DatabaseSchema = { students: {} };
- fs.writeFileSync(DB_FILE, JSON.stringify(initial, null, 2), 'utf-8');
+ public static resetInstance(): void {
+ if (LocalDatabase.instance) {
+ LocalDatabase.instance.close();
+ LocalDatabase.instance = null;
}
}
- private load(): void {
+ public getSqliteDb(): Database.Database {
+ return this.sqlite;
+ }
+
+ public getDbPath(): string {
+ return this.dbPath;
+ }
+
+ private initSchema(): void {
+ this.sqlite.pragma('journal_mode = WAL');
+ this.sqlite.pragma('synchronous = FULL');
+ this.sqlite.pragma('foreign_keys = ON');
+ this.sqlite.pragma('busy_timeout = 5000');
+
+ this.sqlite.exec(`
+ CREATE TABLE IF NOT EXISTS meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS students (
+ student_id TEXT PRIMARY KEY,
+ last_synced TEXT,
+ remembered_password TEXT,
+ advisory_teacher TEXT,
+ syllabus_json TEXT,
+ private_lessons_json TEXT,
+ exams_json TEXT,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS assignments (
+ student_id TEXT NOT NULL,
+ id TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ type TEXT NOT NULL,
+ unit TEXT NOT NULL DEFAULT '',
+ topic TEXT NOT NULL DEFAULT '',
+ start_date TEXT NOT NULL DEFAULT '',
+ end_date TEXT NOT NULL DEFAULT '',
+ parsed_start_date TEXT,
+ parsed_end_date TEXT,
+ description TEXT NOT NULL DEFAULT '',
+ detected_check_date TEXT,
+ status TEXT NOT NULL DEFAULT 'active',
+ completed INTEGER NOT NULL DEFAULT 0,
+ completed_at TEXT,
+ excluded INTEGER NOT NULL DEFAULT 0,
+ page INTEGER,
+ PRIMARY KEY (student_id, id),
+ FOREIGN KEY (student_id) REFERENCES students(student_id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_assignments_student ON assignments(student_id);
+
+ CREATE TABLE IF NOT EXISTS sessions (
+ sid TEXT PRIMARY KEY,
+ sess TEXT NOT NULL,
+ expire INTEGER NOT NULL
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire);
+ `);
+ }
+
+ /**
+ * Automatically migrate data from legacy data/db.json into SQLite without losing any student data.
+ * Preserves a backup at data/db.json.bak and leaves data/db.json intact.
+ * Uses a SHA-256 content hash so that if db.json is ever restored or updated later,
+ * any missing records are additively merged without overwriting newer SQLite state.
+ */
+ public migrateFromLegacyJson(): { migratedCount: number; skippedTestCount: number } {
+ const result = { migratedCount: 0, skippedTestCount: 0 };
+
+ if (!fs.existsSync(this.legacyJsonPath)) {
+ return result;
+ }
+
try {
- if (fs.existsSync(DB_FILE)) {
- const raw = fs.readFileSync(DB_FILE, 'utf-8');
- this.cache = JSON.parse(raw) as DatabaseSchema;
- if (!this.cache.students) {
- this.cache.students = {};
- }
+ const raw = fs.readFileSync(this.legacyJsonPath, 'utf-8');
+ const fileHash = crypto.createHash('sha256').update(raw).digest('hex');
+
+ const migratedHashRow = this.sqlite
+ .prepare('SELECT value FROM meta WHERE key = ?')
+ .get('json_migrated_sha256') as { value: string } | undefined;
+
+ if (migratedHashRow && migratedHashRow.value === fileHash) {
+ return result;
}
- this.initialized = true;
+
+ const parsed = JSON.parse(raw) as DatabaseSchema;
+ const studentsMap = parsed?.students || {};
+
+ // Backup original db.json before any changes
+ const backupPath = `${this.legacyJsonPath}.bak`;
+ if (!fs.existsSync(backupPath)) {
+ fs.copyFileSync(this.legacyJsonPath, backupPath);
+ }
+
+ const upsertStudentStmt = this.sqlite.prepare(`
+ INSERT INTO students (
+ student_id,
+ last_synced,
+ remembered_password,
+ advisory_teacher,
+ syllabus_json,
+ private_lessons_json,
+ exams_json,
+ updated_at
+ ) VALUES (
+ @student_id,
+ @last_synced,
+ @remembered_password,
+ @advisory_teacher,
+ @syllabus_json,
+ @private_lessons_json,
+ @exams_json,
+ @updated_at
+ )
+ ON CONFLICT(student_id) DO UPDATE SET
+ last_synced = COALESCE(students.last_synced, excluded.last_synced),
+ remembered_password = COALESCE(students.remembered_password, excluded.remembered_password),
+ advisory_teacher = COALESCE(students.advisory_teacher, excluded.advisory_teacher),
+ syllabus_json = COALESCE(students.syllabus_json, excluded.syllabus_json),
+ private_lessons_json = COALESCE(students.private_lessons_json, excluded.private_lessons_json),
+ exams_json = COALESCE(students.exams_json, excluded.exams_json),
+ updated_at = excluded.updated_at
+ `);
+
+ const upsertAssignmentStmt = this.sqlite.prepare(`
+ INSERT INTO assignments (
+ student_id,
+ id,
+ subject,
+ type,
+ unit,
+ topic,
+ start_date,
+ end_date,
+ parsed_start_date,
+ parsed_end_date,
+ description,
+ detected_check_date,
+ status,
+ completed,
+ completed_at,
+ excluded,
+ page
+ ) VALUES (
+ @student_id,
+ @id,
+ @subject,
+ @type,
+ @unit,
+ @topic,
+ @start_date,
+ @end_date,
+ @parsed_start_date,
+ @parsed_end_date,
+ @description,
+ @detected_check_date,
+ @status,
+ @completed,
+ @completed_at,
+ @excluded,
+ @page
+ )
+ ON CONFLICT(student_id, id) DO UPDATE SET
+ subject = COALESCE(NULLIF(assignments.subject, ''), excluded.subject),
+ type = COALESCE(NULLIF(assignments.type, ''), excluded.type),
+ unit = COALESCE(NULLIF(assignments.unit, ''), excluded.unit),
+ topic = COALESCE(NULLIF(assignments.topic, ''), excluded.topic),
+ start_date = COALESCE(NULLIF(assignments.start_date, ''), excluded.start_date),
+ end_date = COALESCE(NULLIF(assignments.end_date, ''), excluded.end_date),
+ parsed_start_date = COALESCE(assignments.parsed_start_date, excluded.parsed_start_date),
+ parsed_end_date = COALESCE(assignments.parsed_end_date, excluded.parsed_end_date),
+ description = COALESCE(NULLIF(assignments.description, ''), excluded.description),
+ detected_check_date = COALESCE(assignments.detected_check_date, excluded.detected_check_date),
+ status = CASE WHEN assignments.completed = 1 OR excluded.completed = 1 THEN 'completed' ELSE assignments.status END,
+ completed = CASE WHEN assignments.completed = 1 OR excluded.completed = 1 THEN 1 ELSE 0 END,
+ completed_at = COALESCE(assignments.completed_at, excluded.completed_at),
+ excluded = CASE WHEN assignments.excluded = 1 OR excluded.excluded = 1 THEN 1 ELSE 0 END,
+ page = COALESCE(assignments.page, excluded.page)
+ `);
+
+ const setMetaStmt = this.sqlite.prepare(`
+ INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)
+ `);
+
+ const nowIso = new Date().toISOString();
+
+ const runMigration = this.sqlite.transaction(() => {
+ for (const [studentId, store] of Object.entries(studentsMap)) {
+ if (!studentId || !store) continue;
+
+ if (!this.skipTestFilter && SYNTHETIC_TEST_ID_REGEX.test(studentId)) {
+ result.skippedTestCount++;
+ continue;
+ }
+
+ let encryptedPassword: string | null = null;
+ if (store.rememberedCredentials?.password) {
+ const plain = decryptCredential(store.rememberedCredentials.password);
+ if (plain) {
+ encryptedPassword = encryptCredential(plain);
+ }
+ }
+
+ upsertStudentStmt.run({
+ student_id: studentId,
+ last_synced: store.lastSynced || null,
+ remembered_password: encryptedPassword,
+ advisory_teacher: store.advisoryTeacher || store.privateLessons?.detectedAdvisor || null,
+ syllabus_json: store.syllabus ? JSON.stringify(store.syllabus) : null,
+ private_lessons_json: store.privateLessons ? JSON.stringify(store.privateLessons) : null,
+ exams_json: store.exams ? JSON.stringify(store.exams) : null,
+ updated_at: nowIso
+ });
+
+ const assignments = store.assignments ? Object.values(store.assignments) : [];
+ for (const a of assignments) {
+ if (!a || !a.id) continue;
+ upsertAssignmentStmt.run({
+ student_id: studentId,
+ id: a.id,
+ subject: a.subject || 'Genel',
+ type: a.type || 'Ödev',
+ unit: a.unit || '',
+ topic: a.topic || '',
+ start_date: a.startDate || '',
+ end_date: a.endDate || '',
+ parsed_start_date: a.parsedStartDate || null,
+ parsed_end_date: a.parsedEndDate || null,
+ description: a.description || '',
+ detected_check_date: a.detectedCheckDate || null,
+ status: a.status || 'active',
+ completed: a.completed ? 1 : 0,
+ completed_at: a.completedAt || null,
+ excluded: a.excluded ? 1 : 0,
+ page: a.page ?? null
+ });
+ }
+
+ result.migratedCount++;
+ }
+
+ setMetaStmt.run('json_migrated_at', nowIso);
+ setMetaStmt.run('json_migrated_sha256', fileHash);
+ setMetaStmt.run('schema_version', '2');
+ });
+
+ runMigration();
} catch (err) {
- console.error('Error loading database file, initializing empty:', err);
- this.cache = { students: {} };
+ console.error('Error migrating legacy db.json to SQLite:', err);
}
+
+ return result;
}
- private save(): void {
- try {
- const tmpFile = `${DB_FILE}.${process.pid}.${Date.now()}.tmp`;
- fs.writeFileSync(tmpFile, JSON.stringify(this.cache, null, 2), 'utf-8');
- fs.renameSync(tmpFile, DB_FILE);
- } catch (err) {
- console.error('Error saving database:', err);
+ private ensureStudentRow(studentId: string): StudentRow {
+ const existing = this.sqlite
+ .prepare('SELECT * FROM students WHERE student_id = ?')
+ .get(studentId) as StudentRow | undefined;
+
+ if (existing) {
+ return existing;
}
+
+ const now = new Date().toISOString();
+ this.sqlite
+ .prepare(`
+ INSERT INTO students (
+ student_id,
+ last_synced,
+ remembered_password,
+ advisory_teacher,
+ syllabus_json,
+ private_lessons_json,
+ exams_json,
+ updated_at
+ ) VALUES (?, NULL, NULL, NULL, NULL, NULL, NULL, ?)
+ `)
+ .run(studentId, now);
+
+ return {
+ student_id: studentId,
+ last_synced: null,
+ remembered_password: null,
+ advisory_teacher: null,
+ syllabus_json: null,
+ private_lessons_json: null,
+ exams_json: null
+ };
+ }
+
+ private mapAssignmentRow(row: AssignmentRow): Assignment {
+ return {
+ id: row.id,
+ subject: row.subject,
+ type: row.type,
+ unit: row.unit,
+ topic: row.topic,
+ startDate: row.start_date,
+ endDate: row.end_date,
+ parsedStartDate: row.parsed_start_date,
+ parsedEndDate: row.parsed_end_date,
+ description: row.description,
+ detectedCheckDate: row.detected_check_date,
+ status: row.status as Assignment['status'],
+ completed: row.completed === 1,
+ completedAt: row.completed_at,
+ excluded: row.excluded === 1,
+ page: row.page ?? undefined
+ };
}
public getStudentStore(studentId: string): StudentStore {
- if (!this.cache.students[studentId]) {
- this.cache.students[studentId] = {
- studentId,
- lastSynced: null,
- assignments: {}
- };
- this.save();
+ const row = this.ensureStudentRow(studentId);
+ const assignmentRows = this.sqlite
+ .prepare('SELECT * FROM assignments WHERE student_id = ?')
+ .all(studentId) as AssignmentRow[];
+
+ const assignments: Record = {};
+ for (const r of assignmentRows) {
+ assignments[r.id] = this.mapAssignmentRow(r);
}
- return this.cache.students[studentId];
- }
- public mergeAssignments(studentId: string, newAssignments: Assignment[]): StudentStore {
- const student = this.getStudentStore(studentId);
- student.lastSynced = new Date().toISOString();
+ const store: StudentStore = {
+ studentId: row.student_id,
+ lastSynced: row.last_synced,
+ assignments
+ };
- for (const item of newAssignments) {
- const existing = student.assignments[item.id];
- if (existing) {
- // Preserve user completion status, timestamp, and disincluded flag
- student.assignments[item.id] = {
- ...item,
- completed: existing.completed,
- completedAt: existing.completedAt,
- excluded: existing.excluded || false
- };
- } else {
- student.assignments[item.id] = {
- ...item,
- excluded: false
- };
+ if (row.remembered_password) {
+ store.rememberedCredentials = {
+ studentId: row.student_id,
+ password: row.remembered_password
+ };
+ }
+
+ if (row.advisory_teacher) {
+ store.advisoryTeacher = row.advisory_teacher;
+ }
+
+ if (row.syllabus_json) {
+ try {
+ store.syllabus = JSON.parse(row.syllabus_json) as SyllabusStore;
+ } catch {
+ // Ignore malformed JSON
}
}
- this.save();
- return student;
+ if (row.private_lessons_json) {
+ try {
+ store.privateLessons = JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
+ } catch {
+ // Ignore malformed JSON
+ }
+ }
+
+ if (row.exams_json) {
+ try {
+ store.exams = JSON.parse(row.exams_json) as ExamStore;
+ } catch {
+ // Ignore malformed JSON
+ }
+ }
+
+ return store;
}
- public toggleExcludeAssignment(studentId: string, assignmentId: string, excluded?: boolean): Assignment | null {
- const student = this.getStudentStore(studentId);
- const assignment = student.assignments[assignmentId];
- if (!assignment) {
+ public mergeAssignments(studentId: string, newAssignments: Assignment[]): StudentStore {
+ this.ensureStudentRow(studentId);
+ const now = new Date().toISOString();
+
+ const updateStudentSync = this.sqlite.prepare(
+ 'UPDATE students SET last_synced = ?, updated_at = ? WHERE student_id = ?'
+ );
+
+ const getExistingStmt = this.sqlite.prepare(
+ 'SELECT completed, completed_at, excluded FROM assignments WHERE student_id = ? AND id = ?'
+ );
+
+ const upsertStmt = this.sqlite.prepare(`
+ INSERT INTO assignments (
+ student_id,
+ id,
+ subject,
+ type,
+ unit,
+ topic,
+ start_date,
+ end_date,
+ parsed_start_date,
+ parsed_end_date,
+ description,
+ detected_check_date,
+ status,
+ completed,
+ completed_at,
+ excluded,
+ page
+ ) VALUES (
+ @student_id,
+ @id,
+ @subject,
+ @type,
+ @unit,
+ @topic,
+ @start_date,
+ @end_date,
+ @parsed_start_date,
+ @parsed_end_date,
+ @description,
+ @detected_check_date,
+ @status,
+ @completed,
+ @completed_at,
+ @excluded,
+ @page
+ )
+ ON CONFLICT(student_id, id) DO UPDATE SET
+ subject = excluded.subject,
+ type = excluded.type,
+ unit = excluded.unit,
+ topic = excluded.topic,
+ start_date = excluded.start_date,
+ end_date = excluded.end_date,
+ parsed_start_date = excluded.parsed_start_date,
+ parsed_end_date = excluded.parsed_end_date,
+ description = excluded.description,
+ detected_check_date = excluded.detected_check_date,
+ status = excluded.status,
+ completed = excluded.completed,
+ completed_at = excluded.completed_at,
+ excluded = excluded.excluded,
+ page = excluded.page
+ `);
+
+ const tx = this.sqlite.transaction(() => {
+ updateStudentSync.run(now, now, studentId);
+
+ for (const item of newAssignments) {
+ const existing = getExistingStmt.get(studentId, item.id) as
+ | { completed: number; completed_at: string | null; excluded: number }
+ | undefined;
+
+ const isCompleted = existing ? existing.completed === 1 : Boolean(item.completed);
+ const completedAt = existing ? existing.completed_at : (item.completedAt || null);
+ const isExcluded = existing ? existing.excluded === 1 : Boolean(item.excluded);
+ const status = isCompleted ? 'completed' : item.status;
+
+ upsertStmt.run({
+ student_id: studentId,
+ id: item.id,
+ subject: item.subject,
+ type: item.type,
+ unit: item.unit || '',
+ topic: item.topic || '',
+ start_date: item.startDate || '',
+ end_date: item.endDate || '',
+ parsed_start_date: item.parsedStartDate || null,
+ parsed_end_date: item.parsedEndDate || null,
+ description: item.description || '',
+ detected_check_date: item.detectedCheckDate || null,
+ status,
+ completed: isCompleted ? 1 : 0,
+ completed_at: completedAt,
+ excluded: isExcluded ? 1 : 0,
+ page: item.page ?? null
+ });
+ }
+ });
+
+ tx();
+ return this.getStudentStore(studentId);
+ }
+
+ public toggleExcludeAssignment(
+ studentId: string,
+ assignmentId: string,
+ excluded?: boolean
+ ): Assignment | null {
+ this.ensureStudentRow(studentId);
+ const existing = this.sqlite
+ .prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
+ .get(studentId, assignmentId) as AssignmentRow | undefined;
+
+ if (!existing) {
return null;
}
- const newExcluded = excluded !== undefined ? excluded : !assignment.excluded;
- assignment.excluded = newExcluded;
+ const newExcluded = excluded !== undefined ? excluded : existing.excluded !== 1;
+ this.sqlite
+ .prepare('UPDATE assignments SET excluded = ? WHERE student_id = ? AND id = ?')
+ .run(newExcluded ? 1 : 0, studentId, assignmentId);
- this.save();
- return assignment;
+ const updated = this.sqlite
+ .prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
+ .get(studentId, assignmentId) as AssignmentRow;
+
+ return this.mapAssignmentRow(updated);
}
- public toggleAssignment(studentId: string, assignmentId: string, completed?: boolean): Assignment | null {
- const student = this.getStudentStore(studentId);
- const assignment = student.assignments[assignmentId];
- if (!assignment) {
+ public toggleAssignment(
+ studentId: string,
+ assignmentId: string,
+ completed?: boolean
+ ): Assignment | null {
+ this.ensureStudentRow(studentId);
+ const existing = this.sqlite
+ .prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
+ .get(studentId, assignmentId) as AssignmentRow | undefined;
+
+ if (!existing) {
return null;
}
- const newCompleted = completed !== undefined ? completed : !assignment.completed;
- assignment.completed = newCompleted;
- assignment.completedAt = newCompleted ? new Date().toISOString() : null;
- assignment.status = newCompleted ? 'completed' : assignment.status;
+ const newCompleted = completed !== undefined ? completed : existing.completed !== 1;
+ const completedAt = newCompleted ? new Date().toISOString() : null;
+ const newStatus = newCompleted ? 'completed' : existing.status;
- this.save();
- return assignment;
+ this.sqlite
+ .prepare(
+ 'UPDATE assignments SET completed = ?, completed_at = ?, status = ? WHERE student_id = ? AND id = ?'
+ )
+ .run(newCompleted ? 1 : 0, completedAt, newStatus, studentId, assignmentId);
+
+ const updated = this.sqlite
+ .prepare('SELECT * FROM assignments WHERE student_id = ? AND id = ?')
+ .get(studentId, assignmentId) as AssignmentRow;
+
+ return this.mapAssignmentRow(updated);
}
public saveCredentials(studentId: string, password: string): void {
- const student = this.getStudentStore(studentId);
+ this.ensureStudentRow(studentId);
const encryptedPassword = encryptCredential(password);
- student.rememberedCredentials = { studentId, password: encryptedPassword };
- this.save();
+ this.sqlite
+ .prepare('UPDATE students SET remembered_password = ?, updated_at = ? WHERE student_id = ?')
+ .run(encryptedPassword, new Date().toISOString(), studentId);
}
public clearCredentials(studentId: string): void {
- const student = this.getStudentStore(studentId);
- delete student.rememberedCredentials;
- this.save();
+ this.ensureStudentRow(studentId);
+ this.sqlite
+ .prepare('UPDATE students SET remembered_password = NULL, updated_at = ? WHERE student_id = ?')
+ .run(new Date().toISOString(), studentId);
}
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
- const student = this.cache.students[studentId];
- if (!student?.rememberedCredentials) return null;
+ const row = this.sqlite
+ .prepare('SELECT remembered_password FROM students WHERE student_id = ?')
+ .get(studentId) as { remembered_password: string | null } | undefined;
+
+ if (!row?.remembered_password) return null;
+ const decrypted = decryptCredential(row.remembered_password);
+ if (!decrypted) return null;
return {
- studentId: student.rememberedCredentials.studentId,
- password: decryptCredential(student.rememberedCredentials.password)
+ studentId,
+ password: decrypted
};
}
+ public getRawEncryptedPassword(studentId: string): string | null {
+ const row = this.sqlite
+ .prepare('SELECT remembered_password FROM students WHERE student_id = ?')
+ .get(studentId) as { remembered_password: string | null } | undefined;
+ return row?.remembered_password || null;
+ }
+
public saveSyllabus(
studentId: string,
weekId: string,
weekRange: string,
schedule: Record
): void {
- const student = this.getStudentStore(studentId);
- const existingStation = student.syllabus?.selectedStation || null;
+ const row = this.ensureStudentRow(studentId);
+ const existingSyllabus = row.syllabus_json ? (JSON.parse(row.syllabus_json) as SyllabusStore) : null;
+ const existingStation = existingSyllabus?.selectedStation || null;
- student.syllabus = {
+ const syllabus: SyllabusStore = {
weekId,
weekRange,
selectedStation: existingStation,
+ advisoryTeacher: row.advisory_teacher || existingSyllabus?.advisoryTeacher || null,
lastSynced: new Date().toISOString(),
schedule
};
- this.save();
+
+ this.sqlite
+ .prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?')
+ .run(JSON.stringify(syllabus), new Date().toISOString(), studentId);
}
public setStudentStation(studentId: string, station: string | null): void {
- const student = this.getStudentStore(studentId);
- if (!student.syllabus) {
- student.syllabus = {
+ const row = this.ensureStudentRow(studentId);
+ let syllabus: SyllabusStore;
+ if (row.syllabus_json) {
+ syllabus = JSON.parse(row.syllabus_json) as SyllabusStore;
+ syllabus.selectedStation = station;
+ } else {
+ syllabus = {
weekId: '',
weekRange: '',
selectedStation: station,
lastSynced: null,
schedule: {}
};
- } else {
- student.syllabus.selectedStation = station;
}
- this.save();
+
+ this.sqlite
+ .prepare('UPDATE students SET syllabus_json = ?, updated_at = ? WHERE student_id = ?')
+ .run(JSON.stringify(syllabus), new Date().toISOString(), studentId);
}
- public getSyllabus(studentId: string): any {
- const student = this.cache.students[studentId];
- return student?.syllabus || null;
+ public getSyllabus(studentId: string): SyllabusStore | null {
+ const row = this.sqlite
+ .prepare('SELECT syllabus_json FROM students WHERE student_id = ?')
+ .get(studentId) as { syllabus_json: string | null } | undefined;
+
+ if (!row?.syllabus_json) return null;
+ try {
+ return JSON.parse(row.syllabus_json) as SyllabusStore;
+ } catch {
+ return null;
+ }
}
public savePrivateLessons(
@@ -248,43 +735,94 @@ export class LocalDatabase {
formMeta?: PrivateLessonFormMeta,
detectedAdvisor?: string
): void {
- const student = this.getStudentStore(studentId);
- const existing = student.privateLessons;
+ const row = this.ensureStudentRow(studentId);
+ const existing = row.private_lessons_json
+ ? (JSON.parse(row.private_lessons_json) as PrivateLessonsStore)
+ : null;
- student.privateLessons = {
+ const privateLessons: PrivateLessonsStore = {
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;
+ let newAdvisor = row.advisory_teacher;
+ let updatedSyllabusJson = row.syllabus_json;
+
+ if (detectedAdvisor && !newAdvisor) {
+ newAdvisor = detectedAdvisor;
+ if (updatedSyllabusJson) {
+ try {
+ const syl = JSON.parse(updatedSyllabusJson) as SyllabusStore;
+ syl.advisoryTeacher = detectedAdvisor;
+ updatedSyllabusJson = JSON.stringify(syl);
+ } catch {
+ // ignore
+ }
}
}
- this.save();
+ this.sqlite
+ .prepare(
+ 'UPDATE students SET private_lessons_json = ?, advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?'
+ )
+ .run(
+ JSON.stringify(privateLessons),
+ newAdvisor,
+ updatedSyllabusJson,
+ new Date().toISOString(),
+ studentId
+ );
}
public getPrivateLessons(studentId: string): PrivateLessonsStore | null {
- const student = this.cache.students[studentId];
- return student?.privateLessons || null;
+ const row = this.sqlite
+ .prepare('SELECT private_lessons_json FROM students WHERE student_id = ?')
+ .get(studentId) as { private_lessons_json: string | null } | undefined;
+
+ if (!row?.private_lessons_json) return null;
+ try {
+ return JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
+ } catch {
+ return null;
+ }
}
public setStudentAdvisoryTeacher(studentId: string, teacher: string | null): void {
- const student = this.getStudentStore(studentId);
- student.advisoryTeacher = teacher;
- if (student.syllabus) {
- student.syllabus.advisoryTeacher = teacher;
+ const row = this.ensureStudentRow(studentId);
+ let updatedSyllabusJson = row.syllabus_json;
+ if (updatedSyllabusJson) {
+ try {
+ const syl = JSON.parse(updatedSyllabusJson) as SyllabusStore;
+ syl.advisoryTeacher = teacher;
+ updatedSyllabusJson = JSON.stringify(syl);
+ } catch {
+ // ignore
+ }
}
- this.save();
+
+ this.sqlite
+ .prepare('UPDATE students SET advisory_teacher = ?, syllabus_json = ?, updated_at = ? WHERE student_id = ?')
+ .run(teacher, updatedSyllabusJson, new Date().toISOString(), studentId);
}
public getStudentAdvisoryTeacher(studentId: string): string | null {
- const student = this.cache.students[studentId];
- return student?.advisoryTeacher || student?.privateLessons?.detectedAdvisor || null;
+ const row = this.sqlite
+ .prepare('SELECT advisory_teacher, private_lessons_json FROM students WHERE student_id = ?')
+ .get(studentId) as { advisory_teacher: string | null; private_lessons_json: string | null } | undefined;
+
+ if (!row) return null;
+ if (row.advisory_teacher) return row.advisory_teacher;
+ if (row.private_lessons_json) {
+ try {
+ const pl = JSON.parse(row.private_lessons_json) as PrivateLessonsStore;
+ return pl.detectedAdvisor || null;
+ } catch {
+ return null;
+ }
+ }
+ return null;
}
// ----------------------------------------------------
@@ -292,68 +830,103 @@ export class LocalDatabase {
// ----------------------------------------------------
public saveExamReports(studentId: string, reports: ExamReportDetail[]): void {
- const student = this.getStudentStore(studentId);
- const existing = student.exams;
+ const row = this.ensureStudentRow(studentId);
+ const existing = row.exams_json ? (JSON.parse(row.exams_json) as ExamStore) : null;
const reportsMap: Record = existing?.reports ? { ...existing.reports } : {};
reports.forEach(r => {
reportsMap[r.summary.id] = r;
});
- student.exams = {
+ const exams: ExamStore = {
lastSynced: new Date().toISOString(),
reports: reportsMap,
- topicWeaknesses: existing?.topicWeaknesses || {}
+ topicWeaknesses: existing?.topicWeaknesses || {},
+ questions: existing?.questions || {}
};
- this.save();
+ this.sqlite
+ .prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
+ .run(JSON.stringify(exams), new Date().toISOString(), studentId);
}
public getExamReports(studentId: string): ExamStore | null {
- const student = this.cache.students[studentId];
- return student?.exams || null;
+ const row = this.sqlite
+ .prepare('SELECT exams_json FROM students WHERE student_id = ?')
+ .get(studentId) as { exams_json: string | null } | undefined;
+
+ if (!row?.exams_json) return null;
+ try {
+ return JSON.parse(row.exams_json) as ExamStore;
+ } catch {
+ return 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: {}
- };
+ const row = this.ensureStudentRow(studentId);
+ const exams: ExamStore = row.exams_json
+ ? (JSON.parse(row.exams_json) as ExamStore)
+ : {
+ lastSynced: new Date().toISOString(),
+ reports: {},
+ topicWeaknesses: {},
+ questions: {}
+ };
+
+ if (!exams.topicWeaknesses) {
+ exams.topicWeaknesses = {};
}
- if (!student.exams.topicWeaknesses) {
- student.exams.topicWeaknesses = {};
- }
- student.exams.topicWeaknesses[examId] = weaknesses;
- this.save();
+ exams.topicWeaknesses[examId] = weaknesses;
+
+ this.sqlite
+ .prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
+ .run(JSON.stringify(exams), new Date().toISOString(), studentId);
}
public getTopicWeaknesses(studentId: string, examId: string): ExamTopicWeakness[] | null {
- const student = this.cache.students[studentId];
- return student?.exams?.topicWeaknesses?.[examId] || null;
+ const exams = this.getExamReports(studentId);
+ return exams?.topicWeaknesses?.[examId] || null;
}
public saveExamQuestions(studentId: string, examId: string, questions: ExamQuestionItem[]): void {
- const student = this.getStudentStore(studentId);
- if (!student.exams) {
- student.exams = {
- lastSynced: new Date().toISOString(),
- reports: {},
- topicWeaknesses: {},
- questions: {}
- };
+ const row = this.ensureStudentRow(studentId);
+ const exams: ExamStore = row.exams_json
+ ? (JSON.parse(row.exams_json) as ExamStore)
+ : {
+ lastSynced: new Date().toISOString(),
+ reports: {},
+ topicWeaknesses: {},
+ questions: {}
+ };
+
+ if (!exams.questions) {
+ exams.questions = {};
}
- if (!student.exams.questions) {
- student.exams.questions = {};
- }
- student.exams.questions[examId] = questions;
- this.save();
+ exams.questions[examId] = questions;
+
+ this.sqlite
+ .prepare('UPDATE students SET exams_json = ?, updated_at = ? WHERE student_id = ?')
+ .run(JSON.stringify(exams), new Date().toISOString(), studentId);
}
public getExamQuestions(studentId: string, examId: string): ExamQuestionItem[] | null {
- const student = this.cache.students[studentId];
- return student?.exams?.questions?.[examId] || null;
+ const exams = this.getExamReports(studentId);
+ return exams?.questions?.[examId] || null;
+ }
+
+ public close(): void {
+ try {
+ if (this.sqlite && this.sqlite.open) {
+ try {
+ this.sqlite.pragma('wal_checkpoint(TRUNCATE)');
+ } catch {
+ // Ignore checkpoint errors
+ }
+ this.sqlite.close();
+ }
+ } catch {
+ // Ignore close errors
+ }
}
}
diff --git a/src/services/i18n.ts b/src/services/i18n.ts
new file mode 100644
index 0000000..46cbda0
--- /dev/null
+++ b/src/services/i18n.ts
@@ -0,0 +1,519 @@
+export type SupportedLocale = 'tr' | 'en';
+
+export const DEFAULT_LOCALE: SupportedLocale = 'tr';
+
+export const DAY_NAMES_BY_LOCALE: Record> = {
+ tr: {
+ 1: 'Pazartesi',
+ 2: 'Salı',
+ 3: 'Çarşamba',
+ 4: 'Perşembe',
+ 5: 'Cuma'
+ },
+ en: {
+ 1: 'Pazartesi',
+ 2: 'Salı',
+ 3: 'Çarşamba',
+ 4: 'Perşembe',
+ 5: 'Cuma'
+ }
+};
+
+const translations: Record> = {
+ tr: {
+ // Brand & Common
+ 'app.title': 'BeKultur (E-Kültür)',
+ 'nav.homework': 'Ödevler',
+ 'nav.syllabus': 'Ders Programı',
+ 'nav.privateLessons': 'Özel Ders',
+ 'nav.exams': 'Sınav Raporları',
+ 'header.student': 'Öğrenci',
+ 'header.logout': 'Çıkış Yap',
+ 'header.themeToggle': 'Tema Değiştir',
+ 'header.themeLight': 'Açık Tema',
+ 'header.themeDark': 'Koyu Tema',
+ 'header.langToggleTitle': 'Dili Değiştir / Switch Language',
+
+ // Login (/Kullanici/Giris parity)
+ 'login.pageTitle': 'Giriş Yap - BeKultur (E-Kültür)',
+ 'login.subtitle': 'E-Kültür öğrenci portalı bilgilerinizle giriş yapınız.',
+ 'login.studentIdLabel': 'Öğrenci ID',
+ 'login.studentIdPlaceholder': 'Öğrenci ID',
+ 'login.passwordLabel': 'Parola',
+ 'login.passwordPlaceholder': 'Parola',
+ 'login.rememberMe': 'Beni hatırla',
+ 'login.submit': 'Giriş Yap',
+ 'login.submitting': 'Giriş yapılıyor...',
+ 'login.errorMissing': 'Lütfen Öğrenci ID ve Parola alanlarını doldurunuz.',
+ 'login.errorInvalid': 'Öğrenci ID veya Parola hatalı.',
+ 'login.errorServer': 'Giriş sırasında beklenmeyen bir sunucu hatası oluştu.',
+
+ // Homework / Dashboard (/Odev parity)
+ 'dashboard.pageTitle': 'Ödevler - BeKultur',
+ 'dashboard.title': 'Ödevler',
+ 'dashboard.studentLabel': 'Öğrenci',
+ 'dashboard.lastSynced': 'Son güncelleme:',
+ 'dashboard.notSynced': 'Henüz güncellenmedi',
+ 'dashboard.syncRecent': 'Güncel Ödevleri Çek',
+ 'dashboard.syncAll': 'Tüm Geçmişi Çek',
+ 'dashboard.syncing': 'Güncelleniyor...',
+ 'dashboard.syncingAll': 'Tüm geçmiş çekiliyor...',
+ 'dashboard.fetchingRecent': 'Güncel ödevler E-Kültür portalından çekiliyor...',
+ 'dashboard.fetchingAll': 'Tüm ödev geçmişi E-Kültür portalından çekiliyor...',
+ 'dashboard.syncFailed': 'Senkronizasyon başarısız:',
+ 'dashboard.networkError': 'Senkronizasyon sırasında ağ hatası oluştu.',
+ 'dashboard.statCompletion': 'Tamamlanma',
+ 'dashboard.statDoneUnit': 'tamamlandı',
+ 'dashboard.statActive': 'Aktif',
+ 'dashboard.statActiveSub': 'Devam eden ödevler',
+ 'dashboard.statNextWeek': 'Gelecek Hafta Kontrol',
+ 'dashboard.statNextWeekSub': 'Haftaya teslim / kontrol',
+ 'dashboard.statDueSoon': 'Yaklaşan',
+ 'dashboard.statDueSoonSub': '3 gün içinde biten',
+ 'dashboard.statOverdue': 'Süresi Geçen',
+ 'dashboard.statOverdueSub': 'Bitiş tarihi geçmiş',
+ 'dashboard.statTotal': 'Toplam',
+ 'dashboard.statTotalSub': 'Tüm ödevler',
+ 'dashboard.subjectsTitle': 'Dersler',
+ 'dashboard.tabAll': 'Tümü',
+ 'dashboard.tabNextWeek': 'Gelecek Hafta Kontrol',
+ 'dashboard.tabActive': 'Aktif',
+ 'dashboard.tabDueSoon': 'Yaklaşan',
+ 'dashboard.tabCompleted': 'Tamamlanan',
+ 'dashboard.tabOverdue': 'Süresi Geçen',
+ 'dashboard.tabExcluded': 'Hariç Tutulan',
+ 'dashboard.searchPlaceholder': 'Ders, yayın, ünite, konu veya açıklamaya göre ara...',
+ 'dashboard.allSubjectsOption': 'Tüm Dersler',
+ 'dashboard.showingCount': '{count} ödev gösteriliyor',
+ 'dashboard.noResults': 'Filtrelere uygun ödev bulunamadı.',
+ 'dashboard.resetFilters': 'Filtreleri Sıfırla',
+ 'dashboard.checkDateBadge': 'Kontrol:',
+ 'dashboard.badgeExcluded': 'Hariç Tutuldu',
+ 'dashboard.badgeCompleted': 'Tamamlandı',
+ 'dashboard.badgeNextWeek': 'Gelecek Hafta',
+ 'dashboard.badgeDueSoon': 'Yaklaşan',
+ 'dashboard.badgeOverdue': 'Süresi Geçti',
+ 'dashboard.badgeActive': 'Aktif',
+ 'dashboard.btnExclude': 'Hariç Tut',
+ 'dashboard.btnRestore': 'Geri Al',
+ 'dashboard.btnExcludeTitle': 'Bu ödevi listenden hariç tut (örn. başka sınıfa ait ödev)',
+ 'dashboard.btnRestoreTitle': 'Bu ödevi aktif listene geri ekle',
+ 'dashboard.unitLabel': 'Ünite:',
+ 'dashboard.topicLabel': 'Konu:',
+ 'dashboard.dateRangeLabel': 'Başlangıç - Bitiş Tarihi:',
+ 'dashboard.descriptionLabel': 'Açıklama:',
+ 'dashboard.completedOn': 'Tamamlandı:',
+ 'dashboard.offlineToggleAlert': 'Çevrimdışı moddasınız. Ödev durumu internet bağlantısı olmadan değiştirilemez.',
+ 'dashboard.offlineExcludeAlert': 'Çevrimdışı moddasınız. Ödev hariç tutma/geri alma işlemi için internet bağlantısı gereklidir.',
+ 'dashboard.offlineSyncAlert': 'Çevrimdışı moddasınız. Senkronizasyon için internet bağlantısı gereklidir.',
+
+ // Syllabus (/dersprogrami parity)
+ 'syllabus.pageTitle': 'Ders Programı - BeKultur',
+ 'syllabus.title': 'Ders Programı',
+ 'syllabus.weekLabel': 'Hafta:',
+ 'syllabus.syncedLabel': 'Son güncelleme:',
+ 'syllabus.notSynced': 'Henüz güncellenmedi',
+ 'syllabus.syncBtn': 'Ders Programını Güncelle',
+ 'syllabus.syncing': 'Güncelleniyor...',
+ 'syllabus.fetchingAlert': '5 günlük ders programı E-Kültür portalından çekiliyor...',
+ 'syllabus.updatedAlert': 'Ders programı başarıyla güncellendi!',
+ 'syllabus.stationLabel': 'İstasyon:',
+ 'syllabus.allStations': 'Tüm İstasyonlar',
+ 'syllabus.advisorLabel': 'Danışman:',
+ 'syllabus.advisoryTag': 'Danışmanlık',
+ 'syllabus.viewLabel': 'Görünüm:',
+ 'syllabus.dayView': 'Günlük Görünüm',
+ 'syllabus.weekView': 'Haftalık Tablo',
+ 'syllabus.todayBadge': 'Bugün',
+ 'syllabus.noLessonsDay': '{day} günü için ders kaydı bulunamadı. Portaldan çekmek için "Ders Programını Güncelle" butonuna tıklayınız.',
+ 'syllabus.classBadge': 'Sınıf',
+ 'syllabus.periodHeader': 'Ders Saati',
+ 'syllabus.periodNumberLabel': '{period}. Ders',
+ 'syllabus.nowInSession': 'Şu anki ders: {period} — {subject} ({time})',
+ 'syllabus.nextUp': 'Sıradaki ders: {period} — {subject} ({time})',
+ 'syllabus.offlineStationAlert': 'Çevrimdışı moddasınız. İstasyon seçimi için internet bağlantısı gereklidir.',
+
+ // Private Lessons (/ozelders & /ozeldersistek parity)
+ 'privateLessons.pageTitle': 'Özel Ders - BeKultur',
+ 'privateLessons.title': 'Özel Ders',
+ 'privateLessons.subtitle': 'Özel Ders & Başvuru',
+ 'privateLessons.syncedLabel': 'Son güncelleme:',
+ 'privateLessons.syncBtn': 'Dersleri Güncelle',
+ 'privateLessons.syncing': 'Güncelleniyor...',
+ 'privateLessons.syncSuccess': '{count} özel ders kaydı başarıyla güncellendi.',
+ 'privateLessons.advisorLabel': 'Danışman:',
+ 'privateLessons.policyNote': 'Başkası adına özel ders almayınız, seçtiğiniz öğretmen onayladığı takdirde özel derse alınacaksınız.',
+ 'privateLessons.requestTitle': 'Özel Ders İstek',
+ 'privateLessons.onlineBadge': 'Online Başvuru',
+ 'privateLessons.courseLabel': 'Ders',
+ 'privateLessons.unitLabel': 'Ünite',
+ 'privateLessons.topicLabel': 'Konu',
+ 'privateLessons.loading': 'Yükleniyor...',
+ 'privateLessons.selectPrompt': 'Seçiniz...',
+ 'privateLessons.selectCourseFirst': 'Önce ders seçiniz...',
+ 'privateLessons.selectUnitFirst': 'Önce ünite seçiniz...',
+ 'privateLessons.noUnitFound': 'Ünite bulunamadı',
+ 'privateLessons.noTopicFound': 'Konu bulunamadı',
+ 'privateLessons.errorOccurred': 'Hata oluştu',
+ 'privateLessons.submitBtn': 'Gönder',
+ 'privateLessons.submittingBtn': 'Gönderiliyor...',
+ 'privateLessons.myLessonsTitle': 'Özel Derslerim',
+ 'privateLessons.filterAll': 'Tümü',
+ 'privateLessons.upcomingGroupTitle': 'Yaklaşan / Onaylanan Özel Dersler',
+ 'privateLessons.upcomingBadge': 'Yaklaşan',
+ 'privateLessons.activeCountBadge': '{count} Aktif',
+ 'privateLessons.pastGroupTitle': 'Özel Ders Geçmişi',
+ 'privateLessons.pastCountBadge': '{count} Geçmiş',
+ 'privateLessons.completedBadge': 'Tamamlandı',
+ 'privateLessons.emptyState': 'Henüz kayıtlı özel dersiniz bulunmuyor. Yukarıdaki formdan başvuru yapabilir veya portaldan çekmek için "Dersleri Güncelle" butonuna tıklayabilirsiniz.',
+
+ // Exam Reports (/rapor/sinav, /rapor/sinavkarne, /rapor/yanliskonu, /ogrencisoruanaliz parity)
+ 'exams.pageTitle': 'Sınav Raporları - BeKultur',
+ 'exams.title': 'Sınav Raporları',
+ 'exams.subtitle': 'Sınav Karne, Gelişim Analizi & Öğrenci Soru Analiz',
+ 'exams.syncedLabel': 'Son güncelleme:',
+ 'exams.syncBtn': 'Sınavları Güncelle',
+ 'exams.syncing': 'Güncelleniyor...',
+ 'exams.kpiLatestNet': 'Son Sınav Neti',
+ 'exams.kpiVsPrior': 'net (önceki sınava göre)',
+ 'exams.kpiBaseline': 'İlk sınav (Referans)',
+ 'exams.kpiBestNet': 'En Yüksek Net',
+ 'exams.kpiAcrossExams': 'Toplam {count} sınav içinde',
+ 'exams.kpiAvgNet': 'Ortalama Net',
+ 'exams.kpiAvgSub': 'Genel net ortalaması',
+ 'exams.kpiCurrentRank': 'Genel Sıra',
+ 'exams.kpiBestRank': 'En iyi derece: #{rank}',
+ 'exams.kpiGeneralStanding': 'Genel sıralama',
+ 'exams.filterAll': 'Tüm Sınavlar',
+ 'exams.answerKey': 'Cevap Anahtarı',
+ 'exams.generalRankLabel': 'Genel Sıra :',
+ 'exams.schoolRankLabel': 'Okul Sıra :',
+ 'exams.rankDeltaUnit': 'sıra',
+ 'exams.reviewMistakesBtn': '{count} Yanlış / Boş Soruyu İncele',
+ 'exams.subtabBreakdown': 'Sınav Karne (Ders Dağılımı)',
+ 'exams.subtabWeakness': 'Yanlış Konular (Zayıf Konu Analizi)',
+ 'exams.colSubject': 'Ders',
+ 'exams.colQuestions': 'Soru',
+ 'exams.colCorrect': 'Doğru',
+ 'exams.colWrong': 'Yanlış',
+ 'exams.colEmpty': 'Boş',
+ 'exams.colNet': 'Net',
+ 'exams.colDeltaNet': 'Net Değişim (Δ)',
+ 'exams.colSuccessRate': 'Başarı Oranı',
+ 'exams.rowTotal': 'TOPLAM',
+ 'exams.viewWrongQuestionsTitle': '{count} yanlış soruyu görüntülemek için tıklayınız',
+ 'exams.viewEmptyQuestionsTitle': '{count} boş soruyu görüntülemek için tıklayınız',
+ 'exams.weaknessLoading': 'Yanlış konu analizi yükleniyor...',
+ 'exams.weaknessEmpty': 'Bu sınav için henüz yanlış konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.',
+ 'exams.weaknessError': 'Yanlış konu raporu yüklenirken bir hata oluştu.',
+ 'exams.weaknessTotal': 'Toplam:',
+ 'exams.weaknessCorrect': 'Doğru:',
+ 'exams.weaknessWrong': 'Yanlış:',
+ 'exams.weaknessEmptyCount': 'Boş:',
+ 'exams.modalTitle': 'Öğrenci Soru Analiz',
+ 'exams.modalSubtitle': 'Yanlış ve Boş Bırakılan Sorular',
+ 'exams.modalTypeAll': 'Tümü',
+ 'exams.modalTypeWrong': 'Yanlış',
+ 'exams.modalTypeEmpty': 'Boş',
+ 'exams.modalAllMistakes': 'Tüm Sorular',
+ 'exams.modalLoading': 'Sorular getiriliyor...',
+ 'exams.modalNoMatch': 'Seçili filtrelere uygun soru bulunamadı.',
+ 'exams.modalError': 'Sorular yüklenirken bir hata oluştu.',
+ 'exams.questionNo': 'SoruNo: {num}',
+ 'exams.correctAnswer': 'Doğru Cevap:',
+ 'exams.studentAnswer': 'Öğrenci Cevap:',
+ 'exams.emptyAnswerText': 'Boş',
+ 'exams.zoomHint': 'Büyütmek için tıklayınız',
+ 'exams.noImage': 'Soru görseli bulunamadı.',
+ 'exams.emptyTitle': 'Henüz Sınav Raporu Bulunmuyor',
+ 'exams.emptyDesc': 'Öğrenci portalındaki sınav karnelerinizi içe aktarmak için "Sınavları Güncelle" butonuna tıklayınız.',
+
+ // Exam Ratings
+ 'rating.Breakthrough': 'Sıçrama',
+ 'rating.Outperformed Curve': 'Zor Sınavda Başarı',
+ 'rating.Net Growth': 'Net Artışı',
+ 'rating.Rank Climb': 'Sıralama Yükselişi',
+ 'rating.Top 10 Consistency': 'İlk 10 İstikrarı',
+ 'rating.Needs Review': 'Tekrar Gerekli',
+ 'rating.Stable Performance': 'Dengeli Performans',
+ 'rating.Top 10 Baseline': 'İlk 10 Başlangıç',
+ 'rating.Baseline Exam': 'İlk Sınav',
+
+ // PWA & Offline
+ 'pwa.offlineBadge': '⚡ Çevrimdışı',
+ 'pwa.offlineText': 'Önbellekteki veriler gösteriliyor. Bağlantı gerektiren işlemler duraklatıldı.',
+ 'pwa.onlineBadge': '✓ Çevrimiçi',
+ 'pwa.onlineText': 'Bağlantı yeniden sağlandı. Canlı özellikler aktif.',
+ 'pwa.offlineSuffix': '(Çevrimdışı)',
+ 'pwa.offlineCheckboxTitle': 'Çevrimdışı mod: Ödev durumu bağlantı olmadan değiştirilemez.',
+ 'pwa.offlineExcludeTitle': 'Çevrimdışı mod: Ödev bağlantı olmadan hariç tutulamaz.',
+ 'pwa.offlineStationTitle': 'Çevrimdışı mod: İstasyon seçimi bağlantı gerektirir.',
+ 'pwa.offlineSyncTitle': 'Çevrimdışı mod: Senkronizasyon internet bağlantısı gerektirir.',
+ 'pwa.offlinePrivateNotice': '⚡ Çevrimdışı mod: Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.'
+ },
+
+ en: {
+ // Brand & Common
+ 'app.title': 'BeKultur (Better E-Kultur)',
+ 'nav.homework': 'Homework',
+ 'nav.syllabus': 'Syllabus',
+ 'nav.privateLessons': 'Private Lessons',
+ 'nav.exams': 'Exams',
+ 'header.student': 'Student',
+ 'header.logout': 'Log out',
+ 'header.themeToggle': 'Toggle Theme',
+ 'header.themeLight': 'Light Theme',
+ 'header.themeDark': 'Dark Theme',
+ 'header.langToggleTitle': 'Switch Language / Dili Değiştir',
+
+ // Login
+ 'login.pageTitle': 'Login - BeKultur (Better E-Kultur)',
+ 'login.subtitle': 'Log in with your school portal credentials.',
+ 'login.studentIdLabel': 'Student ID',
+ 'login.studentIdPlaceholder': 'Student ID',
+ 'login.passwordLabel': 'Password',
+ 'login.passwordPlaceholder': 'Password',
+ 'login.rememberMe': 'Remember credentials',
+ 'login.submit': 'Log In',
+ 'login.submitting': 'Logging in...',
+ 'login.errorMissing': 'Please enter both Student ID and Password.',
+ 'login.errorInvalid': 'Authentication failed. Please check your credentials.',
+ 'login.errorServer': 'An unexpected server error occurred during login.',
+
+ // Homework / Dashboard
+ 'dashboard.pageTitle': 'Dashboard - BeKultur',
+ 'dashboard.title': 'Homework',
+ 'dashboard.studentLabel': 'Student',
+ 'dashboard.lastSynced': 'Last synced:',
+ 'dashboard.notSynced': 'Not synced',
+ 'dashboard.syncRecent': 'Sync Recent',
+ 'dashboard.syncAll': 'Sync Full History',
+ 'dashboard.syncing': 'Syncing...',
+ 'dashboard.syncingAll': 'Syncing all...',
+ 'dashboard.fetchingRecent': 'Fetching recent assignments...',
+ 'dashboard.fetchingAll': 'Syncing full history from portal...',
+ 'dashboard.syncFailed': 'Sync failed:',
+ 'dashboard.networkError': 'Network error while syncing.',
+ 'dashboard.statCompletion': 'Completion',
+ 'dashboard.statDoneUnit': 'done',
+ 'dashboard.statActive': 'Active',
+ 'dashboard.statActiveSub': 'In progress',
+ 'dashboard.statNextWeek': 'Checked Next Week',
+ 'dashboard.statNextWeekSub': 'Due or checked next week',
+ 'dashboard.statDueSoon': 'Due Soon',
+ 'dashboard.statDueSoonSub': 'Within 3 days',
+ 'dashboard.statOverdue': 'Overdue',
+ 'dashboard.statOverdueSub': 'Past deadline',
+ 'dashboard.statTotal': 'Total',
+ 'dashboard.statTotalSub': 'All assignments',
+ 'dashboard.subjectsTitle': 'Subjects',
+ 'dashboard.tabAll': 'All',
+ 'dashboard.tabNextWeek': 'Checked Next Week',
+ 'dashboard.tabActive': 'Active',
+ 'dashboard.tabDueSoon': 'Due Soon',
+ 'dashboard.tabCompleted': 'Completed',
+ 'dashboard.tabOverdue': 'Overdue',
+ 'dashboard.tabExcluded': 'Excluded',
+ 'dashboard.searchPlaceholder': 'Filter by subject, book, or description...',
+ 'dashboard.allSubjectsOption': 'All Subjects',
+ 'dashboard.showingCount': 'Showing {count} assignments',
+ 'dashboard.noResults': 'No matching assignments found.',
+ 'dashboard.resetFilters': 'Reset filters',
+ 'dashboard.checkDateBadge': 'Kontrol:',
+ 'dashboard.badgeExcluded': 'Excluded',
+ 'dashboard.badgeCompleted': 'Done',
+ 'dashboard.badgeNextWeek': 'Next Week',
+ 'dashboard.badgeDueSoon': 'Due Soon',
+ 'dashboard.badgeOverdue': 'Overdue',
+ 'dashboard.badgeActive': 'Active',
+ 'dashboard.btnExclude': 'Exclude',
+ 'dashboard.btnRestore': 'Restore',
+ 'dashboard.btnExcludeTitle': 'Exclude this homework (e.g. from another class)',
+ 'dashboard.btnRestoreTitle': 'Restore this homework to your active list',
+ 'dashboard.unitLabel': 'Ünite:',
+ 'dashboard.topicLabel': 'Konu:',
+ 'dashboard.dateRangeLabel': 'Start - End Date:',
+ 'dashboard.descriptionLabel': 'Description:',
+ 'dashboard.completedOn': 'Done:',
+ 'dashboard.offlineToggleAlert': 'You are offline. Homework status cannot be changed without an internet connection.',
+ 'dashboard.offlineExcludeAlert': 'You are offline. Excluding/restoring homework requires an internet connection.',
+ 'dashboard.offlineSyncAlert': 'You are offline. Syncing requires an internet connection.',
+
+ // Syllabus
+ 'syllabus.pageTitle': 'Syllabus - BeKultur',
+ 'syllabus.title': 'Syllabus',
+ 'syllabus.weekLabel': 'Week:',
+ 'syllabus.syncedLabel': 'Synced:',
+ 'syllabus.notSynced': 'Not synced',
+ 'syllabus.syncBtn': 'Sync Syllabus',
+ 'syllabus.syncing': 'Syncing...',
+ 'syllabus.fetchingAlert': 'Fetching weekly timetable across all 5 days...',
+ 'syllabus.updatedAlert': 'Syllabus updated successfully!',
+ 'syllabus.stationLabel': 'Station:',
+ 'syllabus.allStations': 'All Stations',
+ 'syllabus.advisorLabel': 'Advisor:',
+ 'syllabus.advisoryTag': 'Danışmanlık',
+ 'syllabus.viewLabel': 'View:',
+ 'syllabus.dayView': 'Day View',
+ 'syllabus.weekView': 'Full Week Grid',
+ 'syllabus.todayBadge': 'Today',
+ 'syllabus.noLessonsDay': 'No lessons found for {day}. Click "Sync Syllabus" to fetch from portal.',
+ 'syllabus.classBadge': 'Class',
+ 'syllabus.periodHeader': 'Period',
+ 'syllabus.periodNumberLabel': '{period}. Ders',
+ 'syllabus.nowInSession': 'Now in session: {period} — {subject} ({time})',
+ 'syllabus.nextUp': 'Next up: {period} — {subject} at {time}',
+ 'syllabus.offlineStationAlert': 'You are offline. Station selection requires an internet connection.',
+
+ // Private Lessons
+ 'privateLessons.pageTitle': 'Private Lessons - BeKultur',
+ 'privateLessons.title': 'Private Lessons',
+ 'privateLessons.subtitle': 'Özel Ders & Başvuru',
+ 'privateLessons.syncedLabel': 'Synced:',
+ 'privateLessons.syncBtn': 'Sync Lessons',
+ 'privateLessons.syncing': 'Syncing...',
+ 'privateLessons.syncSuccess': 'Successfully refreshed {count} private lesson records.',
+ 'privateLessons.advisorLabel': 'Advisor:',
+ 'privateLessons.policyNote': 'Başkası adına özel ders almayınız, seçtiğiniz öğretmen onayladığı takdirde özel derse alınacaksınız.',
+ 'privateLessons.requestTitle': 'New Lesson Request (Özel Ders İstek)',
+ 'privateLessons.onlineBadge': 'Online Başvuru',
+ 'privateLessons.courseLabel': 'Ders (Course)',
+ 'privateLessons.unitLabel': 'Ünite (Unit)',
+ 'privateLessons.topicLabel': 'Konu (Topic)',
+ 'privateLessons.loading': 'Loading...',
+ 'privateLessons.selectPrompt': 'Seçiniz...',
+ 'privateLessons.selectCourseFirst': 'Önce ders seçiniz...',
+ 'privateLessons.selectUnitFirst': 'Önce ünite seçiniz...',
+ 'privateLessons.noUnitFound': 'Ünite bulunamadı',
+ 'privateLessons.noTopicFound': 'Konu bulunamadı',
+ 'privateLessons.errorOccurred': 'Hata oluştu',
+ 'privateLessons.submitBtn': 'Submit Request (Gönder)',
+ 'privateLessons.submittingBtn': 'Gönderiliyor...',
+ 'privateLessons.myLessonsTitle': 'My Lessons (Özel Derslerim)',
+ 'privateLessons.filterAll': 'All',
+ 'privateLessons.upcomingGroupTitle': 'Upcoming / Approved Lessons',
+ 'privateLessons.upcomingBadge': 'Upcoming',
+ 'privateLessons.activeCountBadge': '{count} Active',
+ 'privateLessons.pastGroupTitle': 'Lesson History',
+ 'privateLessons.pastCountBadge': '{count} Past',
+ 'privateLessons.completedBadge': 'Completed',
+ 'privateLessons.emptyState': 'No private lessons recorded yet. Submit a request above or click Sync Lessons to fetch from the portal.',
+
+ // Exam Reports
+ 'exams.pageTitle': 'Exam Reports - BeKultur',
+ 'exams.title': 'Exam Reports',
+ 'exams.subtitle': 'Sınav Raporları, Gelişim Analizi & Soru İnceleme',
+ 'exams.syncedLabel': 'Synced:',
+ 'exams.syncBtn': 'Sync Exams',
+ 'exams.syncing': 'Syncing...',
+ 'exams.kpiLatestNet': 'Latest Net',
+ 'exams.kpiVsPrior': 'net vs prior',
+ 'exams.kpiBaseline': 'Baseline exam',
+ 'exams.kpiBestNet': 'Personal Best Net',
+ 'exams.kpiAcrossExams': 'Across all {count} exams',
+ 'exams.kpiAvgNet': 'Average Net',
+ 'exams.kpiAvgSub': 'Overall student mean',
+ 'exams.kpiCurrentRank': 'Current Rank',
+ 'exams.kpiBestRank': 'Best standing: #{rank}',
+ 'exams.kpiGeneralStanding': 'General standing',
+ 'exams.filterAll': 'All Exams',
+ 'exams.answerKey': 'Cevap Anahtarı',
+ 'exams.generalRankLabel': 'Genel Sıra :',
+ 'exams.schoolRankLabel': 'Okul Sıra :',
+ 'exams.rankDeltaUnit': 'sıra',
+ 'exams.reviewMistakesBtn': 'Review {count} Mistakes',
+ 'exams.subtabBreakdown': 'Subject Breakdown (Ders Dağılımı)',
+ 'exams.subtabWeakness': 'Topic Weaknesses (Zayıf Konular)',
+ 'exams.colSubject': 'Ders',
+ 'exams.colQuestions': 'Soru',
+ 'exams.colCorrect': 'Doğru',
+ 'exams.colWrong': 'Yanlış',
+ 'exams.colEmpty': 'Boş',
+ 'exams.colNet': 'Net',
+ 'exams.colDeltaNet': 'Net Değişim (Δ)',
+ 'exams.colSuccessRate': 'Başarı Oranı',
+ 'exams.rowTotal': 'TOPLAM',
+ 'exams.viewWrongQuestionsTitle': 'Click to view {count} wrong questions',
+ 'exams.viewEmptyQuestionsTitle': 'Click to view {count} blank questions',
+ 'exams.weaknessLoading': 'Zayıf konu analizi yükleniyor...',
+ 'exams.weaknessEmpty': 'Bu sınav için henüz zayıf konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.',
+ 'exams.weaknessError': 'Zayıf konu raporu yüklenirken bir hata oluştu.',
+ 'exams.weaknessTotal': 'Toplam:',
+ 'exams.weaknessCorrect': 'Doğru:',
+ 'exams.weaknessWrong': 'Yanlış:',
+ 'exams.weaknessEmptyCount': 'Boş:',
+ 'exams.modalTitle': 'Review Mistakes',
+ 'exams.modalSubtitle': 'Wrong & Blank Questions',
+ 'exams.modalTypeAll': 'All',
+ 'exams.modalTypeWrong': 'Wrong (Yanlış)',
+ 'exams.modalTypeEmpty': 'Blank (Boş)',
+ 'exams.modalAllMistakes': 'Tüm Yanlışlar',
+ 'exams.modalLoading': 'Sorular getiriliyor...',
+ 'exams.modalNoMatch': 'Seçili filtrelere uygun soru bulunamadı.',
+ 'exams.modalError': 'Sorular yüklenirken bir hata oluştu.',
+ 'exams.questionNo': 'Soru #{num}',
+ 'exams.correctAnswer': 'Doğru:',
+ 'exams.studentAnswer': 'Öğrenci:',
+ 'exams.emptyAnswerText': 'Boş',
+ 'exams.zoomHint': 'Büyütmek için tıklayınız',
+ 'exams.noImage': 'Soru görseli bulunamadı.',
+ 'exams.emptyTitle': 'Henüz Sınav Raporu Bulunmuyor',
+ 'exams.emptyDesc': 'Öğrenci portalındaki sınav verilerini içe aktarmak için "Sync Exams" butonuna tıklayınız.',
+
+ // Exam Ratings
+ 'rating.Breakthrough': 'Breakthrough',
+ 'rating.Outperformed Curve': 'Outperformed Curve',
+ 'rating.Net Growth': 'Net Growth',
+ 'rating.Rank Climb': 'Rank Climb',
+ 'rating.Top 10 Consistency': 'Top 10 Consistency',
+ 'rating.Needs Review': 'Needs Review',
+ 'rating.Stable Performance': 'Stable Performance',
+ 'rating.Top 10 Baseline': 'Top 10 Baseline',
+ 'rating.Baseline Exam': 'Baseline Exam',
+
+ // PWA & Offline
+ 'pwa.offlineBadge': '⚡ Offline',
+ 'pwa.offlineText': 'Showing locally cached data. Actions requiring connection are paused.',
+ 'pwa.onlineBadge': '✓ Online',
+ 'pwa.onlineText': 'Connection restored. Live features re-enabled.',
+ 'pwa.offlineSuffix': '(Offline)',
+ 'pwa.offlineCheckboxTitle': 'Offline mode: Homework status cannot be changed without connection.',
+ 'pwa.offlineExcludeTitle': 'Offline mode: Homework cannot be excluded without connection.',
+ 'pwa.offlineStationTitle': 'Offline mode: Station selection requires connection.',
+ 'pwa.offlineSyncTitle': 'Offline mode: Sync requires internet connection.',
+ 'pwa.offlinePrivateNotice': '⚡ Çevrimdışı mod: Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.'
+ }
+};
+
+export function normalizeLocale(input?: string | null): SupportedLocale {
+ if (!input) return DEFAULT_LOCALE;
+ const cleaned = input.trim().toLowerCase();
+ if (cleaned === 'en' || cleaned.startsWith('en-')) return 'en';
+ if (cleaned === 'tr' || cleaned.startsWith('tr-')) return 'tr';
+ return DEFAULT_LOCALE;
+}
+
+export function translate(
+ locale: SupportedLocale,
+ key: string,
+ params?: Record
+): string {
+ const dict = translations[locale] || translations[DEFAULT_LOCALE];
+ let template = dict[key] ?? translations[DEFAULT_LOCALE][key] ?? key;
+ if (params) {
+ for (const [k, v] of Object.entries(params)) {
+ template = template.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v));
+ }
+ }
+ return template;
+}
+
+export function createTranslator(locale: SupportedLocale) {
+ return (key: string, params?: Record): string => {
+ return translate(locale, key, params);
+ };
+}
+
+export function getClientDictionary(locale: SupportedLocale): Record {
+ return translations[locale] || translations[DEFAULT_LOCALE];
+}
diff --git a/src/services/secrets.ts b/src/services/secrets.ts
new file mode 100644
index 0000000..de5076d
--- /dev/null
+++ b/src/services/secrets.ts
@@ -0,0 +1,189 @@
+import fs from 'fs';
+import path from 'path';
+import crypto from 'crypto';
+
+const INSECURE_DEFAULTS = new Set([
+ 'bekultur_secret_key_change_in_production',
+ 'bekultur_default_secret_key_change_me',
+ ''
+]);
+
+interface StoredSecrets {
+ sessionSecret: string;
+ encryptionSecret: string;
+ createdAt: string;
+}
+
+let cachedSecrets: StoredSecrets | null = null;
+
+function getSecretsFilePath(): string {
+ const customDbPath = process.env.DB_PATH;
+ const dataDir = customDbPath
+ ? path.dirname(path.resolve(customDbPath))
+ : path.resolve(process.cwd(), 'data');
+ return path.join(dataDir, '.secrets.json');
+}
+
+function loadOrCreateSecrets(): StoredSecrets {
+ if (cachedSecrets) {
+ return cachedSecrets;
+ }
+
+ const secretsFile = getSecretsFilePath();
+ const dir = path.dirname(secretsFile);
+ if (!fs.existsSync(dir)) {
+ fs.mkdirSync(dir, { recursive: true });
+ }
+
+ if (fs.existsSync(secretsFile)) {
+ try {
+ const raw = fs.readFileSync(secretsFile, 'utf-8');
+ const parsed = JSON.parse(raw) as StoredSecrets;
+ if (parsed.sessionSecret && parsed.encryptionSecret) {
+ cachedSecrets = parsed;
+ return cachedSecrets;
+ }
+ } catch (err) {
+ console.warn('Warning: Could not read .secrets.json, regenerating secrets.');
+ }
+ }
+
+ const generated: StoredSecrets = {
+ sessionSecret: crypto.randomBytes(64).toString('hex'),
+ encryptionSecret: crypto.randomBytes(64).toString('hex'),
+ createdAt: new Date().toISOString()
+ };
+
+ try {
+ fs.writeFileSync(secretsFile, JSON.stringify(generated, null, 2), {
+ encoding: 'utf-8',
+ mode: 0o600
+ });
+ } catch (err) {
+ console.warn('Warning: Failed to persist .secrets.json to disk:', err);
+ }
+
+ cachedSecrets = generated;
+ return cachedSecrets;
+}
+
+/**
+ * Retrieve active session secret (prefers non-default env var, otherwise persistent generated secret)
+ */
+export function getSessionSecret(): string {
+ const envSecret = (process.env.SESSION_SECRET || '').trim();
+ if (envSecret && !INSECURE_DEFAULTS.has(envSecret)) {
+ return envSecret;
+ }
+ return loadOrCreateSecrets().sessionSecret;
+}
+
+/**
+ * Retrieve active encryption secret (prefers non-default env var, otherwise persistent generated secret)
+ */
+export function getEncryptionSecret(): string {
+ const envEnc = (process.env.ENCRYPTION_SECRET || process.env.CREDENTIAL_SECRET || '').trim();
+ if (envEnc && !INSECURE_DEFAULTS.has(envEnc)) {
+ return envEnc;
+ }
+ const envSess = (process.env.SESSION_SECRET || '').trim();
+ if (envSess && !INSECURE_DEFAULTS.has(envSess)) {
+ return envSess;
+ }
+ return loadOrCreateSecrets().encryptionSecret;
+}
+
+/**
+ * Encrypt sensitive text (student passwords, portal cookies) using AES-256-GCM with per-item random salt & IV
+ */
+export function encryptCredential(plaintext: string): string {
+ if (!plaintext) return '';
+ try {
+ const secret = getEncryptionSecret();
+ const salt = crypto.randomBytes(16);
+ const iv = crypto.randomBytes(12);
+ const key = crypto.scryptSync(secret, salt, 32);
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
+ let encrypted = cipher.update(plaintext, 'utf8', 'hex');
+ encrypted += cipher.final('hex');
+ const authTag = cipher.getAuthTag().toString('hex');
+ return `enc:v2:${salt.toString('hex')}:${iv.toString('hex')}:${authTag}:${encrypted}`;
+ } catch (err) {
+ console.error('Failed to encrypt credential:', err);
+ throw new Error('Encryption failure');
+ }
+}
+
+/**
+ * Decrypt stored credential, supporting both v2 (random salt) and legacy v1 (static salt + legacy fallback keys)
+ */
+export function decryptCredential(stored: string): string {
+ if (!stored) return '';
+ if (!stored.startsWith('enc:')) {
+ // Legacy plaintext support
+ return stored;
+ }
+
+ // v2 format: enc:v2::::
+ if (stored.startsWith('enc:v2:')) {
+ const parts = stored.split(':');
+ if (parts.length !== 6) return '';
+ const [, , saltHex, ivHex, authTagHex, ciphertextHex] = parts;
+ const candidateSecrets = Array.from(
+ new Set([
+ getEncryptionSecret(),
+ process.env.ENCRYPTION_SECRET || '',
+ process.env.SESSION_SECRET || ''
+ ].filter(Boolean))
+ );
+
+ for (const secret of candidateSecrets) {
+ try {
+ const key = crypto.scryptSync(secret, Buffer.from(saltHex, 'hex'), 32);
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
+ decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
+ let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
+ decrypted += decipher.final('utf8');
+ return decrypted;
+ } catch {
+ // Try next candidate key
+ }
+ }
+ return '';
+ }
+
+ // Legacy v1 format: enc:::
+ const parts = stored.split(':');
+ if (parts.length !== 4) return '';
+ const [, ivHex, authTagHex, ciphertextHex] = parts;
+
+ const legacyCandidateSecrets = Array.from(
+ new Set([
+ getEncryptionSecret(),
+ process.env.ENCRYPTION_SECRET || '',
+ process.env.SESSION_SECRET || '',
+ 'bekultur_secret_key_change_in_production',
+ 'bekultur_default_secret_key_change_me'
+ ].filter(Boolean))
+ );
+
+ for (const secret of legacyCandidateSecrets) {
+ try {
+ const key = crypto.scryptSync(secret, 'bekultur_credential_salt', 32);
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(ivHex, 'hex'));
+ decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
+ let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
+ decrypted += decipher.final('utf8');
+ return decrypted;
+ } catch {
+ // Try next candidate secret
+ }
+ }
+
+ console.error('Failed to decrypt legacy credential with any known key.');
+ return '';
+}
+
+export function isModernEncryptedFormat(stored: string): boolean {
+ return Boolean(stored && stored.startsWith('enc:v2:'));
+}
diff --git a/src/services/session-store.ts b/src/services/session-store.ts
new file mode 100644
index 0000000..6729707
--- /dev/null
+++ b/src/services/session-store.ts
@@ -0,0 +1,212 @@
+import session from 'express-session';
+import Database from 'better-sqlite3';
+import { encryptCredential, decryptCredential } from './secrets';
+
+const DEFAULT_TTL_MS = 14 * 24 * 60 * 60 * 1000; // 14 days
+const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
+
+export interface SQLiteSessionStoreOptions {
+ db: Database.Database;
+ ttlMs?: number;
+ pruneIntervalMs?: number;
+}
+
+export class SQLiteSessionStore extends session.Store {
+ private db: Database.Database;
+ private ttlMs: number;
+ private pruneTimer: NodeJS.Timeout | null = null;
+
+ constructor(options: SQLiteSessionStoreOptions) {
+ super();
+ this.db = options.db;
+ this.ttlMs = options.ttlMs || DEFAULT_TTL_MS;
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS sessions (
+ sid TEXT PRIMARY KEY,
+ sess TEXT NOT NULL,
+ expire INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire);
+ `);
+
+ this.pruneExpired();
+
+ const pruneInterval = options.pruneIntervalMs ?? DEFAULT_PRUNE_INTERVAL_MS;
+ if (pruneInterval > 0) {
+ this.pruneTimer = setInterval(() => {
+ this.pruneExpired();
+ }, pruneInterval);
+ if (this.pruneTimer.unref) {
+ this.pruneTimer.unref();
+ }
+ }
+ }
+
+ private computeExpireTimestamp(sess: session.SessionData): number {
+ if (sess?.cookie?.expires) {
+ const exp = new Date(sess.cookie.expires).getTime();
+ if (!isNaN(exp)) return exp;
+ }
+ if (typeof sess?.cookie?.maxAge === 'number') {
+ return Date.now() + sess.cookie.maxAge;
+ }
+ return Date.now() + this.ttlMs;
+ }
+
+ private serializeSession(sess: session.SessionData): string {
+ const clone: Record = { ...sess };
+ if (typeof clone.portalCookies === 'string' && clone.portalCookies.length > 0 && !clone.portalCookies.startsWith('enc:')) {
+ clone.portalCookies = encryptCredential(clone.portalCookies);
+ }
+ return JSON.stringify(clone);
+ }
+
+ private deserializeSession(rawJson: string): session.SessionData | null {
+ try {
+ const parsed = JSON.parse(rawJson);
+ if (typeof parsed.portalCookies === 'string' && parsed.portalCookies.startsWith('enc:')) {
+ parsed.portalCookies = decryptCredential(parsed.portalCookies);
+ }
+ return parsed as session.SessionData;
+ } catch {
+ return null;
+ }
+ }
+
+ public pruneExpired(): number {
+ try {
+ if (!this.db.open) return 0;
+ const info = this.db
+ .prepare('DELETE FROM sessions WHERE expire <= ?')
+ .run(Date.now());
+ return info.changes;
+ } catch {
+ return 0;
+ }
+ }
+
+ public get(
+ sid: string,
+ callback: (err: any, session?: session.SessionData | null) => void
+ ): void {
+ try {
+ const row = this.db
+ .prepare('SELECT sess, expire FROM sessions WHERE sid = ?')
+ .get(sid) as { sess: string; expire: number } | undefined;
+
+ if (!row) {
+ return callback(null, null);
+ }
+
+ if (row.expire <= Date.now()) {
+ this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
+ return callback(null, null);
+ }
+
+ const sess = this.deserializeSession(row.sess);
+ return callback(null, sess);
+ } catch (err) {
+ return callback(err);
+ }
+ }
+
+ public set(
+ sid: string,
+ sess: session.SessionData,
+ callback?: (err?: any) => void
+ ): void {
+ try {
+ const expire = this.computeExpireTimestamp(sess);
+ const serialized = this.serializeSession(sess);
+
+ this.db
+ .prepare(
+ 'INSERT INTO sessions (sid, sess, expire) VALUES (?, ?, ?) ON CONFLICT(sid) DO UPDATE SET sess = excluded.sess, expire = excluded.expire'
+ )
+ .run(sid, serialized, expire);
+
+ if (callback) callback(null);
+ } catch (err) {
+ if (callback) callback(err);
+ }
+ }
+
+ public destroy(sid: string, callback?: (err?: any) => void): void {
+ try {
+ this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
+ if (callback) callback(null);
+ } catch (err) {
+ if (callback) callback(err);
+ }
+ }
+
+ public touch(
+ sid: string,
+ sess: session.SessionData,
+ callback?: () => void
+ ): void {
+ try {
+ const expire = this.computeExpireTimestamp(sess);
+ this.db
+ .prepare('UPDATE sessions SET expire = ? WHERE sid = ?')
+ .run(expire, sid);
+ if (callback) callback();
+ } catch {
+ if (callback) callback();
+ }
+ }
+
+ public length(callback: (err: any, length?: number) => void): void {
+ try {
+ this.pruneExpired();
+ const row = this.db
+ .prepare('SELECT COUNT(*) as cnt FROM sessions')
+ .get() as { cnt: number };
+ callback(null, row.cnt);
+ } catch (err) {
+ callback(err);
+ }
+ }
+
+ public clear(callback?: (err?: any) => void): void {
+ try {
+ this.db.prepare('DELETE FROM sessions').run();
+ if (callback) callback(null);
+ } catch (err) {
+ if (callback) callback(err);
+ }
+ }
+
+ public all(
+ callback: (
+ err: any,
+ obj?: session.SessionData[] | { [sid: string]: session.SessionData } | null
+ ) => void
+ ): void {
+ try {
+ this.pruneExpired();
+ const rows = this.db
+ .prepare('SELECT sid, sess FROM sessions WHERE expire > ?')
+ .all(Date.now()) as Array<{ sid: string; sess: string }>;
+
+ const sessions: Record = {};
+ for (const r of rows) {
+ const parsed = this.deserializeSession(r.sess);
+ if (parsed) {
+ sessions[r.sid] = parsed;
+ }
+ }
+ callback(null, sessions);
+ } catch (err) {
+ callback(err);
+ }
+ }
+
+ public stopPruning(): void {
+ if (this.pruneTimer) {
+ clearInterval(this.pruneTimer);
+ this.pruneTimer = null;
+ }
+ }
+}
diff --git a/src/services/syllabus.ts b/src/services/syllabus.ts
index cd18583..240edaf 100644
--- a/src/services/syllabus.ts
+++ b/src/services/syllabus.ts
@@ -1,5 +1,6 @@
import { Lesson } from '../types';
import { InsightService } from './insight';
+import { SupportedLocale, translate } from './i18n';
export const DAY_NAMES: Record = {
1: 'Pazartesi',
@@ -167,7 +168,8 @@ export class SyllabusService {
public static getCurrentLessonStatus(
dayLessons: Lesson[],
currentDayNumber: number,
- refDate: Date = new Date()
+ refDate: Date = new Date(),
+ locale: SupportedLocale = 'tr'
): { currentLesson: Lesson | null; nextLesson: Lesson | null; statusText: string | null } {
const todayDay = refDate.getDay(); // 1 = Mon, ..., 5 = Fri
if (todayDay !== currentDayNumber) {
@@ -199,9 +201,17 @@ export class SyllabusService {
let statusText: string | null = null;
if (current) {
- statusText = `Now in session: ${current.period} — ${current.subject} (${current.time})`;
+ statusText = translate(locale, 'syllabus.nowInSession', {
+ period: current.period,
+ subject: current.subject,
+ time: current.time
+ });
} else if (next) {
- statusText = `Next up: ${next.period} — ${next.subject} at ${next.startTime}`;
+ statusText = translate(locale, 'syllabus.nextUp', {
+ period: next.period,
+ subject: next.subject,
+ time: next.startTime
+ });
}
return { currentLesson: current, nextLesson: next, statusText };
diff --git a/test/run-tests.ts b/test/run-tests.ts
index fb6e1df..448a3d2 100644
--- a/test/run-tests.ts
+++ b/test/run-tests.ts
@@ -1,5 +1,11 @@
import assert from 'assert';
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import crypto from 'crypto';
import { LocalDatabase } from '../src/services/db';
+import { SQLiteSessionStore } from '../src/services/session-store';
+import { translate, normalizeLocale } from '../src/services/i18n';
import { InsightService } from '../src/services/insight';
import { ScraperService } from '../src/services/scraper';
import { SyllabusService } from '../src/services/syllabus';
@@ -11,6 +17,13 @@ async function runAllTests() {
console.log(' BeKultur - Automated Test Suite');
console.log('========================================================\n');
+ // Use an isolated temporary directory so tests never pollute production data/
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bekultur-test-'));
+ const testDbPath = path.join(tempDir, 'test-bekultur.db');
+ const testLegacyJsonPath = path.join(tempDir, 'nonexistent-legacy.json');
+ process.env.DB_PATH = testDbPath;
+ process.env.LEGACY_JSON_PATH = testLegacyJsonPath;
+
let passed = 0;
let failed = 0;
@@ -28,166 +41,83 @@ async function runAllTests() {
})();
}
- // 1. Date Parsing
- await test('InsightService: parsePortalDate parses Turkish DD.MM.YYYY correctly', () => {
- const d1 = InsightService.parsePortalDate('20.10.2026');
- assert(d1 !== null, 'Date should not be null');
- assert.strictEqual(d1.getFullYear(), 2026);
- assert.strictEqual(d1.getMonth(), 9);
- assert.strictEqual(d1.getDate(), 20);
+ try {
+ // 1. Date Parsing
+ await test('InsightService: parsePortalDate parses Turkish DD.MM.YYYY correctly', () => {
+ const d1 = InsightService.parsePortalDate('20.10.2026');
+ assert(d1 !== null, 'Date should not be null');
+ assert.strictEqual(d1.getFullYear(), 2026);
+ assert.strictEqual(d1.getMonth(), 9);
+ assert.strictEqual(d1.getDate(), 20);
- const d2 = InsightService.parsePortalDate('8.11.2026');
- assert(d2 !== null);
- assert.strictEqual(d2.getMonth(), 10);
- assert.strictEqual(d2.getDate(), 8);
+ const d2 = InsightService.parsePortalDate('8.11.2026');
+ assert(d2 !== null);
+ assert.strictEqual(d2.getMonth(), 10);
+ assert.strictEqual(d2.getDate(), 8);
- const invalid = InsightService.parsePortalDate('');
- assert.strictEqual(invalid, null);
- });
+ const invalid = InsightService.parsePortalDate('');
+ assert.strictEqual(invalid, null);
+ });
- // 2. Teacher Note Extraction
- await test('InsightService: extractTeacherCheckNote detects various teacher notes', () => {
- const n1 = InsightService.extractTeacherCheckNote('fenomen ayt 237-242 kontrol tarihi 26-30 ekim');
- assert.strictEqual(n1?.toLowerCase(), '26-30 ekim');
+ // 2. Teacher Note Extraction
+ await test('InsightService: extractTeacherCheckNote detects various teacher notes', () => {
+ const n1 = InsightService.extractTeacherCheckNote('fenomen ayt 237-242 kontrol tarihi 26-30 ekim');
+ assert.strictEqual(n1?.toLowerCase(), '26-30 ekim');
- const n2 = InsightService.extractTeacherCheckNote('3D TYT sf. 99-118 + 3D AYT sf. 123-130 (kontrol tarihi 27 Ekim)');
- assert.strictEqual(n2?.toLowerCase(), '27 ekim');
+ const n2 = InsightService.extractTeacherCheckNote('3D TYT sf. 99-118 + 3D AYT sf. 123-130 (kontrol tarihi 27 Ekim)');
+ assert.strictEqual(n2?.toLowerCase(), '27 ekim');
- const n3 = InsightService.extractTeacherCheckNote('12 MF:X YAYINCILIK (ÖDEVLER 26-30 EKİM ARASINDA KONTROL EDİLECEKTİR.)');
- assert.strictEqual(n3?.toLowerCase(), '26-30 ekim');
+ const n3 = InsightService.extractTeacherCheckNote('12 MF:X YAYINCILIK (ÖDEVLER 26-30 EKİM ARASINDA KONTROL EDİLECEKTİR.)');
+ assert.strictEqual(n3?.toLowerCase(), '26-30 ekim');
- const n4 = InsightService.extractTeacherCheckNote('AYT 1. KİTAP [26-56] ÇÖZÜLECEKTİR. 26 10 KONTROL');
- assert.strictEqual(n4?.toLowerCase(), '26 ekim');
+ const n4 = InsightService.extractTeacherCheckNote('AYT 1. KİTAP [26-56] ÇÖZÜLECEKTİR. 26 10 KONTROL');
+ assert.strictEqual(n4?.toLowerCase(), '26 ekim');
- const nNone = InsightService.extractTeacherCheckNote('Toprak Yayınları Bölüm 4 çözülecek.');
- assert.strictEqual(nNone, null);
- });
+ const nNone = InsightService.extractTeacherCheckNote('Toprak Yayınları Bölüm 4 çözülecek.');
+ assert.strictEqual(nNone, null);
+ });
- // 3. Status Computation
- await test('InsightService: computeStatus correctly handles completed, next-week, and overdue', () => {
- const refDate = new Date(2026, 9, 21);
+ // 3. Status Computation
+ await test('InsightService: computeStatus correctly handles completed, next-week, and overdue', () => {
+ const refDate = new Date(2026, 9, 21);
- const s1 = InsightService.computeStatus({
- id: 'test1',
- subject: 'Matematik',
- type: 'Yayın',
- unit: '',
- topic: '',
- startDate: '10.10.2026',
- endDate: '25.10.2026',
- parsedStartDate: '2026-10-10',
- parsedEndDate: '2026-10-25',
- description: 'Test',
- detectedCheckDate: null,
- completed: true,
- completedAt: '2026-10-21T10:00:00Z'
- }, refDate);
- assert.strictEqual(s1, 'completed');
-
- const s2 = InsightService.computeStatus({
- id: 'test2',
- subject: 'Biyoloji',
- type: 'Yayın',
- unit: '',
- topic: '',
- startDate: '01.10.2026',
- endDate: '19.10.2026',
- parsedStartDate: '2026-10-01',
- parsedEndDate: '2026-10-19',
- description: 'Old test',
- detectedCheckDate: null,
- completed: false,
- completedAt: null
- }, refDate);
- assert.strictEqual(s2, 'overdue');
-
- const s3 = InsightService.computeStatus({
- id: 'test3',
- subject: 'AYT Kimya',
- type: 'Yayın',
- unit: '',
- topic: '',
- startDate: '20.10.2026',
- endDate: '26.10.2026',
- parsedStartDate: '2026-10-20',
- parsedEndDate: '2026-10-26',
- description: 'ayt 237-242 kontrol tarihi 26-30 ekim',
- detectedCheckDate: '26-30 ekim',
- completed: false,
- completedAt: null
- }, refDate);
- assert.strictEqual(s3, 'next-week');
- });
-
- // 4. Statistics Calculation
- await test('InsightService: calculateStats computes accurate completion rates and subject breakdown', () => {
- const sampleAssignments: Assignment[] = [
- {
- id: '1',
- subject: 'Kimya',
- type: 'Yayın',
- unit: '',
- topic: '',
- startDate: '20.10.2026',
- endDate: '26.10.2026',
- parsedStartDate: '2026-10-20',
- parsedEndDate: '2026-10-26',
- description: 'Test 1',
- detectedCheckDate: null,
- status: 'next-week',
- completed: false,
- completedAt: null
- },
- {
- id: '2',
- subject: 'Kimya',
+ const s1 = InsightService.computeStatus({
+ id: 'test1',
+ subject: 'Matematik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '10.10.2026',
- endDate: '15.10.2026',
+ endDate: '25.10.2026',
parsedStartDate: '2026-10-10',
- parsedEndDate: '2026-10-15',
- description: 'Test 2',
+ parsedEndDate: '2026-10-25',
+ description: 'Test',
detectedCheckDate: null,
- status: 'completed',
completed: true,
completedAt: '2026-10-21T10:00:00Z'
- },
- {
- id: '3',
- subject: 'Fizik',
+ }, refDate);
+ assert.strictEqual(s1, 'completed');
+
+ const s2 = InsightService.computeStatus({
+ id: 'test2',
+ subject: 'Biyoloji',
type: 'Yayın',
unit: '',
topic: '',
startDate: '01.10.2026',
- endDate: '10.10.2026',
+ endDate: '19.10.2026',
parsedStartDate: '2026-10-01',
- parsedEndDate: '2026-10-10',
- description: 'Test 3',
+ parsedEndDate: '2026-10-19',
+ description: 'Old test',
detectedCheckDate: null,
- status: 'overdue',
completed: false,
completedAt: null
- }
- ];
+ }, refDate);
+ assert.strictEqual(s2, 'overdue');
- const stats = InsightService.calculateStats(sampleAssignments);
- assert.strictEqual(stats.total, 3);
- assert.strictEqual(stats.completed, 1);
- assert.strictEqual(stats.checkedNextWeek, 1);
- assert.strictEqual(stats.overdue, 1);
- assert.strictEqual(stats.completionRate, 33);
- assert.strictEqual(stats.bySubject['Kimya'].total, 2);
- assert.strictEqual(stats.bySubject['Kimya'].completed, 1);
- assert.strictEqual(stats.bySubject['Kimya'].percentage, 50);
-
- // Test with an excluded (disincluded) assignment
- const sampleWithExcluded: Assignment[] = [
- ...sampleAssignments,
- {
- id: '4',
- subject: 'Fizik',
+ const s3 = InsightService.computeStatus({
+ id: 'test3',
+ subject: 'AYT Kimya',
type: 'Yayın',
unit: '',
topic: '',
@@ -195,365 +125,491 @@ async function runAllTests() {
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
- description: 'Other class homework',
+ description: 'ayt 237-242 kontrol tarihi 26-30 ekim',
+ detectedCheckDate: '26-30 ekim',
+ completed: false,
+ completedAt: null
+ }, refDate);
+ assert.strictEqual(s3, 'next-week');
+ });
+
+ // 4. Statistics Calculation
+ await test('InsightService: calculateStats computes accurate completion rates and subject breakdown', () => {
+ const sampleAssignments: Assignment[] = [
+ {
+ id: '1',
+ subject: 'Kimya',
+ type: 'Yayın',
+ unit: '',
+ topic: '',
+ startDate: '20.10.2026',
+ endDate: '26.10.2026',
+ parsedStartDate: '2026-10-20',
+ parsedEndDate: '2026-10-26',
+ description: 'Test 1',
+ detectedCheckDate: null,
+ status: 'next-week',
+ completed: false,
+ completedAt: null
+ },
+ {
+ id: '2',
+ subject: 'Kimya',
+ type: 'Yayın',
+ unit: '',
+ topic: '',
+ startDate: '10.10.2026',
+ endDate: '15.10.2026',
+ parsedStartDate: '2026-10-10',
+ parsedEndDate: '2026-10-15',
+ description: 'Test 2',
+ detectedCheckDate: null,
+ status: 'completed',
+ completed: true,
+ completedAt: '2026-10-21T10:00:00Z'
+ },
+ {
+ id: '3',
+ subject: 'Fizik',
+ type: 'Yayın',
+ unit: '',
+ topic: '',
+ startDate: '01.10.2026',
+ endDate: '10.10.2026',
+ parsedStartDate: '2026-10-01',
+ parsedEndDate: '2026-10-10',
+ description: 'Test 3',
+ detectedCheckDate: null,
+ status: 'overdue',
+ completed: false,
+ completedAt: null
+ }
+ ];
+
+ const stats = InsightService.calculateStats(sampleAssignments);
+ assert.strictEqual(stats.total, 3);
+ assert.strictEqual(stats.completed, 1);
+ assert.strictEqual(stats.checkedNextWeek, 1);
+ assert.strictEqual(stats.overdue, 1);
+ assert.strictEqual(stats.completionRate, 33);
+ assert.strictEqual(stats.bySubject['Kimya'].total, 2);
+ assert.strictEqual(stats.bySubject['Kimya'].completed, 1);
+ assert.strictEqual(stats.bySubject['Kimya'].percentage, 50);
+
+ // Test with an excluded (disincluded) assignment
+ const sampleWithExcluded: Assignment[] = [
+ ...sampleAssignments,
+ {
+ id: '4',
+ subject: 'Fizik',
+ type: 'Yayın',
+ unit: '',
+ topic: '',
+ startDate: '20.10.2026',
+ endDate: '26.10.2026',
+ parsedStartDate: '2026-10-20',
+ parsedEndDate: '2026-10-26',
+ description: 'Other class homework',
+ detectedCheckDate: null,
+ status: 'active',
+ completed: false,
+ completedAt: null,
+ excluded: true
+ }
+ ];
+
+ const statsExcluded = InsightService.calculateStats(sampleWithExcluded);
+ assert.strictEqual(statsExcluded.total, 3, 'Disincluded assignment must NOT increase total count');
+ assert.strictEqual(statsExcluded.excludedCount, 1);
+ assert.strictEqual(statsExcluded.bySubject['Fizik'].total, 1, 'Disincluded assignment must NOT be in subject total');
+ });
+
+ // 5. Local Database (SQLite)
+ await test('LocalDatabase (SQLite): save, merge, and toggle checkboxes with ACID persistence', () => {
+ const db = LocalDatabase.getInstance();
+ const testStudentId = `test_student_${Date.now()}`;
+
+ const testItem: Assignment = {
+ id: `hash_${Date.now()}`,
+ subject: 'Matematik',
+ type: 'Yayın',
+ unit: 'Fonksiyonlar',
+ topic: 'Test',
+ startDate: '20.10.2026',
+ endDate: '26.10.2026',
+ parsedStartDate: '2026-10-20',
+ parsedEndDate: '2026-10-26',
+ description: 'Sayfa 50-60',
detectedCheckDate: null,
status: 'active',
completed: false,
- completedAt: null,
- excluded: true
- }
- ];
+ completedAt: null
+ };
- const statsExcluded = InsightService.calculateStats(sampleWithExcluded);
- assert.strictEqual(statsExcluded.total, 3, 'Disincluded assignment must NOT increase total count');
- assert.strictEqual(statsExcluded.excludedCount, 1);
- assert.strictEqual(statsExcluded.bySubject['Fizik'].total, 1, 'Disincluded assignment must NOT be in subject total');
- });
+ db.mergeAssignments(testStudentId, [testItem]);
+ let store = db.getStudentStore(testStudentId);
+ assert(store.assignments[testItem.id]);
+ assert.strictEqual(store.assignments[testItem.id].completed, false);
- // 5. Local Database
- await test('LocalDatabase: save, merge, and toggle checkboxes in db.json', () => {
- const db = LocalDatabase.getInstance();
- const testStudentId = `test_student_${Date.now()}`;
+ const updated = db.toggleAssignment(testStudentId, testItem.id, true);
+ assert.strictEqual(updated?.completed, true);
+ assert(updated?.completedAt !== null);
- const testItem: Assignment = {
- id: `hash_${Date.now()}`,
- subject: 'Matematik',
- type: 'Yayın',
- unit: 'Fonksiyonlar',
- topic: 'Test',
- startDate: '20.10.2026',
- endDate: '26.10.2026',
- parsedStartDate: '2026-10-20',
- parsedEndDate: '2026-10-26',
- description: 'Sayfa 50-60',
- detectedCheckDate: null,
- status: 'active',
- completed: false,
- completedAt: null
- };
+ db.mergeAssignments(testStudentId, [{
+ ...testItem,
+ completed: false
+ }]);
+ store = db.getStudentStore(testStudentId);
+ assert.strictEqual(
+ store.assignments[testItem.id].completed,
+ true,
+ 'mergeAssignments MUST preserve user checked status!'
+ );
- db.mergeAssignments(testStudentId, [testItem]);
- let store = db.getStudentStore(testStudentId);
- assert(store.assignments[testItem.id]);
- assert.strictEqual(store.assignments[testItem.id].completed, false);
+ // Test disinclude / exclude toggle & preservation across merge
+ const excludedRes = db.toggleExcludeAssignment(testStudentId, testItem.id, true);
+ assert.strictEqual(excludedRes?.excluded, true);
- const updated = db.toggleAssignment(testStudentId, testItem.id, true);
- assert.strictEqual(updated?.completed, true);
- assert(updated?.completedAt !== null);
+ // Re-merge from scraper (which always returns excluded undefined or false)
+ db.mergeAssignments(testStudentId, [{
+ ...testItem,
+ completed: false
+ }]);
+ store = db.getStudentStore(testStudentId);
+ assert.strictEqual(
+ store.assignments[testItem.id].excluded,
+ true,
+ 'mergeAssignments MUST preserve disincluded (excluded) status across scraper syncs!'
+ );
- db.mergeAssignments(testStudentId, [{
- ...testItem,
- completed: false
- }]);
- store = db.getStudentStore(testStudentId);
- assert.strictEqual(
- store.assignments[testItem.id].completed,
- true,
- 'mergeAssignments MUST preserve user checked status!'
- );
+ // Restore / Include back
+ db.toggleExcludeAssignment(testStudentId, testItem.id, false);
+ store = db.getStudentStore(testStudentId);
+ assert.strictEqual(store.assignments[testItem.id].excluded, false);
- // Test disinclude / exclude toggle & preservation across merge
- const excludedRes = db.toggleExcludeAssignment(testStudentId, testItem.id, true);
- assert.strictEqual(excludedRes?.excluded, true);
-
- // Re-merge from scraper (which always returns excluded undefined or false)
- db.mergeAssignments(testStudentId, [{
- ...testItem,
- completed: false
- }]);
- store = db.getStudentStore(testStudentId);
- assert.strictEqual(
- store.assignments[testItem.id].excluded,
- true,
- 'mergeAssignments MUST preserve disincluded (excluded) status across scraper syncs!'
- );
-
- // Restore / Include back
- db.toggleExcludeAssignment(testStudentId, testItem.id, false);
- store = db.getStudentStore(testStudentId);
- assert.strictEqual(store.assignments[testItem.id].excluded, false);
-
- db.saveCredentials(testStudentId, 'test_pass');
- const creds = db.getRememberedCredentials(testStudentId);
- assert.strictEqual(creds?.password, 'test_pass');
- db.clearCredentials(testStudentId);
- assert.strictEqual(db.getRememberedCredentials(testStudentId), null);
- });
-
- // 6. Syllabus & Station Filtering Tests
- await test('SyllabusService: getWeekMetadata computes accurate ISO week and Monday-Friday dates', () => {
- const refDate = new Date(2026, 9, 21); // Wednesday 21 Oct 2026
- const meta = SyllabusService.getWeekMetadata(refDate);
-
- assert(meta.weekId.includes('2026-W43') || meta.weekId.includes('2026-W'), 'Must have valid week ID');
- assert(meta.weekRange.includes('19.10.2026 - 23.10.2026'), `Expected 19.10 - 23.10, got ${meta.weekRange}`);
- });
-
- await test('SyllabusService: normalizeStation handles various formats', () => {
- assert.strictEqual(SyllabusService.normalizeStation('İst4'), 'İst-4');
- assert.strictEqual(SyllabusService.normalizeStation('İst-4'), 'İst-4');
- assert.strictEqual(SyllabusService.normalizeStation('ist1'), 'İst-1');
- assert.strictEqual(SyllabusService.normalizeStation('2'), 'İst-2');
- assert.strictEqual(SyllabusService.normalizeStation(null), null);
- });
-
- await test('SyllabusService: filterLessonsForStation isolates student station and keeps class lessons', () => {
- const rawWednesdayLessons: Lesson[] = [
- // Period 1 has 5 stations + duplicates
- { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst1', day: 3, dayName: 'Çarşamba' },
- { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst2', day: 3, dayName: 'Çarşamba' },
- { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst3', day: 3, dayName: 'Çarşamba' },
- { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
- { period: '1. Ders', periodNumber: 1, subject: 'Türk Edebiyatı', teacher: 'OĞUZHAN YİĞİT', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst5', day: 3, dayName: 'Çarşamba' },
- // Period 2 is whole-class (no station)
- { period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
- ];
-
- // Filter for İst-4
- const filteredForIst4 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-4');
- assert.strictEqual(filteredForIst4.length, 2, 'Should have exactly 2 lessons: 1 for İst-4 and 1 for class');
- assert.strictEqual(filteredForIst4[0].subject, 'TYT Kimya');
- assert.strictEqual(filteredForIst4[0].station, 'İst4');
- assert.strictEqual(filteredForIst4[1].subject, 'TYT Matematik');
- assert.strictEqual(filteredForIst4[1].station, null);
-
- // Filter for İst-5
- const filteredForIst5 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-5');
- assert.strictEqual(filteredForIst5.length, 2);
- assert.strictEqual(filteredForIst5[0].subject, 'Türk Edebiyatı');
- assert.strictEqual(filteredForIst5[0].station, 'İst5');
-
- // Filter for "all"
- const filteredAll = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'all');
- assert.strictEqual(filteredAll.length, 6, 'Should show all 5 stations + 1 class lesson');
- });
-
- await test('SyllabusService: getCurrentLessonStatus correctly detects active and upcoming lessons', () => {
- const lessons: Lesson[] = [
- { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
- { period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
- ];
-
- // Simulate Wednesday at 09:45 (during 1. Ders)
- const activeTime = new Date(2026, 9, 21, 9, 45);
- const activeRes = SyllabusService.getCurrentLessonStatus(lessons, 3, activeTime);
- assert(activeRes.currentLesson !== null);
- assert.strictEqual(activeRes.currentLesson?.subject, 'TYT Kimya');
-
- // Simulate Wednesday at 10:08 (break before 2. Ders)
- const breakTime = new Date(2026, 9, 21, 10, 8);
- const breakRes = SyllabusService.getCurrentLessonStatus(lessons, 3, breakTime);
- assert.strictEqual(breakRes.currentLesson, null);
- assert(breakRes.nextLesson !== null);
- assert.strictEqual(breakRes.nextLesson?.subject, 'TYT Matematik');
- });
-
- await test('LocalDatabase: saveSyllabus, getSyllabus, and setStudentStation persist in db.json', () => {
- const db = LocalDatabase.getInstance();
- const testStudentId = `test_student_syl_${Date.now()}`;
-
- db.saveSyllabus(testStudentId, '2026-W43', '19.10.2026 - 23.10.2026', {
- 1: [],
- 2: [],
- 3: [],
- 4: [],
- 5: []
+ db.saveCredentials(testStudentId, 'test_pass');
+ const creds = db.getRememberedCredentials(testStudentId);
+ assert.strictEqual(creds?.password, 'test_pass');
+ db.clearCredentials(testStudentId);
+ assert.strictEqual(db.getRememberedCredentials(testStudentId), null);
});
- let s = db.getSyllabus(testStudentId);
- assert(s !== null);
- assert.strictEqual(s.weekId, '2026-W43');
+ // 6. Syllabus & Station Filtering Tests
+ await test('SyllabusService: getWeekMetadata computes accurate ISO week and Monday-Friday dates', () => {
+ const refDate = new Date(2026, 9, 21); // Wednesday 21 Oct 2026
+ const meta = SyllabusService.getWeekMetadata(refDate);
- db.setStudentStation(testStudentId, 'İst-4');
- s = db.getSyllabus(testStudentId);
- assert.strictEqual(s.selectedStation, 'İst-4');
- });
+ assert(meta.weekId.includes('2026-W43') || meta.weekId.includes('2026-W'), 'Must have valid week ID');
+ assert(meta.weekRange.includes('19.10.2026 - 23.10.2026'), `Expected 19.10 - 23.10, got ${meta.weekRange}`);
+ });
- // 7. Advisory Teacher & Private Lessons Tests
- await test('SyllabusService: advisoryTeacher filtering collapses multiple Danışmanlık teachers down to student advisor', () => {
- // 5 advisory variations for period 2
- const tuesdayLessons: Lesson[] = [
- { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
- { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'CAN TÜRKOĞLU', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
- { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'SEVGİ BİKİL', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
- { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MERVE BAŞTAN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
- { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MUSTAFA ŞEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' }
- ];
+ await test('SyllabusService: normalizeStation handles various formats', () => {
+ assert.strictEqual(SyllabusService.normalizeStation('İst4'), 'İst-4');
+ assert.strictEqual(SyllabusService.normalizeStation('İst-4'), 'İst-4');
+ assert.strictEqual(SyllabusService.normalizeStation('ist1'), 'İst-1');
+ assert.strictEqual(SyllabusService.normalizeStation('2'), 'İst-2');
+ assert.strictEqual(SyllabusService.normalizeStation(null), null);
+ });
- // Filter with CAN TÜRKOĞLU
- const filteredForCan = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'CAN TÜRKOĞLU');
- assert.strictEqual(filteredForCan.length, 1, 'Should filter out the other 4 teachers and keep exactly 1');
- assert.strictEqual(filteredForCan[0].teacher, 'CAN TÜRKOĞLU');
+ await test('SyllabusService: filterLessonsForStation isolates student station and keeps class lessons', () => {
+ const rawWednesdayLessons: Lesson[] = [
+ // Period 1 has 5 stations + duplicates
+ { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst1', day: 3, dayName: 'Çarşamba' },
+ { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst2', day: 3, dayName: 'Çarşamba' },
+ { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst3', day: 3, dayName: 'Çarşamba' },
+ { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
+ { period: '1. Ders', periodNumber: 1, subject: 'Türk Edebiyatı', teacher: 'OĞUZHAN YİĞİT', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst5', day: 3, dayName: 'Çarşamba' },
+ // Period 2 is whole-class (no station)
+ { period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
+ ];
- // Filter with ÜLKÜ ESEN
- const filteredForUlku = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'ÜLKÜ ESEN');
- assert.strictEqual(filteredForUlku.length, 1);
- assert.strictEqual(filteredForUlku[0].teacher, 'ÜLKÜ ESEN');
- });
+ // Filter for İst-4
+ const filteredForIst4 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-4');
+ assert.strictEqual(filteredForIst4.length, 2, 'Should have exactly 2 lessons: 1 for İst-4 and 1 for class');
+ assert.strictEqual(filteredForIst4[0].subject, 'TYT Kimya');
+ assert.strictEqual(filteredForIst4[0].station, 'İst4');
+ assert.strictEqual(filteredForIst4[1].subject, 'TYT Matematik');
+ assert.strictEqual(filteredForIst4[1].station, null);
- await test('LocalDatabase: savePrivateLessons, getPrivateLessons, and advisory teacher persistence', () => {
- const db = LocalDatabase.getInstance();
- const testStudentId = `test_student_pl_${Date.now()}`;
+ // Filter for İst-5
+ const filteredForIst5 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-5');
+ assert.strictEqual(filteredForIst5.length, 2);
+ assert.strictEqual(filteredForIst5[0].subject, 'Türk Edebiyatı');
+ assert.strictEqual(filteredForIst5[0].station, 'İst5');
- const mockLessons = [
- {
- id: 'pl_1',
- subject: 'Coğrafya',
- teacherName: 'SEVDA KILIÇOĞLU',
- teacherPhoto: 'http://example.com/2337.jpg',
- date: '26.10.2026',
- parsedDate: '2026-10-26',
- isUpcoming: true
- },
- {
- id: 'pl_2',
- subject: 'Danışmanlık',
- teacherName: 'CAN TÜRKOĞLU',
- teacherPhoto: 'http://example.com/2211.jpg',
- date: '20.10.2026',
- parsedDate: '2026-10-20',
- isUpcoming: false
- }
- ];
+ // Filter for "all"
+ const filteredAll = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'all');
+ assert.strictEqual(filteredAll.length, 6, 'Should show all 5 stations + 1 class lesson');
+ });
- db.savePrivateLessons(testStudentId, mockLessons, undefined, 'CAN TÜRKOĞLU');
+ await test('SyllabusService: getCurrentLessonStatus correctly detects active and upcoming lessons in TR & EN', () => {
+ const lessons: Lesson[] = [
+ { period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
+ { period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
+ ];
- const plStore = db.getPrivateLessons(testStudentId);
- assert(plStore !== null);
- assert.strictEqual(plStore.lessons.length, 2);
- assert.strictEqual(plStore.detectedAdvisor, 'CAN TÜRKOĞLU');
+ // Simulate Wednesday at 09:45 (during 1. Ders)
+ const activeTime = new Date(2026, 9, 21, 9, 45);
+ const activeResTr = SyllabusService.getCurrentLessonStatus(lessons, 3, activeTime, 'tr');
+ assert(activeResTr.currentLesson !== null);
+ assert.strictEqual(activeResTr.currentLesson?.subject, 'TYT Kimya');
+ assert(activeResTr.statusText?.includes('Şu anki ders:'), 'Default Turkish statusText must include "Şu anki ders:"');
- // Verify auto-set advisory teacher
- assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'CAN TÜRKOĞLU');
+ // Simulate Wednesday at 10:08 (break before 2. Ders)
+ const breakTime = new Date(2026, 9, 21, 10, 8);
+ const breakResEn = SyllabusService.getCurrentLessonStatus(lessons, 3, breakTime, 'en');
+ assert.strictEqual(breakResEn.currentLesson, null);
+ assert(breakResEn.nextLesson !== null);
+ assert.strictEqual(breakResEn.nextLesson?.subject, 'TYT Matematik');
+ assert(breakResEn.statusText?.includes('Next up:'), 'English statusText must include "Next up:"');
+ });
- // Manual override
- db.setStudentAdvisoryTeacher(testStudentId, 'SEVGİ BİKİL');
- assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'SEVGİ BİKİL');
- });
+ await test('LocalDatabase: saveSyllabus, getSyllabus, and setStudentStation persist in SQLite', () => {
+ const db = LocalDatabase.getInstance();
+ const testStudentId = `test_student_syl_${Date.now()}`;
- // 6. Exam Reports & Analytics Tests
- await test('ExamService: categorizeExam correctly segregates TYT and AYT', () => {
- assert.strictEqual(ExamService.categorizeExam('12 YKS-01_MF'), 'TYT');
- assert.strictEqual(ExamService.categorizeExam('12 YKS-04 MF'), 'TYT');
- assert.strictEqual(ExamService.categorizeExam('TYT Deneme Sınavı 3'), 'TYT');
- assert.strictEqual(ExamService.categorizeExam('12 AYT-01 MF'), 'AYT');
- assert.strictEqual(ExamService.categorizeExam('AYT Sayısal Deneme'), 'AYT');
- assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 80), 'AYT');
- assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 120), 'TYT');
- });
+ db.saveSyllabus(testStudentId, '2026-W43', '19.10.2026 - 23.10.2026', {
+ 1: [],
+ 2: [],
+ 3: [],
+ 4: [],
+ 5: []
+ });
- await test('ExamService: computeDeltasAndRatings calculates Net deltas, Rank deltas, and difficulty-adjusted ratings', () => {
- const mockExams: ExamReportDetail[] = [
- {
- summary: {
- id: '3322',
- name: '12 YKS-01_MF',
- examType: 'TYT',
- totalQuestions: 120,
- totalCorrect: 78,
- totalWrong: 22,
- totalEmpty: 20,
- totalNet: 72.50,
- totalScore: 72.50,
- generalRank: 16
+ let s = db.getSyllabus(testStudentId);
+ assert(s !== null);
+ assert.strictEqual(s.weekId, '2026-W43');
+
+ db.setStudentStation(testStudentId, 'İst-4');
+ s = db.getSyllabus(testStudentId);
+ assert(s !== null);
+ assert.strictEqual(s.selectedStation, 'İst-4');
+ });
+
+ // 7. Advisory Teacher & Private Lessons Tests
+ await test('SyllabusService: advisoryTeacher filtering collapses multiple Danışmanlık teachers down to student advisor', () => {
+ const tuesdayLessons: Lesson[] = [
+ { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
+ { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'CAN TÜRKOĞLU', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
+ { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'SEVGİ BİKİL', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
+ { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MERVE BAŞTAN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
+ { period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MUSTAFA ŞEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' }
+ ];
+
+ const filteredForCan = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'CAN TÜRKOĞLU');
+ assert.strictEqual(filteredForCan.length, 1, 'Should filter out the other 4 teachers and keep exactly 1');
+ assert.strictEqual(filteredForCan[0].teacher, 'CAN TÜRKOĞLU');
+
+ const filteredForUlku = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'ÜLKÜ ESEN');
+ assert.strictEqual(filteredForUlku.length, 1);
+ assert.strictEqual(filteredForUlku[0].teacher, 'ÜLKÜ ESEN');
+ });
+
+ await test('LocalDatabase: savePrivateLessons, getPrivateLessons, and advisory teacher persistence', () => {
+ const db = LocalDatabase.getInstance();
+ const testStudentId = `test_student_pl_${Date.now()}`;
+
+ const mockLessons = [
+ {
+ id: 'pl_1',
+ subject: 'Coğrafya',
+ teacherName: 'SEVDA KILIÇOĞLU',
+ teacherPhoto: 'http://example.com/2337.jpg',
+ date: '26.10.2026',
+ parsedDate: '2026-10-26',
+ isUpcoming: true
},
- subjects: [
- { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 6, emptyCount: 4, net: 28.5, score: 28.5, percentage: 71 }
- ],
- hasAnswerKey: true
- },
- {
- summary: {
- id: '3326',
- name: '12 YKS-02_MF',
- examType: 'TYT',
- totalQuestions: 120,
- totalCorrect: 88,
- totalWrong: 18,
- totalEmpty: 14,
- totalNet: 83.50,
- totalScore: 83.50,
- generalRank: 14
+ {
+ id: 'pl_2',
+ subject: 'Danışmanlık',
+ teacherName: 'CAN TÜRKOĞLU',
+ teacherPhoto: 'http://example.com/2211.jpg',
+ date: '20.10.2026',
+ parsedDate: '2026-10-20',
+ isUpcoming: false
+ }
+ ];
+
+ db.savePrivateLessons(testStudentId, mockLessons, undefined, 'CAN TÜRKOĞLU');
+
+ const plStore = db.getPrivateLessons(testStudentId);
+ assert(plStore !== null);
+ assert.strictEqual(plStore.lessons.length, 2);
+ assert.strictEqual(plStore.detectedAdvisor, 'CAN TÜRKOĞLU');
+
+ // Verify auto-set advisory teacher
+ assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'CAN TÜRKOĞLU');
+
+ // Manual override
+ db.setStudentAdvisoryTeacher(testStudentId, 'SEVGİ BİKİL');
+ assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'SEVGİ BİKİL');
+ });
+
+ // 8. Exam Reports & Analytics Tests
+ await test('ExamService: categorizeExam correctly segregates TYT and AYT', () => {
+ assert.strictEqual(ExamService.categorizeExam('12 YKS-01_MF'), 'TYT');
+ assert.strictEqual(ExamService.categorizeExam('12 YKS-04 MF'), 'TYT');
+ assert.strictEqual(ExamService.categorizeExam('TYT Deneme Sınavı 3'), 'TYT');
+ assert.strictEqual(ExamService.categorizeExam('12 AYT-01 MF'), 'AYT');
+ assert.strictEqual(ExamService.categorizeExam('AYT Sayısal Deneme'), 'AYT');
+ assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 80), 'AYT');
+ assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 120), 'TYT');
+ });
+
+ await test('ExamService: computeDeltasAndRatings calculates Net deltas, Rank deltas, and difficulty-adjusted ratings', () => {
+ const mockExams: ExamReportDetail[] = [
+ {
+ summary: {
+ id: '3322',
+ name: '12 YKS-01_MF',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 78,
+ totalWrong: 22,
+ totalEmpty: 20,
+ totalNet: 72.50,
+ totalScore: 72.50,
+ generalRank: 16
+ },
+ subjects: [
+ { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 6, emptyCount: 4, net: 28.5, score: 28.5, percentage: 71 }
+ ],
+ hasAnswerKey: true
},
- subjects: [
- { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 35, wrongCount: 2, emptyCount: 3, net: 34.5, score: 34.5, percentage: 86 }
- ],
- hasAnswerKey: true
- },
- {
- summary: {
- id: '3340',
- name: '12 YKS-03 MF',
- examType: 'TYT',
- totalQuestions: 120,
- totalCorrect: 92,
- totalWrong: 16,
- totalEmpty: 12,
- totalNet: 88.00,
- totalScore: 88.00,
- generalRank: 8
+ {
+ summary: {
+ id: '3326',
+ name: '12 YKS-02_MF',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 88,
+ totalWrong: 18,
+ totalEmpty: 14,
+ totalNet: 83.50,
+ totalScore: 83.50,
+ generalRank: 14
+ },
+ subjects: [
+ { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 35, wrongCount: 2, emptyCount: 3, net: 34.5, score: 34.5, percentage: 86 }
+ ],
+ hasAnswerKey: true
},
- subjects: [
- { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 36, wrongCount: 2, emptyCount: 2, net: 35.5, score: 35.5, percentage: 89 }
- ],
- hasAnswerKey: true
- },
- {
- summary: {
- id: '3366',
- name: '12 YKS-04 MF',
- examType: 'TYT',
- totalQuestions: 120,
- totalCorrect: 86,
- totalWrong: 14,
- totalEmpty: 20,
- totalNet: 82.50, // Net dropped due to harder test
- totalScore: 82.50,
- generalRank: 9 // Held single-digit rank #9
+ {
+ summary: {
+ id: '3340',
+ name: '12 YKS-03 MF',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 92,
+ totalWrong: 16,
+ totalEmpty: 12,
+ totalNet: 88.00,
+ totalScore: 88.00,
+ generalRank: 8
+ },
+ subjects: [
+ { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 36, wrongCount: 2, emptyCount: 2, net: 35.5, score: 35.5, percentage: 89 }
+ ],
+ hasAnswerKey: true
},
- subjects: [
- { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 7, emptyCount: 3, net: 28.25, score: 28.25, percentage: 75 }
- ],
- hasAnswerKey: true
- }
- ];
+ {
+ summary: {
+ id: '3366',
+ name: '12 YKS-04 MF',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 86,
+ totalWrong: 14,
+ totalEmpty: 20,
+ totalNet: 82.50,
+ totalScore: 82.50,
+ generalRank: 9
+ },
+ subjects: [
+ { subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 7, emptyCount: 3, net: 28.25, score: 28.25, percentage: 75 }
+ ],
+ hasAnswerKey: true
+ }
+ ];
- const processed = ExamService.computeDeltasAndRatings(mockExams);
- assert.strictEqual(processed.length, 4);
+ const processed = ExamService.computeDeltasAndRatings(mockExams);
+ assert.strictEqual(processed.length, 4);
- // Map by ID for assertion
- const yks1 = processed.find(p => p.summary.id === '3322')!;
- const yks2 = processed.find(p => p.summary.id === '3326')!;
- const yks3 = processed.find(p => p.summary.id === '3340')!;
- const yks4 = processed.find(p => p.summary.id === '3366')!;
+ const yks1 = processed.find(p => p.summary.id === '3322')!;
+ const yks2 = processed.find(p => p.summary.id === '3326')!;
+ const yks3 = processed.find(p => p.summary.id === '3340')!;
+ const yks4 = processed.find(p => p.summary.id === '3366')!;
- // Exam 1: Baseline
- assert.strictEqual(yks1.summary.deltaNet, undefined);
- assert.strictEqual(yks1.summary.deltaRank, undefined);
+ assert.strictEqual(yks1.summary.deltaNet, undefined);
+ assert.strictEqual(yks1.summary.deltaRank, undefined);
- // Exam 2: Net +11.00, Rank improved from 16 to 14 (+2 places climbed) -> Breakthrough
- assert.strictEqual(yks2.summary.deltaNet, 11.00);
- assert.strictEqual(yks2.summary.deltaRank, 2);
- assert.strictEqual(yks2.summary.rating?.label, 'Breakthrough');
- assert.strictEqual(yks2.subjects[0].deltaNet, 6.00); // 34.5 - 28.5
+ assert.strictEqual(yks2.summary.deltaNet, 11.00);
+ assert.strictEqual(yks2.summary.deltaRank, 2);
+ assert.strictEqual(yks2.summary.rating?.label, 'Breakthrough');
+ assert.strictEqual(yks2.subjects[0].deltaNet, 6.00);
- // Exam 3: Net +4.50, Rank improved from 14 to 8 (+6 places climbed) -> Breakthrough
- assert.strictEqual(yks3.summary.deltaNet, 4.50);
- assert.strictEqual(yks3.summary.deltaRank, 6);
- assert.strictEqual(yks3.summary.rating?.label, 'Breakthrough');
+ assert.strictEqual(yks3.summary.deltaNet, 4.50);
+ assert.strictEqual(yks3.summary.deltaRank, 6);
+ assert.strictEqual(yks3.summary.rating?.label, 'Breakthrough');
- // Exam 4: Net -5.50 (harder exam), but rank held in top 10 (#9) -> Outperformed Curve!
- assert.strictEqual(yks4.summary.deltaNet, -5.50);
- assert.strictEqual(yks4.summary.deltaRank, -1);
- assert.strictEqual(yks4.summary.rating?.label, 'Outperformed Curve');
- });
+ assert.strictEqual(yks4.summary.deltaNet, -5.50);
+ assert.strictEqual(yks4.summary.deltaRank, -1);
+ assert.strictEqual(yks4.summary.rating?.label, 'Outperformed Curve');
+ });
- await test('ExamService: calculateKPIs correctly computes aggregate metrics', () => {
- const mockDetails: ExamReportDetail[] = [
- {
+ await test('ExamService: calculateKPIs correctly computes aggregate metrics', () => {
+ const mockDetails: ExamReportDetail[] = [
+ {
+ summary: {
+ id: '1',
+ name: 'Exam 1',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 80,
+ totalWrong: 20,
+ totalEmpty: 20,
+ totalNet: 75.0,
+ totalScore: 75.0,
+ generalRank: 15
+ },
+ subjects: [],
+ hasAnswerKey: false
+ },
+ {
+ summary: {
+ id: '2',
+ name: 'Exam 2',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 90,
+ totalWrong: 15,
+ totalEmpty: 15,
+ totalNet: 85.0,
+ totalScore: 85.0,
+ generalRank: 5
+ },
+ subjects: [],
+ hasAnswerKey: false
+ }
+ ];
+
+ const kpis = ExamService.calculateKPIs(mockDetails);
+ assert.strictEqual(kpis.latestNet, 75.0);
+ assert.strictEqual(kpis.bestNet, 85.0);
+ assert.strictEqual(kpis.averageNet, 80.0);
+ assert.strictEqual(kpis.bestRank, 5);
+ assert.strictEqual(kpis.averageRank, 10);
+ assert.strictEqual(kpis.totalExams, 2);
+ });
+
+ await test('LocalDatabase: saveExamReports and saveTopicWeaknesses persistence', () => {
+ const db = LocalDatabase.getInstance();
+ const testStudentId = `test_student_exam_${Date.now()}`;
+
+ const mockDetail: ExamReportDetail = {
summary: {
- id: '1',
- name: 'Exam 1',
+ id: '9999',
+ name: 'Test Exam',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 80,
@@ -561,216 +617,482 @@ async function runAllTests() {
totalEmpty: 20,
totalNet: 75.0,
totalScore: 75.0,
- generalRank: 15
+ generalRank: 10
},
subjects: [],
hasAnswerKey: false
- },
- {
- summary: {
- id: '2',
- name: 'Exam 2',
- examType: 'TYT',
- totalQuestions: 120,
- totalCorrect: 90,
- totalWrong: 15,
- totalEmpty: 15,
- totalNet: 85.0,
- totalScore: 85.0,
- generalRank: 5
+ };
+
+ db.saveExamReports(testStudentId, [mockDetail]);
+ const examStore = db.getExamReports(testStudentId);
+ assert(examStore !== null);
+ assert(examStore.reports['9999'] !== undefined);
+ assert.strictEqual(examStore.reports['9999'].summary.name, 'Test Exam');
+
+ const mockWeakness = [
+ {
+ examId: '9999',
+ examName: 'Test Exam',
+ subjectName: 'Türkçe',
+ topicName: 'Paragraf',
+ totalCount: 5,
+ correctCount: 2,
+ wrongCount: 3,
+ emptyCount: 0,
+ successRate: 40
+ }
+ ];
+
+ db.saveTopicWeaknesses(testStudentId, '9999', mockWeakness);
+ const retrieved = db.getTopicWeaknesses(testStudentId, '9999');
+ assert(retrieved !== null);
+ assert.strictEqual(retrieved.length, 1);
+ assert.strictEqual(retrieved[0].topicName, 'Paragraf');
+ });
+
+ // 9. PWA & Offline Support Tests
+ await test('PWA: manifest.json is valid and contains standard required PWA fields and icons', () => {
+ 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');
+
+ 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 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, theme toggle, and UI safeguard handlers', () => {
+ 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('themeToggleBtn'), 'pwa.js must wire dark/light theme toggle');
+ 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');
+ });
+
+ // 10. Security, SQLite Migration, Session Store, i18n, and Dark Theme Tests
+ await test('LocalDatabase: saveCredentials encrypts with AES-256-GCM v2 and getRememberedCredentials decrypts', () => {
+ const db = LocalDatabase.getInstance();
+ const testId = 'audit_security_student';
+ const rawPass = 'SuperSecret123!';
+
+ db.saveCredentials(testId, rawPass);
+
+ // Verify stored format in SQLite is encrypted with enc:v2:
+ const row = db
+ .getSqliteDb()
+ .prepare('SELECT remembered_password FROM students WHERE student_id = ?')
+ .get(testId) as { remembered_password: string } | undefined;
+ assert(row && row.remembered_password, 'Credentials row must exist in SQLite');
+ assert(row.remembered_password.startsWith('enc:v2:'), 'Stored password must be encrypted with enc:v2: prefix');
+ assert(!row.remembered_password.includes(rawPass), 'Raw password must not be present in SQLite');
+
+ // Verify retrieval returns decrypted password
+ const retrieved = db.getRememberedCredentials(testId);
+ assert(retrieved !== null, 'Retrieved credentials must not be null');
+ assert.strictEqual(retrieved.password, rawPass, 'Decrypted password must match original raw password');
+
+ db.clearCredentials(testId);
+ });
+
+ await test('LocalDatabase: Zero-Data-Loss Migration from legacy db.json to SQLite (preserving v1 credentials & filtering synthetic test records)', () => {
+ const migJsonPath = path.join(tempDir, 'legacy-db.json');
+ const migDbPath = path.join(tempDir, 'migrated-bekultur.db');
+
+ // Encrypt a password using the legacy v1 scheme (`enc:::` with default legacy key)
+ const legacyKey = crypto.scryptSync('bekultur_secret_key_change_in_production', 'bekultur_credential_salt', 32);
+ const iv = crypto.randomBytes(12);
+ const cipher = crypto.createCipheriv('aes-256-gcm', legacyKey, iv);
+ let encrypted = cipher.update('MyLegacyPortalPassword99', 'utf8', 'hex');
+ encrypted += cipher.final('hex');
+ const authTag = cipher.getAuthTag().toString('hex');
+ const legacyCiphertext = `enc:${iv.toString('hex')}:${authTag}:${encrypted}`;
+
+ const legacyPayload = {
+ students: {
+ '415': {
+ studentId: '415',
+ lastSynced: '2026-10-25T12:00:00.000Z',
+ rememberedCredentials: {
+ studentId: '415',
+ password: legacyCiphertext
+ },
+ assignments: {
+ hw_completed_1: {
+ id: 'hw_completed_1',
+ subject: 'AYT Matematik',
+ type: 'Yayın',
+ unit: 'Türev',
+ topic: 'Limit ve Süreklilik',
+ startDate: '20.10.2026',
+ endDate: '27.10.2026',
+ parsedStartDate: '2026-10-20',
+ parsedEndDate: '2026-10-27',
+ description: '3D AYT Sayfa 100-120',
+ detectedCheckDate: '27 ekim',
+ status: 'completed',
+ completed: true,
+ completedAt: '2026-10-24T18:30:00.000Z',
+ excluded: false
+ },
+ hw_excluded_2: {
+ id: 'hw_excluded_2',
+ subject: 'Biyoloji',
+ type: 'Yayın',
+ unit: '',
+ topic: '',
+ startDate: '20.10.2026',
+ endDate: '27.10.2026',
+ parsedStartDate: '2026-10-20',
+ parsedEndDate: '2026-10-27',
+ description: 'Diğer şube ödevi',
+ detectedCheckDate: null,
+ status: 'active',
+ completed: false,
+ completedAt: null,
+ excluded: true
+ }
+ },
+ syllabus: {
+ weekId: '2026-W43',
+ weekRange: '19.10.2026 - 23.10.2026',
+ lastSynced: '2026-10-25T12:00:00.000Z',
+ selectedStation: 'İst-4',
+ advisoryTeacher: 'CAN TÜRKOĞLU',
+ days: { 1: [], 2: [], 3: [], 4: [], 5: [] }
+ },
+ privateLessons: {
+ lastSynced: '2026-10-25T12:00:00.000Z',
+ detectedAdvisor: 'CAN TÜRKOĞLU',
+ lessons: [
+ {
+ id: 'pl_legacy_1',
+ subject: 'Fizik',
+ teacherName: 'CAN TÜRKOĞLU',
+ teacherPhoto: null,
+ date: '26.10.2026',
+ parsedDate: '2026-10-26',
+ isUpcoming: true
+ }
+ ]
+ },
+ exams: {
+ lastSynced: '2026-10-25T12:00:00.000Z',
+ reports: {
+ '3366': {
+ summary: {
+ id: '3366',
+ name: '12 YKS-04 MF',
+ examType: 'TYT',
+ totalQuestions: 120,
+ totalCorrect: 90,
+ totalWrong: 16,
+ totalEmpty: 14,
+ totalNet: 86.0,
+ totalScore: 86.0,
+ generalRank: 7
+ },
+ subjects: [],
+ hasAnswerKey: true
+ }
+ },
+ topicWeaknesses: {
+ '3366': [
+ {
+ examId: '3366',
+ examName: '12 YKS-04 MF',
+ subjectName: 'Fizik',
+ topicName: 'Optik',
+ totalCount: 3,
+ correctCount: 1,
+ wrongCount: 2,
+ emptyCount: 0,
+ successRate: 33
+ }
+ ]
+ },
+ questions: {
+ '3366_Y': [
+ {
+ questionNumber: 5,
+ correctAnswer: 'D',
+ studentAnswer: 'B',
+ imageUrl: 'https://example.com/q5.png',
+ status: 'wrong',
+ subjectId: '14',
+ subjectName: 'Fizik'
+ }
+ ]
+ }
+ }
+ },
+ test_student_99999: {
+ studentId: 'test_student_99999',
+ lastSynced: null,
+ assignments: {}
+ },
+ audit_security_student: {
+ studentId: 'audit_security_student',
+ lastSynced: null,
+ assignments: {}
+ }
+ }
+ };
+
+ fs.writeFileSync(migJsonPath, JSON.stringify(legacyPayload, null, 2), 'utf-8');
+
+ // Instantiate LocalDatabase pointing to the legacy JSON file
+ const migratedDb = new LocalDatabase(migDbPath, migJsonPath);
+
+ // 1. Verify backup file was created
+ assert(fs.existsSync(`${migJsonPath}.bak`), 'Non-destructive backup legacy-db.json.bak must be created');
+
+ // 2. Verify real student 415 data was 100% preserved
+ const store415 = migratedDb.getStudentStore('415');
+ assert.strictEqual(store415.lastSynced, '2026-10-25T12:00:00.000Z');
+ assert(store415.assignments['hw_completed_1'], 'Completed assignment must be migrated');
+ assert.strictEqual(store415.assignments['hw_completed_1'].completed, true);
+ assert.strictEqual(store415.assignments['hw_completed_1'].completedAt, '2026-10-24T18:30:00.000Z');
+ assert(store415.assignments['hw_excluded_2'], 'Excluded assignment must be migrated');
+ assert.strictEqual(store415.assignments['hw_excluded_2'].excluded, true);
+
+ // 3. Verify legacy v1 encrypted password decrypts seamlessly and was upgraded to v2 at rest
+ const creds415 = migratedDb.getRememberedCredentials('415');
+ assert(creds415 !== null, 'Legacy credentials must be migrated and decryptable');
+ assert.strictEqual(creds415.password, 'MyLegacyPortalPassword99');
+
+ // 4. Verify syllabus, private lessons, and exam reports migrated intact
+ const syl415 = migratedDb.getSyllabus('415');
+ assert.strictEqual(syl415?.selectedStation, 'İst-4');
+ assert.strictEqual( migratedDb.getStudentAdvisoryTeacher('415'), 'CAN TÜRKOĞLU');
+
+ const pl415 = migratedDb.getPrivateLessons('415');
+ assert.strictEqual(pl415?.lessons.length, 1);
+ assert.strictEqual(pl415?.lessons[0].subject, 'Fizik');
+
+ const exams415 = migratedDb.getExamReports('415');
+ assert(exams415?.reports['3366'], 'Exam report 3366 must be migrated');
+ assert.strictEqual(exams415?.reports['3366'].summary.totalNet, 86.0);
+ assert.strictEqual(migratedDb.getTopicWeaknesses('415', '3366')?.[0].topicName, 'Optik');
+ assert.strictEqual(migratedDb.getExamQuestions('415', '3366_Y')?.[0].questionNumber, 5);
+
+ // 5. Verify synthetic test_student_* and audit_* records were filtered out
+ const rowTest = migratedDb
+ .getSqliteDb()
+ .prepare('SELECT student_id FROM students WHERE student_id IN (?, ?)')
+ .all('test_student_99999', 'audit_security_student');
+ assert.strictEqual(rowTest.length, 0, 'Synthetic test_student_* and audit_* records must be skipped during migration');
+
+ // 6. Toggle hw_excluded_2 as completed in SQLite, close DB (simulating container restart), and reopen
+ migratedDb.toggleAssignment('415', 'hw_excluded_2', true);
+ migratedDb.close();
+
+ // Modify legacy db.json (e.g. adding a new student 416 while 415 still has hw_excluded_2 completed: false in JSON)
+ const updatedLegacy = JSON.parse(fs.readFileSync(migJsonPath, 'utf-8'));
+ updatedLegacy.students['416'] = {
+ studentId: '416',
+ lastSynced: '2026-10-26T10:00:00.000Z',
+ assignments: {}
+ };
+ fs.writeFileSync(migJsonPath, JSON.stringify(updatedLegacy, null, 2), 'utf-8');
+
+ const reopenedDb = new LocalDatabase(migDbPath, migJsonPath);
+ const reopened415 = reopenedDb.getStudentStore('415');
+ assert.strictEqual(
+ reopened415.assignments['hw_excluded_2'].completed,
+ true,
+ 'Restart/re-migration must NEVER overwrite newer completed state in SQLite!'
+ );
+ const reopened416 = reopenedDb.getStudentStore('416');
+ assert.strictEqual(reopened416.lastSynced, '2026-10-26T10:00:00.000Z', 'Additive migration must import newly added student 416');
+ reopenedDb.close();
+ });
+
+ await test('SQLiteSessionStore: persists sessions, encrypts portalCookies at rest, and prunes expired sessions', async () => {
+ const db = LocalDatabase.getInstance();
+ const store = new SQLiteSessionStore({ db: db.getSqliteDb(), pruneIntervalMs: 0 });
+
+ const sid = 'test_session_id_123';
+ const sessionData: any = {
+ cookie: {
+ originalMaxAge: 60000,
+ expires: new Date(Date.now() + 60000).toISOString()
},
- subjects: [],
- hasAnswerKey: false
- }
- ];
+ studentId: '415',
+ portalCookies: 'ASP.NET_SessionId=secret_portal_cookie_val; path=/'
+ };
- const kpis = ExamService.calculateKPIs(mockDetails);
- assert.strictEqual(kpis.latestNet, 75.0);
- assert.strictEqual(kpis.bestNet, 85.0);
- assert.strictEqual(kpis.averageNet, 80.0);
- assert.strictEqual(kpis.bestRank, 5);
- assert.strictEqual(kpis.averageRank, 10);
- assert.strictEqual(kpis.totalExams, 2);
- });
+ await new Promise((resolve, reject) => {
+ store.set(sid, sessionData, err => (err ? reject(err) : resolve()));
+ });
- await test('LocalDatabase: saveExamReports and saveTopicWeaknesses persistence', () => {
- const db = LocalDatabase.getInstance();
- const testStudentId = `test_student_exam_${Date.now()}`;
+ // Verify raw SQLite row encrypts portalCookies at rest
+ const rawRow = db
+ .getSqliteDb()
+ .prepare('SELECT sess FROM sessions WHERE sid = ?')
+ .get(sid) as { sess: string } | undefined;
+ assert(rawRow, 'Session row must exist in SQLite');
+ assert(!rawRow.sess.includes('secret_portal_cookie_val'), 'Plaintext portal cookie must NOT appear in SQLite sessions table');
+ assert(rawRow.sess.includes('enc:v2:'), 'Portal cookie must be encrypted with AES-256-GCM v2 in SQLite');
- const mockDetail: ExamReportDetail = {
- summary: {
- id: '9999',
- name: 'Test Exam',
- examType: 'TYT',
- totalQuestions: 120,
- totalCorrect: 80,
- totalWrong: 20,
- totalEmpty: 20,
- totalNet: 75.0,
- totalScore: 75.0,
- generalRank: 10
- },
- subjects: [],
- hasAnswerKey: false
- };
+ // Verify store.get decrypts portalCookies transparently
+ const loaded = await new Promise((resolve, reject) => {
+ store.get(sid, (err, sess) => (err ? reject(err) : resolve(sess)));
+ });
+ assert(loaded, 'Loaded session must not be null');
+ assert.strictEqual(loaded.studentId, '415');
+ assert.strictEqual(loaded.portalCookies, 'ASP.NET_SessionId=secret_portal_cookie_val; path=/');
- db.saveExamReports(testStudentId, [mockDetail]);
- const examStore = db.getExamReports(testStudentId);
- assert(examStore !== null);
- assert(examStore.reports['9999'] !== undefined);
- assert.strictEqual(examStore.reports['9999'].summary.name, 'Test Exam');
+ // Insert an already-expired session and verify pruneExpired removes it
+ const expiredSid = 'expired_session_id_999';
+ db.getSqliteDb()
+ .prepare('INSERT OR REPLACE INTO sessions (sid, sess, expire) VALUES (?, ?, ?)')
+ .run(expiredSid, '{}', Date.now() - 10000);
+ store.pruneExpired();
- // Topic weaknesses
- const mockWeakness = [
- {
- examId: '9999',
- examName: 'Test Exam',
- subjectName: 'Türkçe',
- topicName: 'Paragraf',
- totalCount: 5,
- correctCount: 2,
- wrongCount: 3,
- emptyCount: 0,
- successRate: 40
- }
- ];
+ const expiredLoaded = await new Promise((resolve, reject) => {
+ store.get(expiredSid, (err, sess) => (err ? reject(err) : resolve(sess)));
+ });
+ assert.strictEqual(expiredLoaded, null, 'Expired session must be pruned');
- db.saveTopicWeaknesses(testStudentId, '9999', mockWeakness);
- const retrieved = db.getTopicWeaknesses(testStudentId, '9999');
- assert(retrieved !== null);
- assert.strictEqual(retrieved.length, 1);
- assert.strictEqual(retrieved[0].topicName, 'Paragraf');
- });
-
- // 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}`);
+ // Destroy session
+ await new Promise((resolve, reject) => {
+ store.destroy(sid, err => (err ? reject(err) : resolve()));
+ });
+ const afterDestroy = await new Promise((resolve, reject) => {
+ store.get(sid, (err, sess) => (err ? reject(err) : resolve(sess)));
+ });
+ assert.strictEqual(afterDestroy, null, 'Destroyed session must return null');
});
- });
- 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');
+ await test('i18n Service: defaults to Turkish (tr) with official E-Kültür terminology parity and supports English (en)', () => {
+ assert.strictEqual(normalizeLocale(undefined), 'tr', 'Default locale must be Turkish (tr)');
+ assert.strictEqual(normalizeLocale('tr'), 'tr');
+ assert.strictEqual(normalizeLocale('en'), 'en');
+ assert.strictEqual(normalizeLocale('fr'), 'tr', 'Unsupported locale must fall back to Turkish (tr)');
- 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');
- });
+ // Verify Official E-Kültür Turkish terminology
+ assert.strictEqual(translate('tr', 'login.studentIdLabel'), 'Öğrenci ID');
+ assert.strictEqual(translate('tr', 'login.passwordLabel'), 'Parola');
+ assert.strictEqual(translate('tr', 'login.submit'), 'Giriş Yap');
+ assert.strictEqual(translate('tr', 'nav.homework'), 'Ödevler');
+ assert.strictEqual(translate('tr', 'nav.syllabus'), 'Ders Programı');
+ assert.strictEqual(translate('tr', 'nav.privateLessons'), 'Özel Ders');
+ assert.strictEqual(translate('tr', 'nav.exams'), 'Sınav Raporları');
+ assert.strictEqual(translate('tr', 'privateLessons.requestTitle'), 'Özel Ders İstek');
+ assert(translate('tr', 'exams.subtabBreakdown').includes('Sınav Karne'));
+ assert(translate('tr', 'exams.subtabWeakness').includes('Yanlış Konular'));
+ assert.strictEqual(translate('tr', 'exams.answerKey'), 'Cevap Anahtarı');
- 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. Security & Hardening Tests
- await test('LocalDatabase: saveCredentials encrypts with AES-256-GCM and getRememberedCredentials decrypts', () => {
- const fs = require('fs');
- const path = require('path');
- const db = LocalDatabase.getInstance();
- const dbFile = path.resolve(process.cwd(), 'data', 'db.json');
- const testId = 'audit_security_student';
- const rawPass = 'SuperSecret123!';
-
- db.saveCredentials(testId, rawPass);
-
- // Verify stored format on disk is encrypted
- const onDiskRaw = JSON.parse(fs.readFileSync(dbFile, 'utf-8'));
- const storedCred = onDiskRaw.students[testId]?.rememberedCredentials;
- assert(storedCred, 'Credentials must be saved');
- assert(storedCred.password.startsWith('enc:'), 'Stored password must be encrypted with enc: prefix');
- assert(!storedCred.password.includes(rawPass), 'Raw password must not be present in database file');
-
- // Verify retrieval returns decrypted password
- const retrieved = db.getRememberedCredentials(testId);
- assert(retrieved !== null, 'Retrieved credentials must not be null');
- assert.strictEqual(retrieved.password, rawPass, 'Decrypted password must match original raw password');
-
- // Clean up
- db.clearCredentials(testId);
- });
-
- await test('LocalDatabase: saveExamQuestions and getExamQuestions persists question review cache', () => {
- const db = LocalDatabase.getInstance();
- const testId = 'audit_exam_student';
- const examKey = '3366_Y';
- const sampleQuestions = [
- {
- questionNumber: 1,
- correctAnswer: 'A',
- studentAnswer: 'C',
- imageUrl: 'https://panel.example.com/soru/1.png',
- status: 'wrong' as const,
- subjectId: '10',
- subjectName: 'Türkçe'
- }
- ];
-
- db.saveExamQuestions(testId, examKey, sampleQuestions);
- const cached = db.getExamQuestions(testId, examKey);
- assert(cached !== null, 'Cached questions should exist');
- assert.strictEqual(cached.length, 1);
- assert.strictEqual(cached[0].questionNumber, 1);
- assert.strictEqual(cached[0].correctAnswer, 'A');
- });
-
- await test('PWA: sw.js contains route-specific offline fallbacks and ignoreSearch', () => {
- const fs = require('fs');
- const path = require('path');
- const swPath = path.resolve(__dirname, '../public/sw.js');
- const swContent = fs.readFileSync(swPath, 'utf-8');
-
- assert(swContent.includes('ignoreSearch: true'), 'sw.js must match cache ignoring query strings');
- assert(swContent.includes("url.pathname.startsWith('/exams')"), 'sw.js must have route fallback for exams');
- assert(swContent.includes("url.pathname.startsWith('/syllabus')"), 'sw.js must have route fallback for syllabus');
- assert(swContent.includes("url.pathname.startsWith('/private-lessons')"), 'sw.js must have route fallback for private lessons');
- });
-
- // 7. Optional Live Portal Test (via environment variables only)
- const testStudentId = process.env.TEST_STUDENT_ID;
- const testPassword = process.env.TEST_PASSWORD;
-
- if (testStudentId && testPassword) {
- await test('ScraperService: Live portal authentication and scraping', async () => {
- const loginRes = await ScraperService.login(testStudentId, testPassword);
- assert.strictEqual(loginRes.success, true, `Login failed: ${loginRes.error}`);
-
- const scrapeRes = await ScraperService.scrapePage(loginRes.cookies, 1, testStudentId);
- assert(scrapeRes.assignments.length > 0, 'Page 1 must contain homework cards');
+ // Verify English translation & parameter interpolation
+ assert.strictEqual(translate('en', 'nav.homework'), 'Homework');
+ assert.strictEqual(translate('en', 'exams.kpiAcrossExams', { count: 4 }), 'Across all 4 exams');
+ assert.strictEqual(translate('tr', 'exams.kpiAcrossExams', { count: 4 }), 'Toplam 4 sınav içinde');
});
- } else {
- console.log(' - Live portal test skipped (set TEST_STUDENT_ID and TEST_PASSWORD to run)');
+
+ await test('UI & Dark Theme: header.ejs and style.css implement modern color-scheme, theme toggle, and language switcher', () => {
+ const headerPath = path.resolve(__dirname, '../views/partials/header.ejs');
+ const cssPath = path.resolve(__dirname, '../public/css/style.css');
+
+ const headerContent = fs.readFileSync(headerPath, 'utf-8');
+ const cssContent = fs.readFileSync(cssPath, 'utf-8');
+
+ assert(headerContent.includes('meta name="color-scheme" content="light dark"'), 'header.ejs must declare color-scheme meta tag');
+ assert(headerContent.includes('id="themeToggleBtn"'), 'header.ejs must include themeToggleBtn');
+ assert(headerContent.includes('class="lang-switcher"'), 'header.ejs must include TR | EN language switcher');
+ assert(headerContent.includes('window.BeKulturDict'), 'header.ejs must expose client-side i18n dictionary');
+
+ assert(cssContent.includes('color-scheme: light dark'), 'style.css must set color-scheme: light dark on :root');
+ assert(cssContent.includes('@media (prefers-color-scheme: dark)'), 'style.css must support system dark mode preference');
+ assert(cssContent.includes(':root[data-theme="dark"]'), 'style.css must support explicit dark theme override');
+ });
+
+ await test('LocalDatabase: saveExamQuestions and getExamQuestions persists question review cache', () => {
+ const db = LocalDatabase.getInstance();
+ const testId = 'audit_exam_student';
+ const examKey = '3366_Y';
+ const sampleQuestions = [
+ {
+ questionNumber: 1,
+ correctAnswer: 'A',
+ studentAnswer: 'C',
+ imageUrl: 'https://panel.example.com/soru/1.png',
+ status: 'wrong' as const,
+ subjectId: '10',
+ subjectName: 'Türkçe'
+ }
+ ];
+
+ db.saveExamQuestions(testId, examKey, sampleQuestions);
+ const cached = db.getExamQuestions(testId, examKey);
+ assert(cached !== null, 'Cached questions should exist');
+ assert.strictEqual(cached.length, 1);
+ assert.strictEqual(cached[0].questionNumber, 1);
+ assert.strictEqual(cached[0].correctAnswer, 'A');
+ });
+
+ await test('PWA: sw.js contains route-specific offline fallbacks and ignoreSearch', () => {
+ const swPath = path.resolve(__dirname, '../public/sw.js');
+ const swContent = fs.readFileSync(swPath, 'utf-8');
+
+ assert(swContent.includes('ignoreSearch: true'), 'sw.js must match cache ignoring query strings');
+ assert(swContent.includes("url.pathname.startsWith('/exams')"), 'sw.js must have route fallback for exams');
+ assert(swContent.includes("url.pathname.startsWith('/syllabus')"), 'sw.js must have route fallback for syllabus');
+ assert(swContent.includes("url.pathname.startsWith('/private-lessons')"), 'sw.js must have route fallback for private lessons');
+ });
+
+ // Optional Live Portal Test (via environment variables only)
+ const testStudentId = process.env.TEST_STUDENT_ID;
+ const testPassword = process.env.TEST_PASSWORD;
+
+ if (testStudentId && testPassword) {
+ await test('ScraperService: Live portal authentication and scraping', async () => {
+ const loginRes = await ScraperService.login(testStudentId, testPassword);
+ assert.strictEqual(loginRes.success, true, `Login failed: ${loginRes.error}`);
+
+ const scrapeRes = await ScraperService.scrapePage(loginRes.cookies, 1, testStudentId);
+ assert(scrapeRes.assignments.length > 0, 'Page 1 must contain homework cards');
+ });
+ } else {
+ console.log(' - Live portal test skipped (set TEST_STUDENT_ID and TEST_PASSWORD to run)');
+ }
+ } finally {
+ try {
+ LocalDatabase.getInstance().close();
+ } catch {
+ // ignore
+ }
+ try {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ } catch {
+ // ignore
+ }
}
console.log('\n--------------------------------------------------------');
diff --git a/views/dashboard.ejs b/views/dashboard.ejs
index c0e9019..78f3a9e 100644
--- a/views/dashboard.ejs
+++ b/views/dashboard.ejs
@@ -4,15 +4,15 @@
-
Homework
+
<%= t('dashboard.title') %>
- Student #<%= studentId %>
+ <%= t('dashboard.studentLabel') %> #<%= studentId %>
•
<% if (lastSynced) { %>
- Last synced: <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %>
+ <%= t('dashboard.lastSynced') %> <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %>
<% } else { %>
- Not synced
+ <%= t('dashboard.notSynced') %>
<% } %>
@@ -20,10 +20,10 @@
@@ -33,49 +33,49 @@
-
Completion
+
<%= t('dashboard.statCompletion') %>
<%= stats.completionRate %>%
-
<%= stats.completed %> / <%= stats.total %> done
+
<%= stats.completed %> / <%= stats.total %> <%= t('dashboard.statDoneUnit') %>
-
Active
+
<%= t('dashboard.statActive') %>
<%= stats.active %>
-
In progress
+
<%= t('dashboard.statActiveSub') %>
-
Checked Next Week
+
<%= t('dashboard.statNextWeek') %>
<%= stats.checkedNextWeek %>
-
Due or checked next week
+
<%= t('dashboard.statNextWeekSub') %>
-
Due Soon
+
<%= t('dashboard.statDueSoon') %>
<%= stats.dueSoon %>
-
Within 3 days
+
<%= t('dashboard.statDueSoonSub') %>
-
Overdue
+
<%= t('dashboard.statOverdue') %>
<%= stats.overdue %>
-
Past deadline
+
<%= t('dashboard.statOverdueSub') %>
-
Total
+
<%= t('dashboard.statTotal') %>
<%= stats.total %>
-
All assignments
+
<%= t('dashboard.statTotalSub') %>
@@ -99,25 +99,25 @@
- Showing <%= assignments.length %> assignments
+ <%= t('dashboard.showingCount', { count: assignments.length }) %>
-
No matching assignments found.
-
+
<%= t('dashboard.noResults') %>
+
@@ -187,39 +187,39 @@
<% if (item.detectedCheckDate) { %>
- Kontrol: <%= item.detectedCheckDate %>
+ <%= t('dashboard.checkDateBadge') %> <%= item.detectedCheckDate %>
<% } %>
<% if (item.excluded) { %>
- Excluded
+ <%= t('dashboard.badgeExcluded') %>
<% } else if (item.completed) { %>
- Done
+ <%= t('dashboard.badgeCompleted') %>
<% } else if (item.status === 'next-week') { %>
- Next Week
+ <%= t('dashboard.badgeNextWeek') %>
<% } else if (item.status === 'due-soon') { %>
- Due Soon
+ <%= t('dashboard.badgeDueSoon') %>
<% } else if (item.status === 'overdue') { %>
- Overdue
+ <%= t('dashboard.badgeOverdue') %>
<% } else { %>
- Active
+ <%= t('dashboard.badgeActive') %>
<% } %>
<% if (item.unit || item.topic) { %>
- <% if (item.unit) { %>Ünite: <%= item.unit %><% } %>
- <% if (item.topic) { %>Konu: <%= item.topic %><% } %>
+ <% if (item.unit) { %><%= t('dashboard.unitLabel') %> <%= item.unit %><% } %>
+ <% if (item.topic) { %><%= t('dashboard.topicLabel') %> <%= item.topic %><% } %>
<% } %>
@@ -228,13 +228,13 @@