""" app/api/stats.py ---------------- Mobile API endpoint for dashboard statistics. GET /api/v1/stats/dashboard Returns inspector-scoped counts used by the iPad dashboard card: - today_inspections : inspections started or completed today - completed_today : completed inspections today - open_issues : open + in_progress issues in contracted facilities - avg_score_30d : average overall_score (last 30 days, own inspections) - pending_followups : completed inspections with follow_up_required and no child re-inspection yet - sla_breached : open/in-progress issues past their SLA deadline - sla_at_risk : open/in-progress issues past 75% of SLA window Admins and directors receive org-wide numbers (no facility scoping). Project managers receive unscoped numbers same as admin. Inspectors receive numbers scoped to their contracted facilities / own work. Customers are denied (403) — stats are for operational staff only. """ import logging from datetime import timedelta from flask import Blueprint, g from sqlalchemy import func from app import db from app.models.inspection import Inspection from app.models.issue import Issue from app.models.facility import Area from app.api.errors import api_ok, api_error from app.api.decorators import jwt_required from app.utils.scope import get_inspector_scope from app.utils.sla import sla_status from app.utils.time_utils import now_eastern logger = logging.getLogger(__name__) bp = Blueprint('api_stats', __name__) _ALLOWED_ROLES = {'admin', 'director', 'inspector', 'external_inspector', 'project_manager', 'auditor'} @bp.route('/stats/dashboard', methods=['GET']) @jwt_required def dashboard_stats(): """ Return dashboard KPI counts for the authenticated user. Response 200 ------------ { "ok": true, "data": { "today_inspections": 3, "completed_today": 2, "open_issues": 7, "avg_score_30d": 84.5, "pending_followups": 1, "sla_breached": 2, "sla_at_risk": 1 } } """ user = g.api_user if user.role not in _ALLOWED_ROLES: return api_error('Access denied', 403) now = now_eastern() today_start = now.replace(hour=0, minute=0, second=0, microsecond=0) today_end = today_start + timedelta(days=1) thirty_days_ago = now - timedelta(days=30) is_inspector = user.is_inspector fids = get_inspector_scope(user) if is_inspector else None # None = no scoping # ── Today's inspections ─────────────────────────────────────────────── today_q = Inspection.query.filter( Inspection.inspection_date >= today_start, Inspection.inspection_date < today_end, ) if is_inspector: if not fids: today_q = today_q.filter(False) else: today_q = today_q.filter( Inspection.facility_id.in_(fids), Inspection.inspector_id == user.id, ) today_inspections = today_q.count() completed_today = today_q.filter( Inspection.status == 'completed' ).count() # ── Open issues ─────────────────────────────────────────────────────── open_q = Issue.query.filter(Issue.status.in_(['open', 'in_progress'])) if is_inspector: if not fids: open_q = open_q.filter(False) else: open_q = open_q.outerjoin(Area, Issue.area_id == Area.id).filter( db.or_( Issue.facility_id.in_(fids), db.and_(Issue.area_id.isnot(None), Area.facility_id.in_(fids)), ) ) open_issues_all = open_q.all() open_issues = len(open_issues_all) # ── Severity breakdown (derived from the same open_issues_all list) ─── severity_breakdown = { 'critical': sum(1 for i in open_issues_all if i.severity == 'critical'), 'high': sum(1 for i in open_issues_all if i.severity == 'high'), 'medium': sum(1 for i in open_issues_all if i.severity == 'medium'), 'low': sum(1 for i in open_issues_all if i.severity == 'low'), } # ── SLA counts (derived from the same open_issues_all list) ────────── sla_breached = sum(1 for i in open_issues_all if sla_status(i) == 'breached') sla_at_risk = sum(1 for i in open_issues_all if sla_status(i) == 'at_risk') # ── Average score last 30 days ──────────────────────────────────────── score_q = db.session.query(func.avg(Inspection.overall_score)).filter( Inspection.status == 'completed', Inspection.overall_score.isnot(None), Inspection.inspection_date >= thirty_days_ago, ) if is_inspector: if not fids: score_q = score_q.filter(False) else: score_q = score_q.filter( Inspection.facility_id.in_(fids), Inspection.inspector_id == user.id, ) raw_avg = score_q.scalar() avg_score = round(float(raw_avg), 1) if raw_avg is not None else None # ── Pending follow-ups ──────────────────────────────────────────────── # Completed inspections that still need a re-inspection and have none yet. followup_q = Inspection.query.filter_by( follow_up_required=True, status='completed' ).filter(~Inspection.follow_ups.any()) if is_inspector: if not fids: followup_q = followup_q.filter(False) else: followup_q = followup_q.filter( Inspection.facility_id.in_(fids), Inspection.inspector_id == user.id, ) pending_followups = followup_q.count() logger.info( 'API STATS | dashboard | user=%s | role=%s | ' 'today=%d | open_issues=%d | avg=%.1f | followups=%d | sla_b=%d | sla_r=%d', user.username, user.role, today_inspections, open_issues, avg_score or 0.0, pending_followups, sla_breached, sla_at_risk, ) return api_ok({ 'today_inspections': today_inspections, 'completed_today': completed_today, 'open_issues': open_issues, 'avg_score_30d': avg_score, 'pending_followups': pending_followups, 'sla_breached': sla_breached, 'sla_at_risk': sla_at_risk, 'severity_breakdown': severity_breakdown, })