-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
486 lines (408 loc) · 15.9 KB
/
app.py
File metadata and controls
486 lines (408 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
from pathlib import Path
APP_DIR = Path(__file__).resolve().parent
DB_PATH = APP_DIR / "campus.db"
SCHEMA_PATH = APP_DIR / "schema.sql"
app = Flask(__name__)
app.secret_key = "campuspulse_secret_key" # for flash messages
# ---------------- DB Helpers ----------------
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON;")
return conn
def init_db():
conn = get_db()
conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8"))
conn.close()
def time_overlap(start_a, end_a, start_b, end_b):
# times as "HH:MM"
return start_a < end_b and start_b < end_a
def session_conflicts(conn, day, start_time, end_time, classroom_id, faculty_id):
"""Return (room_conflict, faculty_conflict) boolean."""
rows = conn.execute(
"""
SELECT id, classroom_id, faculty_id, start_time, end_time
FROM class_sessions
WHERE day_of_week = ?
""",
(day,),
).fetchall()
room_conflict = False
faculty_conflict = False
for r in rows:
if time_overlap(start_time, end_time, r["start_time"], r["end_time"]):
if int(r["classroom_id"]) == int(classroom_id):
room_conflict = True
if int(r["faculty_id"]) == int(faculty_id):
faculty_conflict = True
return room_conflict, faculty_conflict
# ---------------- Analytics Queries ----------------
def get_dashboard_stats(conn):
stats = {}
stats["blocks"] = conn.execute("SELECT COUNT(*) c FROM blocks").fetchone()["c"]
stats["classrooms"] = conn.execute("SELECT COUNT(*) c FROM classrooms").fetchone()["c"]
stats["courses"] = conn.execute("SELECT COUNT(*) c FROM courses").fetchone()["c"]
stats["faculty"] = conn.execute("SELECT COUNT(*) c FROM faculty").fetchone()["c"]
stats["students"] = conn.execute("SELECT COUNT(*) c FROM students").fetchone()["c"]
stats["sessions"] = conn.execute("SELECT COUNT(*) c FROM class_sessions").fetchone()["c"]
# warnings: overcapacity sessions
stats["overcapacity"] = conn.execute(
"""
SELECT COUNT(*) c
FROM class_sessions s
JOIN classrooms c ON c.id = s.classroom_id
WHERE s.expected_students > c.capacity
"""
).fetchone()["c"]
return stats
def classroom_utilization(conn):
return conn.execute(
"""
SELECT
cr.id AS classroom_id,
b.name AS block_name,
cr.room_no,
cr.capacity,
COUNT(s.id) AS total_sessions,
ROUND(COALESCE(AVG(
CASE WHEN cr.capacity = 0 THEN 0
ELSE (1.0 * s.expected_students / cr.capacity) * 100
END
),0), 2) AS avg_util_percent,
COALESCE(SUM(s.expected_students),0) AS total_expected_students
FROM classrooms cr
JOIN blocks b ON b.id = cr.block_id
LEFT JOIN class_sessions s ON s.classroom_id = cr.id
GROUP BY cr.id
ORDER BY avg_util_percent DESC
"""
).fetchall()
def block_utilization(conn):
# ✅ FIXED COLUMN NAME + COALESCE
return conn.execute(
"""
SELECT
b.id AS block_id,
b.name AS block_name,
COUNT(s.id) AS total_sessions_in_block,
ROUND(COALESCE(AVG(
CASE WHEN cr.capacity = 0 THEN 0
ELSE (1.0 * s.expected_students / cr.capacity) * 100
END
),0), 2) AS avg_block_utilization_percent
FROM blocks b
JOIN classrooms cr ON cr.block_id = b.id
LEFT JOIN class_sessions s ON s.classroom_id = cr.id
GROUP BY b.id
ORDER BY avg_block_utilization_percent DESC
"""
).fetchall()
def faculty_workload(conn):
# hours computed from time difference (HH:MM) using sqlite strftime seconds
return conn.execute(
"""
SELECT
f.id AS faculty_id,
f.name,
f.department,
f.max_weekly_hours,
ROUND(COALESCE(SUM(
(strftime('%s', '2000-01-01 ' || s.end_time) - strftime('%s', '2000-01-01 ' || s.start_time)) / 3600.0
), 0), 2) AS total_hours,
ROUND(
CASE WHEN f.max_weekly_hours = 0 THEN 0
ELSE (COALESCE(SUM(
(strftime('%s', '2000-01-01 ' || s.end_time) - strftime('%s', '2000-01-01 ' || s.start_time)) / 3600.0
),0) / f.max_weekly_hours) * 100
END
, 2) AS workload_percent
FROM faculty f
LEFT JOIN class_sessions s ON s.faculty_id = f.id
GROUP BY f.id
ORDER BY workload_percent DESC
"""
).fetchall()
# ---------------- Routes ----------------
@app.route("/")
def dashboard():
conn = get_db()
stats = get_dashboard_stats(conn)
blocks = block_utilization(conn)
faculty = faculty_workload(conn)
# ---- SAFE CHART DATA ----
block_labels, block_values = [], []
for b in blocks:
b = dict(b) # convert sqlite3.Row -> dict
block_labels.append(b.get("block_name", ""))
block_values.append(float(b.get("avg_block_utilization_percent") or 0))
fac_labels, fac_values = [], []
for f in faculty:
f = dict(f)
fac_labels.append(f.get("name", ""))
fac_values.append(float(f.get("workload_percent") or 0))
conn.close()
return render_template(
"dashboard.html",
stats=stats,
blocks=blocks,
faculty=faculty,
block_labels=block_labels,
block_values=block_values,
fac_labels=fac_labels,
fac_values=fac_values
)
@app.route("/blocks", methods=["GET", "POST"])
def blocks():
conn = get_db()
if request.method == "POST":
name = request.form.get("name", "").strip()
if not name:
flash("Block name required!", "danger")
else:
try:
conn.execute("INSERT INTO blocks(name) VALUES(?)", (name,))
conn.commit()
flash("Block added!", "success")
except sqlite3.IntegrityError:
flash("Block already exists!", "warning")
return redirect(url_for("blocks"))
rows = conn.execute("SELECT * FROM blocks ORDER BY name").fetchall()
conn.close()
return render_template("blocks.html", blocks=rows)
@app.route("/blocks/delete/<int:block_id>")
def delete_block(block_id):
conn = get_db()
conn.execute("DELETE FROM blocks WHERE id=?", (block_id,))
conn.commit()
conn.close()
flash("Block deleted!", "info")
return redirect(url_for("blocks"))
@app.route("/classrooms", methods=["GET", "POST"])
def classrooms():
conn = get_db()
blocks_list = conn.execute("SELECT * FROM blocks ORDER BY name").fetchall()
if request.method == "POST":
block_id = request.form.get("block_id")
room_no = request.form.get("room_no", "").strip()
capacity = request.form.get("capacity", "").strip()
has_projector = 1 if request.form.get("has_projector") else 0
has_ac = 1 if request.form.get("has_ac") else 0
if not block_id or not room_no or not capacity.isdigit():
flash("Fill all fields correctly!", "danger")
else:
try:
conn.execute(
"""
INSERT INTO classrooms(block_id, room_no, capacity, has_projector, has_ac)
VALUES(?,?,?,?,?)
""",
(block_id, room_no, int(capacity), has_projector, has_ac),
)
conn.commit()
flash("Classroom added!", "success")
except sqlite3.IntegrityError:
flash("This room already exists in the block!", "warning")
return redirect(url_for("classrooms"))
rooms = conn.execute(
"""
SELECT cr.*, b.name AS block_name
FROM classrooms cr JOIN blocks b ON b.id = cr.block_id
ORDER BY b.name, cr.room_no
"""
).fetchall()
conn.close()
return render_template("classrooms.html", classrooms=rooms, blocks=blocks_list)
@app.route("/classrooms/delete/<int:room_id>")
def delete_classroom(room_id):
conn = get_db()
conn.execute("DELETE FROM classrooms WHERE id=?", (room_id,))
conn.commit()
conn.close()
flash("Classroom deleted!", "info")
return redirect(url_for("classrooms"))
@app.route("/courses", methods=["GET", "POST"])
def courses():
conn = get_db()
if request.method == "POST":
code = request.form.get("code", "").strip().upper()
title = request.form.get("title", "").strip()
dept = request.form.get("department", "").strip()
credits = request.form.get("credits", "").strip()
if not code or not title or not credits.isdigit():
flash("Fill course fields correctly!", "danger")
else:
try:
conn.execute(
"INSERT INTO courses(code,title,department,credits) VALUES(?,?,?,?)",
(code, title, dept, int(credits)),
)
conn.commit()
flash("Course added!", "success")
except sqlite3.IntegrityError:
flash("Course code already exists!", "warning")
return redirect(url_for("courses"))
rows = conn.execute("SELECT * FROM courses ORDER BY code").fetchall()
conn.close()
return render_template("courses.html", courses=rows)
@app.route("/courses/delete/<int:course_id>")
def delete_course(course_id):
conn = get_db()
conn.execute("DELETE FROM courses WHERE id=?", (course_id,))
conn.commit()
conn.close()
flash("Course deleted!", "info")
return redirect(url_for("courses"))
@app.route("/faculty", methods=["GET", "POST"])
def faculty():
conn = get_db()
if request.method == "POST":
name = request.form.get("name", "").strip()
dept = request.form.get("department", "").strip()
max_hours = request.form.get("max_weekly_hours", "").strip()
if not name or (max_hours and not max_hours.isdigit()):
flash("Fill faculty fields correctly!", "danger")
else:
mh = int(max_hours) if max_hours.isdigit() else 18
conn.execute(
"INSERT INTO faculty(name,department,max_weekly_hours) VALUES(?,?,?)",
(name, dept, mh),
)
conn.commit()
flash("Faculty added!", "success")
return redirect(url_for("faculty"))
rows = conn.execute("SELECT * FROM faculty ORDER BY name").fetchall()
conn.close()
return render_template("faculty.html", faculty=rows)
@app.route("/faculty/delete/<int:faculty_id>")
def delete_faculty(faculty_id):
conn = get_db()
conn.execute("DELETE FROM faculty WHERE id=?", (faculty_id,))
conn.commit()
conn.close()
flash("Faculty deleted!", "info")
return redirect(url_for("faculty"))
@app.route("/students", methods=["GET", "POST"])
def students():
conn = get_db()
if request.method == "POST":
name = request.form.get("name", "").strip()
program = request.form.get("program", "").strip()
year = request.form.get("year", "").strip()
if not name or (year and not year.isdigit()):
flash("Fill student fields correctly!", "danger")
else:
yr = int(year) if year.isdigit() else None
conn.execute(
"INSERT INTO students(name,program,year) VALUES(?,?,?)",
(name, program, yr),
)
conn.commit()
flash("Student added!", "success")
return redirect(url_for("students"))
rows = conn.execute("SELECT * FROM students ORDER BY name").fetchall()
conn.close()
return render_template("students.html", students=rows)
@app.route("/students/delete/<int:student_id>")
def delete_student(student_id):
conn = get_db()
conn.execute("DELETE FROM students WHERE id=?", (student_id,))
conn.commit()
conn.close()
flash("Student deleted!", "info")
return redirect(url_for("students"))
@app.route("/sessions", methods=["GET", "POST"])
def sessions():
conn = get_db()
courses_list = conn.execute("SELECT * FROM courses ORDER BY code").fetchall()
faculty_list = conn.execute("SELECT * FROM faculty ORDER BY name").fetchall()
rooms_list = conn.execute(
"""
SELECT cr.id, b.name || '-' || cr.room_no AS room_label, cr.capacity
FROM classrooms cr JOIN blocks b ON b.id = cr.block_id
ORDER BY b.name, cr.room_no
"""
).fetchall()
if request.method == "POST":
course_id = request.form.get("course_id")
faculty_id = request.form.get("faculty_id")
classroom_id = request.form.get("classroom_id")
day = request.form.get("day_of_week")
start_time = request.form.get("start_time")
end_time = request.form.get("end_time")
expected = request.form.get("expected_students", "0").strip()
if not all([course_id, faculty_id, classroom_id, day, start_time, end_time]) or not expected.isdigit():
flash("Fill session fields correctly!", "danger")
return redirect(url_for("sessions"))
if start_time >= end_time:
flash("End time must be after start time!", "danger")
return redirect(url_for("sessions"))
room_conf, fac_conf = session_conflicts(conn, day, start_time, end_time, classroom_id, faculty_id)
if room_conf:
flash("Time clash: This classroom already has a session in that time!", "danger")
return redirect(url_for("sessions"))
if fac_conf:
flash("Time clash: This faculty already has a session in that time!", "danger")
return redirect(url_for("sessions"))
conn.execute(
"""
INSERT INTO class_sessions(course_id, faculty_id, classroom_id, day_of_week, start_time, end_time, expected_students)
VALUES(?,?,?,?,?,?,?)
""",
(course_id, faculty_id, classroom_id, day, start_time, end_time, int(expected)),
)
conn.commit()
# Overcapacity warning
cap = conn.execute("SELECT capacity FROM classrooms WHERE id=?", (classroom_id,)).fetchone()["capacity"]
if int(expected) > int(cap):
flash("Session added, but WARNING: expected students exceed capacity!", "warning")
else:
flash("Session added!", "success")
return redirect(url_for("sessions"))
rows = conn.execute(
"""
SELECT
s.*,
c.code AS course_code,
c.title AS course_title,
f.name AS faculty_name,
b.name AS block_name,
cr.room_no,
cr.capacity
FROM class_sessions s
JOIN courses c ON c.id = s.course_id
JOIN faculty f ON f.id = s.faculty_id
JOIN classrooms cr ON cr.id = s.classroom_id
JOIN blocks b ON b.id = cr.block_id
ORDER BY s.day_of_week, s.start_time
"""
).fetchall()
conn.close()
return render_template("sessions.html",
sessions=rows,
courses=courses_list,
faculty=faculty_list,
rooms=rooms_list)
@app.route("/sessions/delete/<int:session_id>")
def delete_session(session_id):
conn = get_db()
conn.execute("DELETE FROM class_sessions WHERE id=?", (session_id,))
conn.commit()
conn.close()
flash("Session deleted!", "info")
return redirect(url_for("sessions"))
@app.route("/analytics")
def analytics():
conn = get_db()
class_util = classroom_utilization(conn)
block_util = block_utilization(conn)
fac_work = faculty_workload(conn)
conn.close()
return render_template("analytics.html",
classroom_util=class_util,
block_util=block_util,
faculty_workload=fac_work)
if __name__ == "__main__":
init_db()
app.run(debug=True)