init
This commit is contained in:
commit
5577214005
22 changed files with 4997 additions and 0 deletions
7
.dockerignore
Normal file
7
.dockerignore
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
node_modules
|
||||
dist
|
||||
.git
|
||||
.env
|
||||
*.log
|
||||
data/*.json
|
||||
!data/.gitkeep
|
||||
4
.env.example
Normal file
4
.env.example
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
PORT=3000
|
||||
SESSION_SECRET=bekultur_secret_session_key_change_in_production
|
||||
# Optional: Cloudflare Tunnel Token for exposing via Cloudflare
|
||||
CLOUDFLARE_TUNNEL_TOKEN=
|
||||
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
data/*.json
|
||||
!data/.gitkeep
|
||||
*.log
|
||||
.DS_Store
|
||||
41
Dockerfile
Normal file
41
Dockerfile
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# ----------------------------------------------------
|
||||
# Stage 1: Build TypeScript Application
|
||||
# ----------------------------------------------------
|
||||
FROM node:18-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
|
||||
COPY tsconfig.json ./
|
||||
COPY src/ ./src/
|
||||
COPY views/ ./views/
|
||||
COPY public/ ./public/
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# ----------------------------------------------------
|
||||
# Stage 2: Production Runtime
|
||||
# ----------------------------------------------------
|
||||
FROM node:18-alpine AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
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/dist ./dist
|
||||
COPY views/ ./views
|
||||
COPY public/ ./public
|
||||
|
||||
# Ensure local data directory exists for persistent JSON db
|
||||
RUN mkdir -p /app/data
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "dist/server.js"]
|
||||
29
README.md
Normal file
29
README.md
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# BeKultur
|
||||
|
||||
A simple, fast homework scraper and tracker for Kültür Okulları students.
|
||||
|
||||
It logs into your portal, grabs assigned homework, highlights what's due or checked next week, and lets you check off completed assignments in a local JSON database.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Install & Run
|
||||
```bash
|
||||
npm install
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Access at `http://localhost:3000`.
|
||||
|
||||
### 2. Run with Docker
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **No translated content**: Keeps all Turkish course names and descriptions exactly as written.
|
||||
- **Local JSON DB**: Checkboxes are stored in `data/db.json` and persist across refreshes.
|
||||
- **Next Week Insights**: Flags assignments that teachers have marked to check next week.
|
||||
- **Search & Filters**: Filter by status (`Active`, `Next Week`, `Due Soon`, `Completed`, `Overdue`) or search for book names.
|
||||
- **Fast History Sync**: Scrapes recent assignments on login, with a button to sync full history.
|
||||
0
data/.gitkeep
Normal file
0
data/.gitkeep
Normal file
33
docker-compose.yml
Normal file
33
docker-compose.yml
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: bekultur
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- PORT=3000
|
||||
- SESSION_SECRET=${SESSION_SECRET:-bekultur_default_secret_key_change_me}
|
||||
- NODE_ENV=production
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
networks:
|
||||
- bekultur-network
|
||||
|
||||
tunnel:
|
||||
image: cloudflare/cloudflared:latest
|
||||
container_name: bekultur-tunnel
|
||||
restart: unless-stopped
|
||||
command: tunnel run
|
||||
environment:
|
||||
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}
|
||||
depends_on:
|
||||
- app
|
||||
networks:
|
||||
- bekultur-network
|
||||
|
||||
networks:
|
||||
bekultur-network:
|
||||
driver: bridge
|
||||
2114
package-lock.json
generated
Normal file
2114
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
40
package.json
Normal file
40
package.json
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"name": "bekultur",
|
||||
"version": "1.0.0",
|
||||
"description": "BeKultur (Better E-Kultur) - Smart homework tracker for Kultur Okullari",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
"build": "tsc && npm run copy-assets",
|
||||
"copy-assets": "node -e \"const fs=require('fs'); fs.cpSync('views', 'dist/views', {recursive: true}); fs.cpSync('public', 'dist/public', {recursive: true});\"",
|
||||
"start": "node dist/server.js",
|
||||
"dev": "ts-node-dev --respawn --transpile-only src/server.ts",
|
||||
"test": "ts-node test/run-tests.ts"
|
||||
},
|
||||
"keywords": [
|
||||
"bekultur",
|
||||
"kultur-okullari",
|
||||
"homework-tracker",
|
||||
"scraper"
|
||||
],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"axios": "^1.7.7",
|
||||
"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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cookie-parser": "^1.4.7",
|
||||
"@types/ejs": "^3.1.5",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/express-session": "^1.18.0",
|
||||
"@types/node": "^20.14.9",
|
||||
"ts-node": "^10.9.2",
|
||||
"ts-node-dev": "^2.0.0",
|
||||
"typescript": "^5.5.2"
|
||||
}
|
||||
}
|
||||
692
public/css/style.css
Normal file
692
public/css/style.css
Normal file
|
|
@ -0,0 +1,692 @@
|
|||
:root {
|
||||
--primary: #2563eb;
|
||||
--primary-hover: #1d4ed8;
|
||||
--text-main: #1e293b;
|
||||
--text-muted: #64748b;
|
||||
--text-light: #94a3b8;
|
||||
--bg-page: #f8fafc;
|
||||
--bg-card: #ffffff;
|
||||
--border: #e2e8f0;
|
||||
|
||||
--success: #16a34a;
|
||||
--warning: #d97706;
|
||||
--urgent: #ea580c;
|
||||
--danger: #dc2626;
|
||||
|
||||
--radius: 6px;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
background-color: var(--bg-page);
|
||||
color: var(--text-main);
|
||||
line-height: 1.45;
|
||||
font-size: 14px;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.9em;
|
||||
background: #f1f5f9;
|
||||
padding: 2px 4px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
/* ---------------- Header ---------------- */
|
||||
.app-header {
|
||||
background: var(--bg-card);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.header-container {
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
padding: 10px 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.brand-link {
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.brand-name {
|
||||
font-size: 1.15rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.user-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.user-id {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* ---------------- Main Layout ---------------- */
|
||||
.main-content {
|
||||
flex: 1;
|
||||
max-width: 1080px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 18px 16px;
|
||||
}
|
||||
|
||||
/* ---------------- Buttons ---------------- */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 6px 14px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid transparent;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background-color: var(--primary-hover);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: white;
|
||||
border-color: var(--border);
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background-color: #f1f5f9;
|
||||
}
|
||||
|
||||
.btn-outline {
|
||||
background: transparent;
|
||||
border-color: var(--border);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.btn-outline:hover {
|
||||
background: #f1f5f9;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 5px 10px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.btn-block {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---------------- Login ---------------- */
|
||||
.auth-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding-top: 60px;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 28px 24px;
|
||||
max-width: 360px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.auth-title {
|
||||
font-size: 1.3rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.auth-subtitle {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
font-size: 0.9rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: white;
|
||||
}
|
||||
|
||||
.form-control:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.form-row-between {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.checkbox-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------------- Alerts ---------------- */
|
||||
.alert {
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius);
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.alert-danger {
|
||||
background: #fef2f2;
|
||||
color: #991b1b;
|
||||
border: 1px solid #fecaca;
|
||||
}
|
||||
|
||||
.alert-info {
|
||||
background: #eff6ff;
|
||||
color: #1e40af;
|
||||
border: 1px solid #bfdbfe;
|
||||
}
|
||||
|
||||
/* ---------------- Dashboard Top Bar ---------------- */
|
||||
.dashboard-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.dashboard-title {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.dashboard-subtitle {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.dot-separator {
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
.sync-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* ---------------- Stats Grid ---------------- */
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||
gap: 10px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
.stat-highlight {
|
||||
border-left: 3px solid var(--warning);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.45rem;
|
||||
font-weight: 700;
|
||||
margin: 4px 0 2px;
|
||||
}
|
||||
|
||||
.stat-subtext {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.progress-bar-container {
|
||||
background: #e2e8f0;
|
||||
height: 4px;
|
||||
border-radius: 9999px;
|
||||
overflow: hidden;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.progress-bar-fill {
|
||||
background: var(--success);
|
||||
height: 100%;
|
||||
border-radius: 9999px;
|
||||
transition: width 0.3s;
|
||||
}
|
||||
|
||||
/* ---------------- Subjects ---------------- */
|
||||
.section-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
padding: 10px 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.cursor-pointer {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toggle-indicator {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.subject-breakdown-body {
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
.subject-breakdown-body.collapsed {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.subject-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.subject-item {
|
||||
background: #f8fafc;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.subject-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 4px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.subject-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.subject-fraction {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.subject-bar {
|
||||
background: #e2e8f0;
|
||||
height: 4px;
|
||||
border-radius: 9999px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.subject-bar-fill {
|
||||
background: var(--primary);
|
||||
height: 100%;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
/* ---------------- Toolbar ---------------- */
|
||||
.toolbar-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.filter-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.tab-btn {
|
||||
background: #f1f5f9;
|
||||
border: 1px solid transparent;
|
||||
color: var(--text-muted);
|
||||
padding: 4px 10px;
|
||||
border-radius: var(--radius);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab-btn:hover {
|
||||
background: #e2e8f0;
|
||||
}
|
||||
|
||||
.tab-btn.active {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.search-box {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
padding: 6px 26px 6px 10px;
|
||||
font-size: 0.85rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.search-clear {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1rem;
|
||||
color: var(--text-light);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.form-select {
|
||||
padding: 6px 10px;
|
||||
font-size: 0.85rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.list-meta {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
/* ---------------- Cards ---------------- */
|
||||
.assignment-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.assignment-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 14px;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.assignment-card.status-next-week:not(.is-completed) {
|
||||
border-left: 3px solid var(--warning);
|
||||
}
|
||||
|
||||
.assignment-card.status-due-soon:not(.is-completed) {
|
||||
border-left: 3px solid var(--urgent);
|
||||
}
|
||||
|
||||
.assignment-card.status-overdue:not(.is-completed) {
|
||||
border-left: 3px solid var(--danger);
|
||||
}
|
||||
|
||||
.assignment-card.status-active:not(.is-completed) {
|
||||
border-left: 3px solid #38bdf8;
|
||||
}
|
||||
|
||||
.assignment-card.is-completed {
|
||||
border-left: 3px solid var(--success);
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.assignment-card.is-completed .card-description {
|
||||
text-decoration: line-through;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.card-checkbox-col {
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.assignment-toggle {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.card-content-col {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.card-top-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.card-subject-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.card-subject {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.card-badges {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 0.725rem;
|
||||
font-weight: 600;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.badge-type {
|
||||
background: #f1f5f9;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.badge-active {
|
||||
background: #e0f2fe;
|
||||
color: #0369a1;
|
||||
}
|
||||
|
||||
.badge-next-week {
|
||||
background: #fef3c7;
|
||||
color: #b45309;
|
||||
}
|
||||
|
||||
.badge-due-soon {
|
||||
background: #ffedd5;
|
||||
color: #c2410c;
|
||||
}
|
||||
|
||||
.badge-overdue {
|
||||
background: #fee2e2;
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.badge-completed {
|
||||
background: #dcfce7;
|
||||
color: #15803d;
|
||||
}
|
||||
|
||||
.badge-check-date {
|
||||
background: #f3e8ff;
|
||||
color: #7e22ce;
|
||||
border: 1px solid #e9d5ff;
|
||||
}
|
||||
|
||||
.card-sub-meta {
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-muted);
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.card-description {
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.45;
|
||||
color: #1e293b;
|
||||
white-space: pre-line;
|
||||
word-break: break-word;
|
||||
background: #f8fafc;
|
||||
padding: 6px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.card-footer-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.card-timestamps {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.card-hash {
|
||||
font-family: Menlo, Monaco, monospace;
|
||||
font-size: 0.7rem;
|
||||
color: var(--text-light);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.app-footer {
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 12px 16px;
|
||||
text-align: center;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-light);
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.dashboard-topbar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.filter-controls {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
303
public/js/app.js
Normal file
303
public/js/app.js
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const assignmentList = document.getElementById('assignmentList');
|
||||
const searchInput = document.getElementById('searchInput');
|
||||
const searchClear = document.getElementById('searchClear');
|
||||
const subjectSelect = document.getElementById('subjectSelect');
|
||||
const filterTabs = document.getElementById('filterTabs');
|
||||
const filteredCountText = document.getElementById('filteredCountText');
|
||||
const noResults = document.getElementById('noResults');
|
||||
const btnResetFilters = document.getElementById('btnResetFilters');
|
||||
const syncAlert = document.getElementById('syncAlert');
|
||||
const btnSyncRecent = document.getElementById('btnSyncRecent');
|
||||
const btnSyncAll = document.getElementById('btnSyncAll');
|
||||
const subjectToggleHeader = document.getElementById('subjectToggleHeader');
|
||||
const subjectBreakdownBody = document.getElementById('subjectBreakdownBody');
|
||||
const subjectToggleIcon = document.getElementById('subjectToggleIcon');
|
||||
|
||||
let currentTab = 'all';
|
||||
let currentSearch = '';
|
||||
let currentSubject = '';
|
||||
|
||||
// Checkbox toggle
|
||||
if (assignmentList) {
|
||||
assignmentList.addEventListener('change', async (e) => {
|
||||
const target = e.target;
|
||||
if (!target.classList.contains('assignment-toggle')) return;
|
||||
|
||||
const assignmentId = target.dataset.id;
|
||||
const isChecked = target.checked;
|
||||
const card = target.closest('.assignment-card');
|
||||
if (!card) return;
|
||||
|
||||
if (isChecked) {
|
||||
card.classList.add('is-completed');
|
||||
card.dataset.completed = 'true';
|
||||
updateCardBadge(card, 'completed');
|
||||
} else {
|
||||
card.classList.remove('is-completed');
|
||||
card.dataset.completed = 'false';
|
||||
updateCardBadge(card, card.dataset.status);
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/toggle', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assignmentId, completed: isChecked })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.stats) {
|
||||
updateStatsUI(data.stats);
|
||||
applyFilters();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to toggle assignment:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateCardBadge(card, status) {
|
||||
const badgesContainer = card.querySelector('.card-badges');
|
||||
if (!badgesContainer) return;
|
||||
|
||||
let existingStatusBadge = badgesContainer.querySelector(
|
||||
'.badge-completed, .badge-next-week, .badge-due-soon, .badge-overdue, .badge-active'
|
||||
);
|
||||
|
||||
if (existingStatusBadge) {
|
||||
if (status === 'completed') {
|
||||
existingStatusBadge.className = 'badge badge-completed';
|
||||
existingStatusBadge.textContent = 'Done';
|
||||
} else {
|
||||
const orig = card.dataset.status;
|
||||
if (orig === 'next-week') {
|
||||
existingStatusBadge.className = 'badge badge-next-week';
|
||||
existingStatusBadge.textContent = 'Next Week';
|
||||
} else if (orig === 'due-soon') {
|
||||
existingStatusBadge.className = 'badge badge-due-soon';
|
||||
existingStatusBadge.textContent = 'Due Soon';
|
||||
} else if (orig === 'overdue') {
|
||||
existingStatusBadge.className = 'badge badge-overdue';
|
||||
existingStatusBadge.textContent = 'Overdue';
|
||||
} else {
|
||||
existingStatusBadge.className = 'badge badge-active';
|
||||
existingStatusBadge.textContent = 'Active';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateStatsUI(stats) {
|
||||
const statCompRate = document.getElementById('statCompletionRate');
|
||||
const statCompFrac = document.getElementById('statCompletionFraction');
|
||||
const progressBar = document.getElementById('progressBarFill');
|
||||
const statActive = document.getElementById('statActiveCount');
|
||||
const statNextWeek = document.getElementById('statNextWeekCount');
|
||||
const statDueSoon = document.getElementById('statDueSoonCount');
|
||||
const statOverdue = document.getElementById('statOverdueCount');
|
||||
const statTotal = document.getElementById('statTotalCount');
|
||||
|
||||
if (statCompRate) statCompRate.textContent = `${stats.completionRate}%`;
|
||||
if (statCompFrac) statCompFrac.textContent = `${stats.completed} / ${stats.total} done`;
|
||||
if (progressBar) progressBar.style.width = `${stats.completionRate}%`;
|
||||
if (statActive) statActive.textContent = stats.active;
|
||||
if (statNextWeek) statNextWeek.textContent = stats.checkedNextWeek;
|
||||
if (statDueSoon) statDueSoon.textContent = stats.dueSoon;
|
||||
if (statOverdue) statOverdue.textContent = stats.overdue;
|
||||
if (statTotal) statTotal.textContent = stats.total;
|
||||
|
||||
const tabAll = document.getElementById('tabAllCount');
|
||||
const tabNext = document.getElementById('tabNextWeekCount');
|
||||
const tabAct = document.getElementById('tabActiveCount');
|
||||
const tabDue = document.getElementById('tabDueSoonCount');
|
||||
const tabComp = document.getElementById('tabCompletedCount');
|
||||
const tabOver = document.getElementById('tabOverdueCount');
|
||||
|
||||
if (tabAll) tabAll.textContent = stats.total;
|
||||
if (tabNext) tabNext.textContent = stats.checkedNextWeek;
|
||||
if (tabAct) tabAct.textContent = stats.active;
|
||||
if (tabDue) tabDue.textContent = stats.dueSoon;
|
||||
if (tabComp) tabComp.textContent = stats.completed;
|
||||
if (tabOver) tabOver.textContent = stats.overdue;
|
||||
|
||||
if (stats.bySubject) {
|
||||
Object.values(stats.bySubject).forEach(s => {
|
||||
const item = document.querySelector(`.subject-item[data-subject="${CSS.escape(s.subject)}"]`);
|
||||
if (item) {
|
||||
const frac = item.querySelector('.subject-fraction');
|
||||
const fill = item.querySelector('.subject-bar-fill');
|
||||
if (frac) frac.textContent = `${s.completed}/${s.total} (${s.percentage}%)`;
|
||||
if (fill) fill.style.width = `${s.percentage}%`;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Filter tabs
|
||||
if (filterTabs) {
|
||||
filterTabs.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('.tab-btn');
|
||||
if (!btn) return;
|
||||
filterTabs.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentTab = btn.dataset.filter || 'all';
|
||||
applyFilters();
|
||||
});
|
||||
}
|
||||
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', (e) => {
|
||||
currentSearch = e.target.value.trim().toLowerCase();
|
||||
if (searchClear) searchClear.classList.toggle('hidden', currentSearch.length === 0);
|
||||
applyFilters();
|
||||
});
|
||||
}
|
||||
|
||||
if (searchClear) {
|
||||
searchClear.addEventListener('click', () => {
|
||||
searchInput.value = '';
|
||||
currentSearch = '';
|
||||
searchClear.classList.add('hidden');
|
||||
applyFilters();
|
||||
});
|
||||
}
|
||||
|
||||
if (subjectSelect) {
|
||||
subjectSelect.addEventListener('change', (e) => {
|
||||
currentSubject = e.target.value;
|
||||
applyFilters();
|
||||
});
|
||||
}
|
||||
|
||||
if (btnResetFilters) {
|
||||
btnResetFilters.addEventListener('click', () => {
|
||||
currentTab = 'all';
|
||||
currentSearch = '';
|
||||
currentSubject = '';
|
||||
if (searchInput) searchInput.value = '';
|
||||
if (searchClear) searchClear.classList.add('hidden');
|
||||
if (subjectSelect) subjectSelect.value = '';
|
||||
if (filterTabs) {
|
||||
filterTabs.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
const allTab = filterTabs.querySelector('[data-filter="all"]');
|
||||
if (allTab) allTab.classList.add('active');
|
||||
}
|
||||
applyFilters();
|
||||
});
|
||||
}
|
||||
|
||||
function applyFilters() {
|
||||
if (!assignmentList) return;
|
||||
const cards = assignmentList.querySelectorAll('.assignment-card');
|
||||
let visibleCount = 0;
|
||||
|
||||
cards.forEach(card => {
|
||||
const status = card.dataset.status;
|
||||
const isCompleted = card.dataset.completed === 'true';
|
||||
const subject = card.dataset.subject;
|
||||
const searchText = card.dataset.search || '';
|
||||
|
||||
let matchesTab = true;
|
||||
if (currentTab === 'completed') {
|
||||
matchesTab = isCompleted;
|
||||
} else if (currentTab === 'active') {
|
||||
matchesTab = !isCompleted && (status === 'active' || status === 'next-week' || status === 'due-soon');
|
||||
} else if (currentTab === 'next-week') {
|
||||
matchesTab = !isCompleted && status === 'next-week';
|
||||
} else if (currentTab === 'due-soon') {
|
||||
matchesTab = !isCompleted && status === 'due-soon';
|
||||
} else if (currentTab === 'overdue') {
|
||||
matchesTab = !isCompleted && status === 'overdue';
|
||||
}
|
||||
|
||||
let matchesSubject = true;
|
||||
if (currentSubject) {
|
||||
matchesSubject = (subject === currentSubject);
|
||||
}
|
||||
|
||||
let matchesSearch = true;
|
||||
if (currentSearch) {
|
||||
matchesSearch = searchText.includes(currentSearch);
|
||||
}
|
||||
|
||||
if (matchesTab && matchesSubject && matchesSearch) {
|
||||
card.style.display = 'flex';
|
||||
visibleCount++;
|
||||
} else {
|
||||
card.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
if (filteredCountText) {
|
||||
filteredCountText.textContent = `Showing ${visibleCount} assignments`;
|
||||
}
|
||||
|
||||
if (noResults) {
|
||||
noResults.classList.toggle('hidden', visibleCount > 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Sync actions
|
||||
if (btnSyncRecent) {
|
||||
btnSyncRecent.addEventListener('click', async () => {
|
||||
btnSyncRecent.disabled = true;
|
||||
btnSyncRecent.textContent = 'Syncing...';
|
||||
showAlert('Fetching recent assignments...', 'info');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/sync', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
showAlert(`Sync failed: ${data.error}`, 'danger');
|
||||
btnSyncRecent.disabled = false;
|
||||
btnSyncRecent.textContent = 'Sync Recent';
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Network error while syncing.', 'danger');
|
||||
btnSyncRecent.disabled = false;
|
||||
btnSyncRecent.textContent = 'Sync Recent';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (btnSyncAll) {
|
||||
btnSyncAll.addEventListener('click', async () => {
|
||||
btnSyncAll.disabled = true;
|
||||
btnSyncAll.textContent = 'Syncing all...';
|
||||
showAlert('Syncing full history from portal...', 'info');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/sync-all', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
showAlert(`Sync all failed: ${data.error}`, 'danger');
|
||||
btnSyncAll.disabled = false;
|
||||
btnSyncAll.textContent = 'Sync Full History';
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Network error while syncing full history.', 'danger');
|
||||
btnSyncAll.disabled = false;
|
||||
btnSyncAll.textContent = 'Sync Full History';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showAlert(msg, type = 'info') {
|
||||
if (!syncAlert) return;
|
||||
syncAlert.className = `alert alert-${type}`;
|
||||
syncAlert.textContent = msg;
|
||||
syncAlert.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// Subject collapse
|
||||
if (subjectToggleHeader && subjectBreakdownBody && subjectToggleIcon) {
|
||||
subjectToggleHeader.addEventListener('click', () => {
|
||||
const isHidden = subjectBreakdownBody.classList.toggle('collapsed');
|
||||
subjectToggleIcon.textContent = isHidden ? '▶' : '▼';
|
||||
});
|
||||
}
|
||||
});
|
||||
388
src/server.ts
Normal file
388
src/server.ts
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import session from 'express-session';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import path from 'path';
|
||||
import dotenv from 'dotenv';
|
||||
import { ScraperService } from './services/scraper';
|
||||
import { LocalDatabase } from './services/db';
|
||||
import { InsightService } from './services/insight';
|
||||
import { Assignment } from './types';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const SESSION_SECRET = process.env.SESSION_SECRET || 'bekultur_secret_key_change_in_production';
|
||||
|
||||
// View engine setup
|
||||
app.set('view engine', 'ejs');
|
||||
// Support running from both ts-node (src/../views) and dist (dist/views)
|
||||
const viewsPath = path.resolve(__dirname, '../views');
|
||||
const publicPath = path.resolve(__dirname, '../public');
|
||||
app.set('views', viewsPath);
|
||||
|
||||
// Middleware
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use(express.static(publicPath));
|
||||
|
||||
app.use(
|
||||
session({
|
||||
secret: SESSION_SECRET,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Augment express-session
|
||||
declare module 'express-session' {
|
||||
interface SessionData {
|
||||
studentId?: string;
|
||||
portalCookies?: string;
|
||||
studentName?: string;
|
||||
}
|
||||
}
|
||||
|
||||
const db = LocalDatabase.getInstance();
|
||||
|
||||
// Auth guard helper
|
||||
function requireAuth(req: Request, res: Response, next: NextFunction) {
|
||||
if (req.session && req.session.studentId) {
|
||||
return next();
|
||||
}
|
||||
// Check if studentId remembered in cookie
|
||||
const rememberedId = req.cookies.bekultur_student_id;
|
||||
if (rememberedId) {
|
||||
const creds = db.getRememberedCredentials(rememberedId);
|
||||
if (creds) {
|
||||
// Auto re-login in background
|
||||
ScraperService.login(creds.studentId, creds.password).then(loginRes => {
|
||||
if (loginRes.success) {
|
||||
req.session.studentId = creds.studentId;
|
||||
req.session.portalCookies = loginRes.cookies;
|
||||
req.session.studentName = loginRes.studentName;
|
||||
return next();
|
||||
} else {
|
||||
res.clearCookie('bekultur_student_id');
|
||||
return res.redirect('/');
|
||||
}
|
||||
}).catch(() => {
|
||||
return res.redirect('/');
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.redirect('/');
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// Routes
|
||||
// ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* GET /
|
||||
* Login Page
|
||||
*/
|
||||
app.get('/', (req: Request, res: Response) => {
|
||||
if (req.session && req.session.studentId) {
|
||||
return res.redirect('/dashboard');
|
||||
}
|
||||
|
||||
const rememberedId = req.cookies.bekultur_student_id || '';
|
||||
const error = (req.query.error as string) || null;
|
||||
|
||||
res.render('login', {
|
||||
error,
|
||||
rememberedId,
|
||||
title: 'Login - BeKultur (Better E-Kultur)'
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /login
|
||||
* Authenticate against portal and scrape recent assignments
|
||||
*/
|
||||
app.post('/login', async (req: Request, res: Response) => {
|
||||
const { studentId, password, rememberMe } = req.body;
|
||||
|
||||
if (!studentId || !password) {
|
||||
return res.render('login', {
|
||||
error: 'Please enter both Student ID and Password.',
|
||||
rememberedId: studentId || '',
|
||||
title: 'Login - BeKultur'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const loginRes = await ScraperService.login(studentId, password);
|
||||
|
||||
if (!loginRes.success) {
|
||||
return res.render('login', {
|
||||
error: loginRes.error || 'Authentication failed. Please check your credentials.',
|
||||
rememberedId: studentId,
|
||||
title: 'Login - BeKultur'
|
||||
});
|
||||
}
|
||||
|
||||
req.session.studentId = studentId;
|
||||
req.session.portalCookies = loginRes.cookies;
|
||||
req.session.studentName = loginRes.studentName;
|
||||
|
||||
// Handle "Remember Me"
|
||||
if (rememberMe) {
|
||||
db.saveCredentials(studentId, password);
|
||||
res.cookie('bekultur_student_id', studentId, {
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
httpOnly: true
|
||||
});
|
||||
} else {
|
||||
db.clearCredentials(studentId);
|
||||
res.clearCookie('bekultur_student_id');
|
||||
}
|
||||
|
||||
// Scrape recent pages (1-2)
|
||||
try {
|
||||
const scrapeRes = await ScraperService.scrapeMultiplePages(loginRes.cookies, studentId, 2);
|
||||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||||
} catch (scrapeErr: any) {
|
||||
console.warn('Initial scrape warning (cached data will be used if available):', scrapeErr.message);
|
||||
}
|
||||
|
||||
res.redirect('/dashboard');
|
||||
} catch (err: any) {
|
||||
console.error('Login route error:', err);
|
||||
res.render('login', {
|
||||
error: 'An unexpected server error occurred during login.',
|
||||
rememberedId: studentId,
|
||||
title: 'Login - BeKultur'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /logout
|
||||
*/
|
||||
app.post('/logout', (req: Request, res: Response) => {
|
||||
req.session.destroy(() => {
|
||||
res.redirect('/');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /logout (convenience)
|
||||
*/
|
||||
app.get('/logout', (req: Request, res: Response) => {
|
||||
req.session.destroy(() => {
|
||||
res.redirect('/');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /dashboard
|
||||
* English dashboard with stats and checkable assignments
|
||||
*/
|
||||
app.get('/dashboard', requireAuth, (req: Request, res: Response) => {
|
||||
const studentId = req.session.studentId!;
|
||||
const studentStore = db.getStudentStore(studentId);
|
||||
|
||||
// Recalculate status for each assignment relative to current date
|
||||
const rawList = Object.values(studentStore.assignments);
|
||||
const updatedAssignments: Assignment[] = rawList.map(item => {
|
||||
const status = InsightService.computeStatus(item);
|
||||
return {
|
||||
...item,
|
||||
status
|
||||
};
|
||||
});
|
||||
|
||||
// Calculate statistics
|
||||
const stats = InsightService.calculateStats(updatedAssignments);
|
||||
|
||||
// Unique list of subjects for filter
|
||||
const subjects = Array.from(new Set(updatedAssignments.map(a => a.subject))).sort();
|
||||
|
||||
// Sort assignments:
|
||||
// 1. Not completed first
|
||||
// 2. Priority: next-week & due-soon first, then active, then overdue, then completed
|
||||
const statusPriority: Record<string, number> = {
|
||||
'due-soon': 1,
|
||||
'next-week': 2,
|
||||
'active': 3,
|
||||
'future': 4,
|
||||
'overdue': 5,
|
||||
'completed': 6
|
||||
};
|
||||
|
||||
updatedAssignments.sort((a, b) => {
|
||||
const pA = statusPriority[a.status] || 99;
|
||||
const pB = statusPriority[b.status] || 99;
|
||||
if (pA !== pB) return pA - pB;
|
||||
// secondary sort by end date descending
|
||||
return (b.parsedEndDate || '').localeCompare(a.parsedEndDate || '');
|
||||
});
|
||||
|
||||
res.render('dashboard', {
|
||||
title: 'Dashboard - BeKultur',
|
||||
studentId,
|
||||
studentName: req.session.studentName || `Student ${studentId}`,
|
||||
lastSynced: studentStore.lastSynced,
|
||||
stats,
|
||||
assignments: updatedAssignments,
|
||||
subjects
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/toggle
|
||||
* Toggle assignment completion state
|
||||
*/
|
||||
app.post('/api/toggle', requireAuth, (req: Request, res: Response) => {
|
||||
const studentId = req.session.studentId!;
|
||||
const { assignmentId, completed } = req.body;
|
||||
|
||||
if (!assignmentId) {
|
||||
return res.status(400).json({ success: false, error: 'Assignment ID is required' });
|
||||
}
|
||||
|
||||
const updated = db.toggleAssignment(studentId, assignmentId, completed);
|
||||
if (!updated) {
|
||||
return res.status(404).json({ success: false, error: 'Assignment not found' });
|
||||
}
|
||||
|
||||
// Recalculate fresh stats
|
||||
const studentStore = db.getStudentStore(studentId);
|
||||
const list = Object.values(studentStore.assignments).map(a => ({
|
||||
...a,
|
||||
status: InsightService.computeStatus(a)
|
||||
}));
|
||||
const stats = InsightService.calculateStats(list);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
assignment: updated,
|
||||
stats
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/sync
|
||||
* Sync recent pages (1-2)
|
||||
*/
|
||||
app.post('/api/sync', requireAuth, async (req: Request, res: Response) => {
|
||||
const studentId = req.session.studentId!;
|
||||
let cookies = req.session.portalCookies;
|
||||
|
||||
try {
|
||||
// If session cookies missing, attempt re-login using remembered credentials
|
||||
if (!cookies) {
|
||||
const creds = db.getRememberedCredentials(studentId);
|
||||
if (creds) {
|
||||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||||
if (loginRes.success) {
|
||||
cookies = loginRes.cookies;
|
||||
req.session.portalCookies = cookies;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!cookies) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Session expired. Please log in again to sync.'
|
||||
});
|
||||
}
|
||||
|
||||
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 2);
|
||||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||||
|
||||
const store = db.getStudentStore(studentId);
|
||||
const list = Object.values(store.assignments).map(a => ({
|
||||
...a,
|
||||
status: InsightService.computeStatus(a)
|
||||
}));
|
||||
const stats = InsightService.calculateStats(list);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
count: scrapeRes.assignments.length,
|
||||
lastSynced: store.lastSynced,
|
||||
stats
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error('API sync error:', err.message);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: `Sync failed: ${err.message}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/sync-all
|
||||
* Sync all historical pages (pages 1 to 7+)
|
||||
*/
|
||||
app.post('/api/sync-all', requireAuth, async (req: Request, res: Response) => {
|
||||
const studentId = req.session.studentId!;
|
||||
let cookies = req.session.portalCookies;
|
||||
|
||||
try {
|
||||
if (!cookies) {
|
||||
const creds = db.getRememberedCredentials(studentId);
|
||||
if (creds) {
|
||||
const loginRes = await ScraperService.login(creds.studentId, creds.password);
|
||||
if (loginRes.success) {
|
||||
cookies = loginRes.cookies;
|
||||
req.session.portalCookies = cookies;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!cookies) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Session expired. Please log in again to sync full history.'
|
||||
});
|
||||
}
|
||||
|
||||
// Scrape up to 20 pages (portal currently has ~7 pages)
|
||||
const scrapeRes = await ScraperService.scrapeMultiplePages(cookies, studentId, 20);
|
||||
db.mergeAssignments(studentId, scrapeRes.assignments);
|
||||
|
||||
const store = db.getStudentStore(studentId);
|
||||
const list = Object.values(store.assignments).map(a => ({
|
||||
...a,
|
||||
status: InsightService.computeStatus(a)
|
||||
}));
|
||||
const stats = InsightService.calculateStats(list);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
count: scrapeRes.assignments.length,
|
||||
totalPages: scrapeRes.totalPages,
|
||||
lastSynced: store.lastSynced,
|
||||
stats
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error('API sync-all error:', err.message);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: `Full history sync failed: ${err.message}`
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Start Server
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
app.listen(PORT, () => {
|
||||
console.log(`=========================================`);
|
||||
console.log(` BeKultur (Better E-Kultur) Server`);
|
||||
console.log(` Running at: http://localhost:${PORT}`);
|
||||
console.log(`=========================================`);
|
||||
});
|
||||
}
|
||||
|
||||
export default app;
|
||||
127
src/services/db.ts
Normal file
127
src/services/db.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { DatabaseSchema, StudentStore, Assignment } from '../types';
|
||||
|
||||
const DB_FILE = path.resolve(process.cwd(), 'data', 'db.json');
|
||||
|
||||
export class LocalDatabase {
|
||||
private static instance: LocalDatabase;
|
||||
private cache: DatabaseSchema = { students: {} };
|
||||
private initialized = false;
|
||||
|
||||
private constructor() {
|
||||
this.ensureDbExists();
|
||||
this.load();
|
||||
}
|
||||
|
||||
public static getInstance(): LocalDatabase {
|
||||
if (!LocalDatabase.instance) {
|
||||
LocalDatabase.instance = new 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');
|
||||
}
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
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 = {};
|
||||
}
|
||||
}
|
||||
this.initialized = true;
|
||||
} catch (err) {
|
||||
console.error('Error loading database file, initializing empty:', err);
|
||||
this.cache = { students: {} };
|
||||
}
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
try {
|
||||
const tmpFile = `${DB_FILE}.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);
|
||||
}
|
||||
}
|
||||
|
||||
public getStudentStore(studentId: string): StudentStore {
|
||||
if (!this.cache.students[studentId]) {
|
||||
this.cache.students[studentId] = {
|
||||
studentId,
|
||||
lastSynced: null,
|
||||
assignments: {}
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
return this.cache.students[studentId];
|
||||
}
|
||||
|
||||
public mergeAssignments(studentId: string, newAssignments: Assignment[]): StudentStore {
|
||||
const student = this.getStudentStore(studentId);
|
||||
student.lastSynced = new Date().toISOString();
|
||||
|
||||
for (const item of newAssignments) {
|
||||
const existing = student.assignments[item.id];
|
||||
if (existing) {
|
||||
// Preserve user completion status and completion timestamp
|
||||
student.assignments[item.id] = {
|
||||
...item,
|
||||
completed: existing.completed,
|
||||
completedAt: existing.completedAt
|
||||
};
|
||||
} else {
|
||||
student.assignments[item.id] = item;
|
||||
}
|
||||
}
|
||||
|
||||
this.save();
|
||||
return student;
|
||||
}
|
||||
|
||||
public toggleAssignment(studentId: string, assignmentId: string, completed?: boolean): Assignment | null {
|
||||
const student = this.getStudentStore(studentId);
|
||||
const assignment = student.assignments[assignmentId];
|
||||
if (!assignment) {
|
||||
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;
|
||||
|
||||
this.save();
|
||||
return assignment;
|
||||
}
|
||||
|
||||
public saveCredentials(studentId: string, password: string): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
student.rememberedCredentials = { studentId, password };
|
||||
this.save();
|
||||
}
|
||||
|
||||
public clearCredentials(studentId: string): void {
|
||||
const student = this.getStudentStore(studentId);
|
||||
delete student.rememberedCredentials;
|
||||
this.save();
|
||||
}
|
||||
|
||||
public getRememberedCredentials(studentId: string): { studentId: string; password: string } | null {
|
||||
const student = this.cache.students[studentId];
|
||||
return student?.rememberedCredentials || null;
|
||||
}
|
||||
}
|
||||
239
src/services/insight.ts
Normal file
239
src/services/insight.ts
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
import { Assignment, AssignmentStatus, DashboardStats, SubjectStat } from '../types';
|
||||
|
||||
export class InsightService {
|
||||
/**
|
||||
* Normalize Turkish text for consistent regex and search matching (handles I / ı / İ / i)
|
||||
*/
|
||||
public static normalizeTurkish(str: string): string {
|
||||
if (!str) return '';
|
||||
return str
|
||||
.replace(/İ/g, 'i')
|
||||
.replace(/I/g, 'ı')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Turkish date string like "20.10.2026" or "8.11.2026" into a Date object
|
||||
*/
|
||||
public static parsePortalDate(dateStr: string): Date | null {
|
||||
if (!dateStr) return null;
|
||||
const parts = dateStr.trim().split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
|
||||
const day = parseInt(parts[0], 10);
|
||||
const month = parseInt(parts[1], 10) - 1;
|
||||
const year = parseInt(parts[2], 10);
|
||||
|
||||
if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
|
||||
return new Date(year, month, day, 23, 59, 59, 999);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Date to ISO date string (YYYY-MM-DD)
|
||||
*/
|
||||
public static toISODate(date: Date | null): string | null {
|
||||
if (!date || isNaN(date.getTime())) return null;
|
||||
const y = date.getFullYear();
|
||||
const m = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const d = String(date.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan description for teacher notes regarding check dates ("kontrol tarihi")
|
||||
*/
|
||||
public static extractTeacherCheckNote(description: string): string | null {
|
||||
if (!description) return null;
|
||||
const norm = this.normalizeTurkish(description);
|
||||
|
||||
// Pattern 1: "kontrol tarihi 26-30 ekim" or "kontrol tarihi 27 ekim"
|
||||
const match1 = norm.match(/kontrol\s+tarihi\s*:?\s*([0-9]{1,2}(?:\s*-\s*[0-9]{1,2})?\s+[a-zçğıöşü]+)/);
|
||||
if (match1) {
|
||||
return match1[1].trim();
|
||||
}
|
||||
|
||||
// Pattern 2: "ödevler 26-30 ekim arasında kontrol edilecektir"
|
||||
const match2 = norm.match(/ödevler\s+([0-9]{1,2}(?:\s*-\s*[0-9]{1,2})?\s+[a-zçğıöşü]+)\s+arasında\s+kontrol/);
|
||||
if (match2) {
|
||||
return match2[1].trim();
|
||||
}
|
||||
|
||||
// Pattern 3: "26 10 kontrol" or "26/10 kontrol"
|
||||
const match3 = norm.match(/([0-9]{1,2}\s+[0-9]{1,2})\s+kontrol/);
|
||||
if (match3) {
|
||||
const parts = match3[1].split(/\s+/);
|
||||
const day = parts[0];
|
||||
const monthNum = parseInt(parts[1], 10);
|
||||
const monthNames = ['', 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'];
|
||||
const monthName = monthNames[monthNum] || parts[1];
|
||||
return `${day} ${monthName}`;
|
||||
}
|
||||
|
||||
// Pattern 4: generic "(... kontrol ...)"
|
||||
const match4 = norm.match(/\(([^)]*kontrol[^)]*)\)/);
|
||||
if (match4) {
|
||||
return match4[1].trim();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify assignment status based on official dates, teacher notes, and completion flag
|
||||
*/
|
||||
public static computeStatus(
|
||||
assignment: Omit<Assignment, 'status'>,
|
||||
refDate: Date = new Date()
|
||||
): AssignmentStatus {
|
||||
if (assignment.completed) {
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
const endDate = this.parsePortalDate(assignment.endDate);
|
||||
const startDate = this.parsePortalDate(assignment.startDate);
|
||||
|
||||
// If start date is in the future (> today + 2 days)
|
||||
const todayStart = new Date(refDate.getFullYear(), refDate.getMonth(), refDate.getDate(), 0, 0, 0);
|
||||
if (startDate && startDate.getTime() > refDate.getTime() + 86400000 * 2) {
|
||||
return 'future';
|
||||
}
|
||||
|
||||
if (!endDate) {
|
||||
return 'active';
|
||||
}
|
||||
|
||||
// Check if already overdue
|
||||
if (endDate.getTime() < todayStart.getTime()) {
|
||||
return 'overdue';
|
||||
}
|
||||
|
||||
// Current week boundaries (Monday to Sunday)
|
||||
const currentDay = refDate.getDay(); // 0 is Sunday, 1 is Monday
|
||||
const distanceToMonday = currentDay === 0 ? -6 : 1 - currentDay;
|
||||
const thisMonday = new Date(refDate);
|
||||
thisMonday.setDate(refDate.getDate() + distanceToMonday);
|
||||
thisMonday.setHours(0, 0, 0, 0);
|
||||
|
||||
const thisSunday = new Date(thisMonday);
|
||||
thisSunday.setDate(thisMonday.getDate() + 6);
|
||||
thisSunday.setHours(23, 59, 59, 999);
|
||||
|
||||
const nextMonday = new Date(thisSunday);
|
||||
nextMonday.setDate(thisSunday.getDate() + 1);
|
||||
nextMonday.setHours(0, 0, 0, 0);
|
||||
|
||||
const nextSunday = new Date(nextMonday);
|
||||
nextSunday.setDate(nextMonday.getDate() + 6);
|
||||
nextSunday.setHours(23, 59, 59, 999);
|
||||
|
||||
// Check if due in next week window
|
||||
const dueTime = endDate.getTime();
|
||||
const isNextWeek = dueTime >= nextMonday.getTime() && dueTime <= nextSunday.getTime();
|
||||
|
||||
// Check if teacher check note specifically mentions next week
|
||||
let noteIsNextWeek = false;
|
||||
if (assignment.detectedCheckDate) {
|
||||
const lower = assignment.detectedCheckDate.toLowerCase();
|
||||
const dayMatches = lower.match(/\d{1,2}/g);
|
||||
if (dayMatches) {
|
||||
for (const dm of dayMatches) {
|
||||
const d = parseInt(dm, 10);
|
||||
const nextMonDay = nextMonday.getDate();
|
||||
const nextSunDay = nextSunday.getDate();
|
||||
if (nextMonDay <= nextSunDay) {
|
||||
if (d >= nextMonDay && d <= nextSunDay) {
|
||||
noteIsNextWeek = true;
|
||||
}
|
||||
} else {
|
||||
if (d >= nextMonDay || d <= nextSunDay) {
|
||||
noteIsNextWeek = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isNextWeek || noteIsNextWeek) {
|
||||
return 'next-week';
|
||||
}
|
||||
|
||||
// Due soon: within 3 days from now
|
||||
const threeDaysFromNow = new Date(refDate);
|
||||
threeDaysFromNow.setDate(refDate.getDate() + 3);
|
||||
threeDaysFromNow.setHours(23, 59, 59, 999);
|
||||
|
||||
if (dueTime <= threeDaysFromNow.getTime()) {
|
||||
return 'due-soon';
|
||||
}
|
||||
|
||||
return 'active';
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate statistics across a list of assignments
|
||||
*/
|
||||
public static calculateStats(assignments: Assignment[]): DashboardStats {
|
||||
let completed = 0;
|
||||
let active = 0;
|
||||
let checkedNextWeek = 0;
|
||||
let dueSoon = 0;
|
||||
let overdue = 0;
|
||||
|
||||
const bySubject: Record<string, SubjectStat> = {};
|
||||
|
||||
for (const item of assignments) {
|
||||
const subj = item.subject.trim() || 'Other';
|
||||
if (!bySubject[subj]) {
|
||||
bySubject[subj] = {
|
||||
subject: subj,
|
||||
total: 0,
|
||||
completed: 0,
|
||||
active: 0,
|
||||
percentage: 0
|
||||
};
|
||||
}
|
||||
|
||||
bySubject[subj].total += 1;
|
||||
|
||||
if (item.completed) {
|
||||
completed += 1;
|
||||
bySubject[subj].completed += 1;
|
||||
} else {
|
||||
if (item.status === 'overdue') {
|
||||
overdue += 1;
|
||||
} else if (item.status === 'next-week') {
|
||||
checkedNextWeek += 1;
|
||||
active += 1;
|
||||
bySubject[subj].active += 1;
|
||||
} else if (item.status === 'due-soon') {
|
||||
dueSoon += 1;
|
||||
active += 1;
|
||||
bySubject[subj].active += 1;
|
||||
} else {
|
||||
active += 1;
|
||||
bySubject[subj].active += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate subject percentages
|
||||
for (const subj of Object.keys(bySubject)) {
|
||||
const s = bySubject[subj];
|
||||
s.percentage = s.total > 0 ? Math.round((s.completed / s.total) * 100) : 0;
|
||||
}
|
||||
|
||||
const total = assignments.length;
|
||||
const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;
|
||||
|
||||
return {
|
||||
total,
|
||||
completed,
|
||||
active,
|
||||
checkedNextWeek,
|
||||
dueSoon,
|
||||
overdue,
|
||||
completionRate,
|
||||
bySubject
|
||||
};
|
||||
}
|
||||
}
|
||||
307
src/services/scraper.ts
Normal file
307
src/services/scraper.ts
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
import axios from 'axios';
|
||||
import * as cheerio from 'cheerio';
|
||||
import crypto from 'crypto';
|
||||
import { Assignment } from '../types';
|
||||
import { InsightService } from './insight';
|
||||
|
||||
const BASE_URL = 'https://ogrenci.ozelbursakulturokullari.com';
|
||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
||||
|
||||
export interface LoginResult {
|
||||
success: boolean;
|
||||
cookies: string;
|
||||
error?: string;
|
||||
studentName?: string;
|
||||
}
|
||||
|
||||
export interface ScrapeResult {
|
||||
assignments: Assignment[];
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export class ScraperService {
|
||||
/**
|
||||
* Helper to format cookies array from set-cookie headers
|
||||
*/
|
||||
private static parseCookies(cookieHeaders: string[] | undefined): string {
|
||||
if (!cookieHeaders || !cookieHeaders.length) return '';
|
||||
return cookieHeaders
|
||||
.map(c => c.split(';')[0].trim())
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge new set-cookie headers into existing cookie string
|
||||
*/
|
||||
private static mergeCookies(currentCookies: string, newHeaders: string[] | undefined): string {
|
||||
if (!newHeaders || !newHeaders.length) return currentCookies;
|
||||
const cookieMap: Record<string, string> = {};
|
||||
|
||||
if (currentCookies) {
|
||||
currentCookies.split(';').forEach(c => {
|
||||
const [k, ...v] = c.trim().split('=');
|
||||
if (k) cookieMap[k] = v.join('=');
|
||||
});
|
||||
}
|
||||
|
||||
newHeaders.forEach(c => {
|
||||
const first = c.split(';')[0].trim();
|
||||
const [k, ...v] = first.split('=');
|
||||
if (k) cookieMap[k] = v.join('=');
|
||||
});
|
||||
|
||||
return Object.entries(cookieMap)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate against Kültür Okulları student portal
|
||||
*/
|
||||
public static async login(studentId: string, password: string): Promise<LoginResult> {
|
||||
try {
|
||||
const client = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT
|
||||
},
|
||||
maxRedirects: 0,
|
||||
validateStatus: () => true // Allow handling redirects manually
|
||||
});
|
||||
|
||||
// 1. GET /Kullanici/Giris to obtain anti-forgery token and initial cookies
|
||||
const loginPageRes = await client.get('/Kullanici/Giris');
|
||||
let cookies = this.parseCookies(loginPageRes.headers['set-cookie']);
|
||||
|
||||
const $ = cheerio.load(loginPageRes.data);
|
||||
const token = $('input[name="__RequestVerificationToken"]').val() as string;
|
||||
|
||||
if (!token) {
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: 'Anti-forgery token could not be found on login page.'
|
||||
};
|
||||
}
|
||||
|
||||
// 2. POST /Kullanici/Giris with credentials
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('OgrenciId', studentId.trim());
|
||||
formData.append('Parola', password.trim());
|
||||
formData.append('__RequestVerificationToken', token);
|
||||
|
||||
const postRes = await client.post('/Kullanici/Giris', formData.toString(), {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': `${BASE_URL}/Kullanici/Giris`,
|
||||
'Cookie': cookies
|
||||
}
|
||||
});
|
||||
|
||||
cookies = this.mergeCookies(cookies, postRes.headers['set-cookie']);
|
||||
|
||||
// Check if successful login (302 redirect or has auth cookies)
|
||||
const hasAuthCookie = cookies.includes('.Ogrenci.Cookie') || cookies.includes('.AspNetCore.Cookies');
|
||||
const isRedirectSuccess = postRes.status === 302 && (postRes.headers.location === '/' || postRes.headers.location === '');
|
||||
|
||||
if (!isRedirectSuccess && !hasAuthCookie) {
|
||||
const postHtml = String(postRes.data || '');
|
||||
const $post = cheerio.load(postHtml);
|
||||
const errorMsg = $post('.text-danger').text().trim() || 'Invalid Student ID or Password.';
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: errorMsg
|
||||
};
|
||||
}
|
||||
|
||||
// Check student name if available from home page
|
||||
let studentName = '';
|
||||
try {
|
||||
const homeRes = await client.get('/', {
|
||||
headers: {
|
||||
'Cookie': cookies
|
||||
}
|
||||
});
|
||||
cookies = this.mergeCookies(cookies, homeRes.headers['set-cookie']);
|
||||
const $home = cheerio.load(homeRes.data);
|
||||
const nameCandidate = $home('.nav-link, .dropdown-toggle, .user-name').text().trim();
|
||||
if (nameCandidate) {
|
||||
studentName = nameCandidate;
|
||||
}
|
||||
} catch (homeErr) {
|
||||
// Non-critical
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
cookies,
|
||||
studentName
|
||||
};
|
||||
} catch (err: any) {
|
||||
console.error('Error during portal login:', err.message);
|
||||
return {
|
||||
success: false,
|
||||
cookies: '',
|
||||
error: `Connection error: ${err.message}`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape homework cards from a single page
|
||||
*/
|
||||
public static async scrapePage(
|
||||
cookies: string,
|
||||
page: number = 1,
|
||||
studentId: string
|
||||
): Promise<ScrapeResult> {
|
||||
try {
|
||||
const url = `${BASE_URL}/Odev?sayfa=${page}`;
|
||||
const res = await axios.get(url, {
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT,
|
||||
'Cookie': cookies,
|
||||
'Referer': `${BASE_URL}/`
|
||||
},
|
||||
validateStatus: () => true
|
||||
});
|
||||
|
||||
if (res.status === 302 || res.status === 401 || (typeof res.data === 'string' && res.data.includes('girisForm'))) {
|
||||
throw new Error('Session expired or unauthorized. Please log in again.');
|
||||
}
|
||||
|
||||
const $ = cheerio.load(res.data);
|
||||
const assignments: Assignment[] = [];
|
||||
|
||||
// Discover maximum pages from pagination
|
||||
let totalPages = 1;
|
||||
$('.pagination li a').each((_, el) => {
|
||||
const href = $(el).attr('href') || '';
|
||||
const match = href.match(/sayfa=(\d+)/i);
|
||||
if (match) {
|
||||
const p = parseInt(match[1], 10);
|
||||
if (p > totalPages) {
|
||||
totalPages = p;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Parse each assignment card
|
||||
$('.kltr-card.mb-4').each((_, cardEl) => {
|
||||
const card = $(cardEl);
|
||||
|
||||
let subject = '';
|
||||
let type = '';
|
||||
let unit = '';
|
||||
let topic = '';
|
||||
let dateRange = '';
|
||||
|
||||
card.find('.row:first-child .col-md-2, .row:first-child .col-md-3').each((_, colEl) => {
|
||||
const label = $(colEl).find('p.fw-bold').text().trim().toLowerCase();
|
||||
const val = $(colEl).find('p:not(.fw-bold)').text().trim();
|
||||
|
||||
if (label.includes('ders')) subject = val;
|
||||
else if (label.includes('tip')) type = val;
|
||||
else if (label.includes('ünite') || label.includes('unite')) unit = val;
|
||||
else if (label.includes('konu')) topic = val;
|
||||
else if (label.includes('başlangıç') || label.includes('bitiş') || label.includes('baslangic')) dateRange = val;
|
||||
});
|
||||
|
||||
// Description is in second row
|
||||
let description = '';
|
||||
const descCol = card.find('.row:nth-child(2) .col-md-12');
|
||||
if (descCol.length) {
|
||||
const descP = descCol.find('p:not(.fw-bold)');
|
||||
description = descP.text().trim();
|
||||
}
|
||||
|
||||
// Parse date range: "20.10.2026 - 26.10.2026"
|
||||
let startDate = '';
|
||||
let endDate = '';
|
||||
if (dateRange) {
|
||||
const parts = dateRange.split('-').map(s => s.trim());
|
||||
if (parts.length >= 2) {
|
||||
startDate = parts[0];
|
||||
endDate = parts[1];
|
||||
} else {
|
||||
startDate = parts[0];
|
||||
endDate = parts[0];
|
||||
}
|
||||
}
|
||||
|
||||
const parsedStartDate = InsightService.toISODate(InsightService.parsePortalDate(startDate));
|
||||
const parsedEndDate = InsightService.toISODate(InsightService.parsePortalDate(endDate));
|
||||
|
||||
// Generate deterministic ID
|
||||
const normalizedDesc = description.replace(/\s+/g, ' ').trim();
|
||||
const hashPayload = `${studentId}|${subject}|${startDate}|${endDate}|${normalizedDesc}`;
|
||||
const id = crypto.createHash('sha256').update(hashPayload).digest('hex').slice(0, 16);
|
||||
|
||||
// Detect teacher note
|
||||
const detectedCheckDate = InsightService.extractTeacherCheckNote(description);
|
||||
|
||||
const assignmentDraft: Omit<Assignment, 'status'> = {
|
||||
id,
|
||||
subject: subject || 'Genel',
|
||||
type: type || 'Ödev',
|
||||
unit,
|
||||
topic,
|
||||
startDate,
|
||||
endDate,
|
||||
parsedStartDate,
|
||||
parsedEndDate,
|
||||
description,
|
||||
detectedCheckDate,
|
||||
completed: false,
|
||||
completedAt: null,
|
||||
page
|
||||
};
|
||||
|
||||
const status = InsightService.computeStatus(assignmentDraft);
|
||||
|
||||
assignments.push({
|
||||
...assignmentDraft,
|
||||
status
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
assignments,
|
||||
totalPages
|
||||
};
|
||||
} catch (err: any) {
|
||||
console.error(`Error scraping page ${page}:`, err.message);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape multiple pages (e.g. pages 1 to maxPages)
|
||||
*/
|
||||
public static async scrapeMultiplePages(
|
||||
cookies: string,
|
||||
studentId: string,
|
||||
maxPages: number = 2
|
||||
): Promise<ScrapeResult> {
|
||||
const firstPage = await this.scrapePage(cookies, 1, studentId);
|
||||
let allAssignments = [...firstPage.assignments];
|
||||
const totalPages = firstPage.totalPages;
|
||||
|
||||
const pagesToFetch = Math.min(totalPages, maxPages);
|
||||
|
||||
for (let p = 2; p <= pagesToFetch; p++) {
|
||||
try {
|
||||
const next = await this.scrapePage(cookies, p, studentId);
|
||||
allAssignments.push(...next.assignments);
|
||||
} catch (err: any) {
|
||||
console.error(`Failed to scrape page ${p}, continuing:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
assignments: allAssignments,
|
||||
totalPages
|
||||
};
|
||||
}
|
||||
}
|
||||
58
src/types/index.ts
Normal file
58
src/types/index.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
export type AssignmentStatus =
|
||||
| 'completed'
|
||||
| 'next-week'
|
||||
| 'due-soon'
|
||||
| 'active'
|
||||
| 'overdue'
|
||||
| 'future';
|
||||
|
||||
export interface Assignment {
|
||||
id: string; // SHA-256 deterministic hash
|
||||
subject: string; // e.g. "AYT Kimya" (Turkish original)
|
||||
type: string; // e.g. "Yayın" (Turkish original)
|
||||
unit: string;
|
||||
topic: string;
|
||||
startDate: string; // raw string e.g. "20.10.2026"
|
||||
endDate: string; // raw string e.g. "26.10.2026"
|
||||
parsedStartDate: string | null; // ISO "2026-10-20"
|
||||
parsedEndDate: string | null; // ISO "2026-10-26"
|
||||
description: string; // original Turkish text
|
||||
detectedCheckDate: string | null; // e.g. "26-30 Ekim"
|
||||
status: AssignmentStatus;
|
||||
completed: boolean;
|
||||
completedAt: string | null;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export interface SubjectStat {
|
||||
subject: string;
|
||||
total: number;
|
||||
completed: number;
|
||||
active: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface DashboardStats {
|
||||
total: number;
|
||||
completed: number;
|
||||
active: number;
|
||||
checkedNextWeek: number;
|
||||
dueSoon: number;
|
||||
overdue: number;
|
||||
completionRate: number;
|
||||
bySubject: Record<string, SubjectStat>;
|
||||
}
|
||||
|
||||
export interface StudentStore {
|
||||
studentId: string;
|
||||
lastSynced: string | null;
|
||||
rememberedCredentials?: {
|
||||
studentId: string;
|
||||
password: string;
|
||||
};
|
||||
assignments: Record<string, Assignment>;
|
||||
}
|
||||
|
||||
export interface DatabaseSchema {
|
||||
students: Record<string, StudentStore>;
|
||||
}
|
||||
261
test/run-tests.ts
Normal file
261
test/run-tests.ts
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
import assert from 'assert';
|
||||
import { LocalDatabase } from '../src/services/db';
|
||||
import { InsightService } from '../src/services/insight';
|
||||
import { ScraperService } from '../src/services/scraper';
|
||||
import { Assignment } from '../src/types';
|
||||
|
||||
async function runAllTests() {
|
||||
console.log('========================================================');
|
||||
console.log(' BeKultur - Automated Test Suite');
|
||||
console.log('========================================================\n');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name: string, fn: () => void | Promise<void>) {
|
||||
return (async () => {
|
||||
try {
|
||||
await fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed++;
|
||||
} catch (err: any) {
|
||||
console.error(` ✗ ${name}`);
|
||||
console.error(` Error: ${err.message}\n`);
|
||||
failed++;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// 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 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');
|
||||
|
||||
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 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);
|
||||
});
|
||||
|
||||
// 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',
|
||||
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);
|
||||
});
|
||||
|
||||
// 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 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]);
|
||||
let store = db.getStudentStore(testStudentId);
|
||||
assert(store.assignments[testItem.id]);
|
||||
assert.strictEqual(store.assignments[testItem.id].completed, false);
|
||||
|
||||
const updated = db.toggleAssignment(testStudentId, testItem.id, true);
|
||||
assert.strictEqual(updated?.completed, true);
|
||||
assert(updated?.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.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. 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)');
|
||||
}
|
||||
|
||||
console.log('\n--------------------------------------------------------');
|
||||
console.log(`Test Results: ${passed} passed, ${failed} failed`);
|
||||
console.log('--------------------------------------------------------\n');
|
||||
|
||||
if (failed > 0) {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
runAllTests().catch(err => {
|
||||
console.error('Fatal test error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
16
tsconfig.json
Normal file
16
tsconfig.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "test"]
|
||||
}
|
||||
232
views/dashboard.ejs
Normal file
232
views/dashboard.ejs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
<%- include('partials/header') %>
|
||||
|
||||
<div class="dashboard-wrapper">
|
||||
<!-- Top Bar -->
|
||||
<div class="dashboard-topbar">
|
||||
<div class="dashboard-title-area">
|
||||
<h1 class="dashboard-title">Homework</h1>
|
||||
<p class="dashboard-subtitle">
|
||||
Student <strong>#<%= studentId %></strong>
|
||||
<span class="dot-separator">•</span>
|
||||
<span id="syncStatus">
|
||||
<% if (lastSynced) { %>
|
||||
Last synced: <%= new Date(lastSynced).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) %>
|
||||
<% } else { %>
|
||||
Not synced
|
||||
<% } %>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="sync-actions">
|
||||
<button type="button" class="btn btn-secondary btn-sm" id="btnSyncRecent">
|
||||
Sync Recent
|
||||
</button>
|
||||
<button type="button" class="btn btn-primary btn-sm" id="btnSyncAll">
|
||||
Sync Full History
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="syncAlert" class="alert alert-info hidden"></div>
|
||||
|
||||
<!-- Summary Stats -->
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Completion</div>
|
||||
<div class="stat-value" id="statCompletionRate"><%= stats.completionRate %>%</div>
|
||||
<div class="stat-subtext" id="statCompletionFraction"><%= stats.completed %> / <%= stats.total %> done</div>
|
||||
<div class="progress-bar-container">
|
||||
<div class="progress-bar-fill" id="progressBarFill" style="width: <%= stats.completionRate %>%"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Active</div>
|
||||
<div class="stat-value" id="statActiveCount"><%= stats.active %></div>
|
||||
<div class="stat-subtext">In progress</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card stat-highlight">
|
||||
<div class="stat-label">Checked Next Week</div>
|
||||
<div class="stat-value" id="statNextWeekCount"><%= stats.checkedNextWeek %></div>
|
||||
<div class="stat-subtext">Due or checked next week</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Due Soon</div>
|
||||
<div class="stat-value" id="statDueSoonCount"><%= stats.dueSoon %></div>
|
||||
<div class="stat-subtext">Within 3 days</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Overdue</div>
|
||||
<div class="stat-value" id="statOverdueCount"><%= stats.overdue %></div>
|
||||
<div class="stat-subtext">Past deadline</div>
|
||||
</div>
|
||||
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Total</div>
|
||||
<div class="stat-value" id="statTotalCount"><%= stats.total %></div>
|
||||
<div class="stat-subtext">All assignments</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Subjects Overview (Collapsible) -->
|
||||
<div class="section-card">
|
||||
<div class="section-header cursor-pointer" id="subjectToggleHeader">
|
||||
<span class="section-title">Subjects (<%= Object.keys(stats.bySubject).length %>)</span>
|
||||
<span class="toggle-indicator" id="subjectToggleIcon">▼</span>
|
||||
</div>
|
||||
<div class="subject-breakdown-body" id="subjectBreakdownBody">
|
||||
<div class="subject-grid" id="subjectGrid">
|
||||
<% Object.values(stats.bySubject).forEach(function(subj) { %>
|
||||
<div class="subject-item" data-subject="<%= subj.subject %>">
|
||||
<div class="subject-info">
|
||||
<span class="subject-name"><%= subj.subject %></span>
|
||||
<span class="subject-fraction"><%= subj.completed %>/<%= subj.total %> (<%= subj.percentage %>%)</span>
|
||||
</div>
|
||||
<div class="subject-bar">
|
||||
<div class="subject-bar-fill" style="width: <%= subj.percentage %>%"></div>
|
||||
</div>
|
||||
</div>
|
||||
<% }); %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toolbar: Tabs & Search -->
|
||||
<div class="toolbar-card">
|
||||
<div class="filter-tabs" id="filterTabs">
|
||||
<button type="button" class="tab-btn active" data-filter="all">
|
||||
All (<span id="tabAllCount"><%= stats.total %></span>)
|
||||
</button>
|
||||
<button type="button" class="tab-btn" data-filter="next-week">
|
||||
Checked Next Week (<span id="tabNextWeekCount"><%= stats.checkedNextWeek %></span>)
|
||||
</button>
|
||||
<button type="button" class="tab-btn" data-filter="active">
|
||||
Active (<span id="tabActiveCount"><%= stats.active %></span>)
|
||||
</button>
|
||||
<button type="button" class="tab-btn" data-filter="due-soon">
|
||||
Due Soon (<span id="tabDueSoonCount"><%= stats.dueSoon %></span>)
|
||||
</button>
|
||||
<button type="button" class="tab-btn" data-filter="completed">
|
||||
Completed (<span id="tabCompletedCount"><%= stats.completed %></span>)
|
||||
</button>
|
||||
<button type="button" class="tab-btn" data-filter="overdue">
|
||||
Overdue (<span id="tabOverdueCount"><%= stats.overdue %></span>)
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="filter-controls">
|
||||
<div class="search-box">
|
||||
<input
|
||||
type="text"
|
||||
id="searchInput"
|
||||
class="search-input"
|
||||
placeholder="Filter by subject, book, or description..."
|
||||
>
|
||||
<button type="button" id="searchClear" class="search-clear hidden">×</button>
|
||||
</div>
|
||||
|
||||
<div class="select-box">
|
||||
<select id="subjectSelect" class="form-select">
|
||||
<option value="">All Subjects</option>
|
||||
<% subjects.forEach(function(s) { %>
|
||||
<option value="<%= s %>"><%= s %></option>
|
||||
<% }); %>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="list-meta">
|
||||
<span id="filteredCountText">Showing <%= assignments.length %> assignments</span>
|
||||
</div>
|
||||
|
||||
<!-- Empty Search State -->
|
||||
<div id="noResults" class="empty-state hidden">
|
||||
<p>No matching assignments found.</p>
|
||||
<button type="button" class="btn btn-secondary btn-sm" id="btnResetFilters">Reset filters</button>
|
||||
</div>
|
||||
|
||||
<!-- Assignments -->
|
||||
<div class="assignment-list" id="assignmentList">
|
||||
<% assignments.forEach(function(item) { %>
|
||||
<div
|
||||
class="assignment-card <%= item.completed ? 'is-completed' : '' %> status-<%= item.status %>"
|
||||
data-id="<%= item.id %>"
|
||||
data-status="<%= item.status %>"
|
||||
data-subject="<%= item.subject %>"
|
||||
data-completed="<%= item.completed ? 'true' : 'false' %>"
|
||||
data-search="<%= (item.subject + ' ' + item.description + ' ' + (item.detectedCheckDate || '') + ' ' + (item.topic || '') + ' ' + (item.unit || '')).toLowerCase() %>"
|
||||
>
|
||||
<div class="card-checkbox-col">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="assignment-toggle"
|
||||
data-id="<%= item.id %>"
|
||||
<%= item.completed ? 'checked' : '' %>
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="card-content-col">
|
||||
<div class="card-top-row">
|
||||
<div class="card-subject-wrap">
|
||||
<span class="card-subject"><%= item.subject %></span>
|
||||
<% if (item.type) { %>
|
||||
<span class="badge badge-type"><%= item.type %></span>
|
||||
<% } %>
|
||||
</div>
|
||||
|
||||
<div class="card-badges">
|
||||
<% if (item.detectedCheckDate) { %>
|
||||
<span class="badge badge-check-date">
|
||||
Kontrol: <%= item.detectedCheckDate %>
|
||||
</span>
|
||||
<% } %>
|
||||
|
||||
<% if (item.completed) { %>
|
||||
<span class="badge badge-completed">Done</span>
|
||||
<% } else if (item.status === 'next-week') { %>
|
||||
<span class="badge badge-next-week">Next Week</span>
|
||||
<% } else if (item.status === 'due-soon') { %>
|
||||
<span class="badge badge-due-soon">Due Soon</span>
|
||||
<% } else if (item.status === 'overdue') { %>
|
||||
<span class="badge badge-overdue">Overdue</span>
|
||||
<% } else { %>
|
||||
<span class="badge badge-active">Active</span>
|
||||
<% } %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<% if (item.unit || item.topic) { %>
|
||||
<div class="card-sub-meta">
|
||||
<% if (item.unit) { %><span><strong>Ünite:</strong> <%= item.unit %></span><% } %>
|
||||
<% if (item.topic) { %><span><strong>Konu:</strong> <%= item.topic %></span><% } %>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<div class="card-description">
|
||||
<%= item.description %>
|
||||
</div>
|
||||
|
||||
<div class="card-footer-row">
|
||||
<div class="card-dates">
|
||||
<span><%= item.startDate %> — <strong><%= item.endDate %></strong></span>
|
||||
</div>
|
||||
|
||||
<div class="card-timestamps">
|
||||
<% if (item.completed && item.completedAt) { %>
|
||||
<span class="completed-timestamp">Done: <%= new Date(item.completedAt).toLocaleDateString() %></span>
|
||||
<% } %>
|
||||
<span class="card-hash">#<%= item.id %></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<% }); %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<%- include('partials/footer') %>
|
||||
65
views/login.ejs
Normal file
65
views/login.ejs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
<%- include('partials/header') %>
|
||||
|
||||
<div class="auth-wrapper">
|
||||
<div class="auth-card">
|
||||
<h1 class="auth-title">BeKultur</h1>
|
||||
<p class="auth-subtitle">Log in with your school portal credentials.</p>
|
||||
|
||||
<% if (typeof error !== 'undefined' && error) { %>
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<span class="alert-text"><%= error %></span>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<form action="/login" method="POST" class="auth-form" id="loginForm">
|
||||
<div class="form-group">
|
||||
<label for="studentId" class="form-label">Student ID</label>
|
||||
<input
|
||||
type="text"
|
||||
id="studentId"
|
||||
name="studentId"
|
||||
class="form-control"
|
||||
placeholder="Student ID"
|
||||
value="<%= typeof rememberedId !== 'undefined' ? rememberedId : '' %>"
|
||||
required
|
||||
autofocus
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="password" class="form-label">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
class="form-control"
|
||||
placeholder="Password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="form-row-between">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" name="rememberMe" value="true" checked>
|
||||
<span>Remember credentials</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary btn-block" id="submitBtn">
|
||||
Log In
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('loginForm').addEventListener('submit', function() {
|
||||
var btn = document.getElementById('submitBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Logging in...';
|
||||
});
|
||||
</script>
|
||||
|
||||
<%- include('partials/footer') %>
|
||||
9
views/partials/footer.ejs
Normal file
9
views/partials/footer.ejs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
</main>
|
||||
<footer class="app-footer">
|
||||
<div class="footer-container">
|
||||
<span class="footer-text">BeKultur</span>
|
||||
</div>
|
||||
</footer>
|
||||
<script src="/js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
25
views/partials/header.ejs
Normal file
25
views/partials/header.ejs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><%= typeof title !== 'undefined' ? title : 'BeKultur' %></title>
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div class="header-container">
|
||||
<div class="brand">
|
||||
<a href="/" class="brand-link">
|
||||
<span class="brand-name">BeKultur</span>
|
||||
</a>
|
||||
</div>
|
||||
<% if (typeof studentId !== 'undefined' && studentId) { %>
|
||||
<div class="user-nav">
|
||||
<span class="user-id">Student: <%= studentId %></span>
|
||||
<a href="/logout" class="btn btn-outline btn-sm">Log out</a>
|
||||
</div>
|
||||
<% } %>
|
||||
</div>
|
||||
</header>
|
||||
<main class="main-content">
|
||||
Loading…
Add table
Add a link
Reference in a new issue