From cef72520146b3470ca53a39adc7df3cf5e96bdcf Mon Sep 17 00:00:00 2001 From: Nguyen Ngo Date: Wed, 27 May 2026 16:20:38 -0400 Subject: [PATCH] 05/27 Sync with iPad app (Phase B) --- app/__init__.py | 2 + app/api/__init__.py | 4 ++ app/api/stats.py | 169 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 app/api/stats.py diff --git a/app/__init__.py b/app/__init__.py index 6f7350b..c3aa335 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -161,6 +161,7 @@ def create_app(config_name='default'): from app.api.issues import bp as _api_issues_bp from app.api.photos import bp as _api_photos_bp from app.api.notifications import bp as _api_notifications_bp + from app.api.stats import bp as _api_stats_bp csrf.exempt(_api_auth_bp) csrf.exempt(_api_facilities_bp) csrf.exempt(_api_templates_bp) @@ -168,6 +169,7 @@ def create_app(config_name='default'): csrf.exempt(_api_issues_bp) csrf.exempt(_api_photos_bp) csrf.exempt(_api_notifications_bp) + csrf.exempt(_api_stats_bp) register_api(app) # ── Security response headers ───────────────────────────────────────── diff --git a/app/api/__init__.py b/app/api/__init__.py index d8469c2..0c0102e 100644 --- a/app/api/__init__.py +++ b/app/api/__init__.py @@ -42,4 +42,8 @@ def register_api(app): from app.api.notifications import bp as notifications_bp api_bp.register_blueprint(notifications_bp) + # Phase B (stats): Dashboard KPI endpoint + from app.api.stats import bp as stats_bp + api_bp.register_blueprint(stats_bp) + app.register_blueprint(api_bp) \ No newline at end of file diff --git a/app/api/stats.py b/app/api/stats.py new file mode 100644 index 0000000..b2db8dc --- /dev/null +++ b/app/api/stats.py @@ -0,0 +1,169 @@ +""" +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', 'project_manager'} + + +@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.role == '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) + + # ── 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, + })