Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ยท
721ec8b
1
Parent(s): 2b2e5e8
deploy: backend from a759fad
Browse files- routes/admin_routes.py +139 -0
routes/admin_routes.py
CHANGED
|
@@ -419,6 +419,145 @@ async def delete_uploaded_file(
|
|
| 419 |
|
| 420 |
# โโโ School-Wide Analytics โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 421 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
@router.get("/school-analytics")
|
| 423 |
def get_school_analytics(request: Request):
|
| 424 |
"""School-wide WRI aggregation for admin dashboard."""
|
|
|
|
| 419 |
|
| 420 |
# โโโ School-Wide Analytics โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 421 |
|
| 422 |
+
@router.get("/dashboard-analytics")
|
| 423 |
+
def get_dashboard_analytics(request: Request):
|
| 424 |
+
"""Aggregate dashboard metrics from current Firestore records."""
|
| 425 |
+
require_admin(request)
|
| 426 |
+
|
| 427 |
+
try:
|
| 428 |
+
import firebase_admin
|
| 429 |
+
from firebase_admin import firestore as fs
|
| 430 |
+
db = fs.client()
|
| 431 |
+
users = list(db.collection("users").stream())
|
| 432 |
+
classrooms = list(db.collection("classrooms").stream())
|
| 433 |
+
audit_logs = list(db.collection("auditLogs").stream())
|
| 434 |
+
managed_students = list(db.collection("managedStudents").stream())
|
| 435 |
+
curriculum_modules = list(db.collection("curriculumModules").stream())
|
| 436 |
+
except Exception:
|
| 437 |
+
logger.exception("Unable to read dashboard analytics from Firestore")
|
| 438 |
+
raise HTTPException(status_code=503, detail="Firestore unavailable")
|
| 439 |
+
|
| 440 |
+
from collections import Counter
|
| 441 |
+
from datetime import timedelta
|
| 442 |
+
|
| 443 |
+
def score_from(record):
|
| 444 |
+
for key in ("averageScore", "average_score", "diagnosticScore", "masteryScore", "mastery_score"):
|
| 445 |
+
value = record.get(key)
|
| 446 |
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
| 447 |
+
return max(0, min(100, float(value)))
|
| 448 |
+
return None
|
| 449 |
+
|
| 450 |
+
students = {}
|
| 451 |
+
for snapshot in users:
|
| 452 |
+
record = snapshot.to_dict() or {}
|
| 453 |
+
if str(record.get("role", "")).lower() == "student":
|
| 454 |
+
students[snapshot.id] = record
|
| 455 |
+
for snapshot in managed_students:
|
| 456 |
+
students.setdefault(snapshot.id, snapshot.to_dict() or {})
|
| 457 |
+
|
| 458 |
+
scores = [score for record in students.values() if (score := score_from(record)) is not None]
|
| 459 |
+
passed = sum(score >= 60 for score in scores)
|
| 460 |
+
total_students = len(students)
|
| 461 |
+
risk_subjects = Counter()
|
| 462 |
+
at_risk_ids = set()
|
| 463 |
+
for snapshot in managed_students:
|
| 464 |
+
record = snapshot.to_dict() or {}
|
| 465 |
+
status = str(record.get("riskStatus") or record.get("risk_status") or "").lower()
|
| 466 |
+
user = students.get(snapshot.id, {})
|
| 467 |
+
overall_risk = str(user.get("overallRisk") or user.get("riskLevel") or "").lower()
|
| 468 |
+
if status in {"intervene", "critical", "at_risk", "high"} or overall_risk == "high":
|
| 469 |
+
at_risk_ids.add(snapshot.id)
|
| 470 |
+
subject = record.get("weakestSubject") or record.get("weakest_subject") or record.get("subject")
|
| 471 |
+
if subject:
|
| 472 |
+
risk_subjects[str(subject)] += 1
|
| 473 |
+
for uid, record in students.items():
|
| 474 |
+
if str(record.get("overallRisk") or record.get("riskLevel") or "").lower() == "high":
|
| 475 |
+
at_risk_ids.add(uid)
|
| 476 |
+
|
| 477 |
+
now = datetime.now(timezone.utc)
|
| 478 |
+
day_names = ["M", "T", "W", "T", "F", "S", "S"]
|
| 479 |
+
weekly = []
|
| 480 |
+
today = now.date()
|
| 481 |
+
for days_ago in range(6, -1, -1):
|
| 482 |
+
date = today - timedelta(days=days_ago)
|
| 483 |
+
weekly.append({"name": day_names[date.weekday()], "ai": 0, "man": 0})
|
| 484 |
+
for snapshot in audit_logs:
|
| 485 |
+
record = snapshot.to_dict() or {}
|
| 486 |
+
timestamp = record.get("timestamp") or record.get("timestampRaw") or record.get("createdAt")
|
| 487 |
+
if hasattr(timestamp, "to_datetime"):
|
| 488 |
+
timestamp = timestamp.to_datetime()
|
| 489 |
+
elif hasattr(timestamp, "seconds"):
|
| 490 |
+
timestamp = datetime.fromtimestamp(timestamp.seconds, tz=timezone.utc)
|
| 491 |
+
elif isinstance(timestamp, str):
|
| 492 |
+
try:
|
| 493 |
+
timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
| 494 |
+
except ValueError:
|
| 495 |
+
continue
|
| 496 |
+
if not isinstance(timestamp, datetime):
|
| 497 |
+
continue
|
| 498 |
+
if timestamp.tzinfo is None:
|
| 499 |
+
timestamp = timestamp.replace(tzinfo=timezone.utc)
|
| 500 |
+
days_ago = (today - timestamp.astimezone(timezone.utc).date()).days
|
| 501 |
+
if not 0 <= days_ago <= 6:
|
| 502 |
+
continue
|
| 503 |
+
action = str(record.get("action") or record.get("eventType") or record.get("type") or "").lower()
|
| 504 |
+
weekly[6 - days_ago]["ai" if any(word in action for word in ("ai", "lesson", "quiz", "tutor")) else "man"] += 1
|
| 505 |
+
|
| 506 |
+
module_subjects = {}
|
| 507 |
+
for snapshot in curriculum_modules:
|
| 508 |
+
record = snapshot.to_dict() or {}
|
| 509 |
+
subject = record.get("subjectName") or record.get("subject") or record.get("subject_name")
|
| 510 |
+
if subject:
|
| 511 |
+
module_subjects[str(record.get("subjectId") or record.get("subject_id") or subject)] = str(subject)
|
| 512 |
+
enrollments = Counter()
|
| 513 |
+
progress_totals = Counter()
|
| 514 |
+
progress_counts = Counter()
|
| 515 |
+
for snapshot in classrooms:
|
| 516 |
+
record = snapshot.to_dict() or {}
|
| 517 |
+
subject_id = str(record.get("subjectId") or record.get("subject_id") or record.get("subject") or "")
|
| 518 |
+
subject_name = module_subjects.get(subject_id, str(record.get("subjectName") or record.get("subject") or subject_id))
|
| 519 |
+
roster = record.get("students") or record.get("studentIds") or []
|
| 520 |
+
enrolled = len(roster) if isinstance(roster, (list, dict)) else 0
|
| 521 |
+
if subject_name:
|
| 522 |
+
enrollments[subject_name] += enrolled
|
| 523 |
+
progress = record.get("averageProgress") or record.get("average_progress") or record.get("progress")
|
| 524 |
+
if isinstance(progress, (int, float)) and not isinstance(progress, bool):
|
| 525 |
+
progress_totals[subject_name] += max(0, min(100, progress))
|
| 526 |
+
progress_counts[subject_name] += 1
|
| 527 |
+
subject_breakdown = [
|
| 528 |
+
{
|
| 529 |
+
"name": name,
|
| 530 |
+
"type": "STEM" if "stem" in name.lower() else "Core",
|
| 531 |
+
"count": count,
|
| 532 |
+
"progress": round(progress_totals[name] / progress_counts[name]) if progress_counts[name] else 0,
|
| 533 |
+
}
|
| 534 |
+
for name, count in enrollments.most_common()
|
| 535 |
+
]
|
| 536 |
+
|
| 537 |
+
score_count = len(scores)
|
| 538 |
+
foundational = sum(score < 50 for score in scores)
|
| 539 |
+
intermediate = sum(50 <= score < 80 for score in scores)
|
| 540 |
+
advanced = sum(score >= 80 for score in scores)
|
| 541 |
+
distribution_total = score_count or 1
|
| 542 |
+
return {
|
| 543 |
+
"weeklyActivity": weekly,
|
| 544 |
+
"subjectBreakdown": subject_breakdown,
|
| 545 |
+
"priorityAttention": {
|
| 546 |
+
"subjectName": risk_subjects.most_common(1)[0][0] if risk_subjects else "General Mathematics",
|
| 547 |
+
"atRiskCount": len(at_risk_ids),
|
| 548 |
+
},
|
| 549 |
+
"globalMastery": {
|
| 550 |
+
"avgMastery": round(sum(scores) / score_count) if score_count else 0,
|
| 551 |
+
"passed": passed,
|
| 552 |
+
"pending": max(0, total_students - passed),
|
| 553 |
+
},
|
| 554 |
+
"difficultyDistribution": {
|
| 555 |
+
"foundational": round(foundational / distribution_total * 100),
|
| 556 |
+
"intermediate": round(intermediate / distribution_total * 100),
|
| 557 |
+
"advanced": round(advanced / distribution_total * 100),
|
| 558 |
+
},
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
@router.get("/school-analytics")
|
| 562 |
def get_school_analytics(request: Request):
|
| 563 |
"""School-wide WRI aggregation for admin dashboard."""
|