First commit
This commit is contained in:
@@ -0,0 +1,427 @@
|
||||
import logging
|
||||
from flask import Blueprint, render_template
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.models.inspection import Inspection, InspectionTemplate
|
||||
from app.models.facility import Facility
|
||||
from app.models.issue import Issue
|
||||
from app.models.user import User
|
||||
from app.utils.sla import sla_status, SLA_HOURS
|
||||
from app.utils.scope import get_customer_scope, get_inspector_scope
|
||||
from sqlalchemy import func
|
||||
from datetime import datetime, timedelta
|
||||
from app.utils.time_utils import now_eastern
|
||||
|
||||
bp = Blueprint('dashboard', __name__)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@bp.route('/')
|
||||
@bp.route('/dashboard')
|
||||
@login_required
|
||||
def index():
|
||||
now = now_eastern()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
today_end = today_start + timedelta(days=1)
|
||||
|
||||
is_inspector = current_user.role == 'inspector'
|
||||
is_privileged = current_user.role in ['admin', 'director']
|
||||
is_customer = current_user.role == 'customer'
|
||||
is_project_manager = current_user.role == 'project_manager'
|
||||
|
||||
# Resolve facility scope
|
||||
customer_facility_ids = get_customer_scope(current_user) # None for non-customers
|
||||
inspector_facility_ids = get_inspector_scope(current_user) # None for non-inspectors
|
||||
|
||||
# ── Today's stats (inspector: own work within contracted facilities) ───
|
||||
base_q = Inspection.query
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
base_q = base_q.filter(False)
|
||||
else:
|
||||
base_q = base_q.filter(
|
||||
Inspection.facility_id.in_(inspector_facility_ids),
|
||||
Inspection.inspector_id == current_user.id,
|
||||
)
|
||||
elif is_customer:
|
||||
if not customer_facility_ids:
|
||||
base_q = base_q.filter(False) # no access
|
||||
else:
|
||||
base_q = base_q.filter(Inspection.facility_id.in_(customer_facility_ids))
|
||||
|
||||
today_inspections = base_q.filter(
|
||||
Inspection.inspection_date >= today_start,
|
||||
Inspection.inspection_date < today_end,
|
||||
).count()
|
||||
|
||||
completed_today = base_q.filter(
|
||||
Inspection.status == 'completed',
|
||||
Inspection.inspection_date >= today_start,
|
||||
Inspection.inspection_date < today_end,
|
||||
).count()
|
||||
|
||||
# ── Open issues (inspector: all issues in contracted facilities) ───────
|
||||
open_issues_q = Issue.query.filter(Issue.status.in_(['open', 'in_progress']))
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
open_issues_q = open_issues_q.filter(False)
|
||||
else:
|
||||
from app.models.facility import Area
|
||||
open_issues_q = open_issues_q.outerjoin(
|
||||
Area, Issue.area_id == Area.id
|
||||
).filter(db.or_(
|
||||
Issue.facility_id.in_(inspector_facility_ids),
|
||||
Area.facility_id.in_(inspector_facility_ids)
|
||||
))
|
||||
elif is_customer:
|
||||
if not customer_facility_ids:
|
||||
open_issues_q = open_issues_q.filter(False)
|
||||
else:
|
||||
from app.models.facility import Area
|
||||
open_issues_q = open_issues_q.outerjoin(
|
||||
Area, Issue.area_id == Area.id
|
||||
).filter(db.or_(
|
||||
Issue.facility_id.in_(customer_facility_ids),
|
||||
Area.facility_id.in_(customer_facility_ids)
|
||||
))
|
||||
|
||||
# Single query — derive count from the list to avoid hitting the DB twice
|
||||
open_issues_all = open_issues_q.all()
|
||||
open_issues = len(open_issues_all)
|
||||
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'),
|
||||
}
|
||||
|
||||
# ── Issues resolved today ─────────────────────────────────────────────────
|
||||
resolved_today_q = Issue.query.filter(
|
||||
Issue.status == 'resolved',
|
||||
Issue.resolved_at >= today_start,
|
||||
Issue.resolved_at < today_end,
|
||||
)
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
resolved_today_q = resolved_today_q.filter(False)
|
||||
else:
|
||||
from app.models.facility import Area as _Area
|
||||
resolved_today_q = resolved_today_q.outerjoin(
|
||||
_Area, Issue.area_id == _Area.id
|
||||
).filter(db.or_(
|
||||
Issue.facility_id.in_(inspector_facility_ids),
|
||||
_Area.facility_id.in_(inspector_facility_ids),
|
||||
))
|
||||
elif is_customer:
|
||||
if not customer_facility_ids:
|
||||
resolved_today_q = resolved_today_q.filter(False)
|
||||
else:
|
||||
from app.models.facility import Area as _Area
|
||||
resolved_today_q = resolved_today_q.outerjoin(
|
||||
_Area, Issue.area_id == _Area.id
|
||||
).filter(db.or_(
|
||||
Issue.facility_id.in_(customer_facility_ids),
|
||||
_Area.facility_id.in_(customer_facility_ids),
|
||||
))
|
||||
resolved_today = resolved_today_q.count()
|
||||
|
||||
# ── Recent inspections ─────────────────────────────────────────────────
|
||||
recent_q = Inspection.query.order_by(Inspection.inspection_date.desc())
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
recent_q = recent_q.filter(False)
|
||||
else:
|
||||
recent_q = recent_q.filter(
|
||||
Inspection.facility_id.in_(inspector_facility_ids),
|
||||
Inspection.inspector_id == current_user.id,
|
||||
)
|
||||
elif is_customer:
|
||||
if customer_facility_ids:
|
||||
recent_q = recent_q.filter(Inspection.facility_id.in_(customer_facility_ids))
|
||||
else:
|
||||
recent_q = recent_q.filter(False)
|
||||
recent_inspections = recent_q.limit(5).all()
|
||||
|
||||
# ── Pending follow-up inspections ────────────────────────────────────
|
||||
# follow_ups is a lazy='dynamic' relationship — comparing it to None does
|
||||
# NOT produce a "has no rows" predicate for dynamic relationships. The
|
||||
# correct idiom is ~.any(), which generates EXISTS (SELECT 1 FROM inspections
|
||||
# WHERE parent_inspection_id = inspections.id). This matches the identical
|
||||
# filter used in routes/inspections.py:follow_up_filter.
|
||||
followup_q = Inspection.query.filter_by(
|
||||
follow_up_required=True, status='completed'
|
||||
).filter(~Inspection.follow_ups.any())
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
followup_q = followup_q.filter(False)
|
||||
else:
|
||||
followup_q = followup_q.filter(
|
||||
Inspection.facility_id.in_(inspector_facility_ids),
|
||||
Inspection.inspector_id == current_user.id,
|
||||
)
|
||||
elif is_customer:
|
||||
if customer_facility_ids:
|
||||
followup_q = followup_q.filter(Inspection.facility_id.in_(customer_facility_ids))
|
||||
else:
|
||||
followup_q = followup_q.filter(False)
|
||||
pending_followups = followup_q.count()
|
||||
|
||||
# ── System stats (admin/director) ────────────────────────────────────────
|
||||
total_facilities = Facility.query.filter_by(active=True).count() if is_privileged else 0
|
||||
total_templates = InspectionTemplate.query.count() if is_privileged else 0
|
||||
total_users = User.query.count() if current_user.role == 'admin' else 0
|
||||
|
||||
# ── Customer: scoped facilities summary ───────────────────────────────
|
||||
customer_facilities = []
|
||||
if is_customer and customer_facility_ids:
|
||||
customer_facilities = Facility.query.filter(
|
||||
Facility.id.in_(customer_facility_ids),
|
||||
Facility.active == True,
|
||||
).order_by(Facility.name).all()
|
||||
|
||||
# ── SLA summary (open + in_progress issues, scoped) ───────────────────
|
||||
sla_q = Issue.query.filter(Issue.status.in_(['open', 'in_progress']))
|
||||
if is_inspector and inspector_facility_ids:
|
||||
from app.models.facility import Area
|
||||
sla_q = sla_q.outerjoin(Area, Issue.area_id == Area.id).filter(
|
||||
db.or_(
|
||||
Issue.facility_id.in_(inspector_facility_ids),
|
||||
Area.facility_id.in_(inspector_facility_ids)
|
||||
)
|
||||
)
|
||||
elif is_customer and customer_facility_ids:
|
||||
from app.models.facility import Area
|
||||
sla_q = sla_q.outerjoin(Area, Issue.area_id == Area.id).filter(
|
||||
db.or_(
|
||||
Issue.facility_id.in_(customer_facility_ids),
|
||||
Area.facility_id.in_(customer_facility_ids)
|
||||
)
|
||||
)
|
||||
if is_inspector and not inspector_facility_ids:
|
||||
all_open_issues = []
|
||||
elif is_customer and not customer_facility_ids:
|
||||
all_open_issues = []
|
||||
else:
|
||||
all_open_issues = sla_q.all()
|
||||
sla_breached = sum(1 for i in all_open_issues if sla_status(i) == 'breached')
|
||||
sla_at_risk = sum(1 for i in all_open_issues if sla_status(i) == 'at_risk')
|
||||
|
||||
# ── Issues opened today ───────────────────────────────────────────────────
|
||||
from app.models.facility import Area as _AreaT
|
||||
opened_today_q = Issue.query.outerjoin(_AreaT, Issue.area_id == _AreaT.id).filter(
|
||||
Issue.reported_at >= today_start,
|
||||
Issue.reported_at < today_end,
|
||||
)
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
opened_today_q = opened_today_q.filter(False)
|
||||
else:
|
||||
opened_today_q = opened_today_q.filter(db.or_(
|
||||
Issue.facility_id.in_(inspector_facility_ids),
|
||||
_AreaT.facility_id.in_(inspector_facility_ids),
|
||||
))
|
||||
elif is_customer:
|
||||
if not customer_facility_ids:
|
||||
opened_today_q = opened_today_q.filter(False)
|
||||
else:
|
||||
opened_today_q = opened_today_q.filter(db.or_(
|
||||
Issue.facility_id.in_(customer_facility_ids),
|
||||
_AreaT.facility_id.in_(customer_facility_ids),
|
||||
))
|
||||
issues_opened_today = opened_today_q.count()
|
||||
|
||||
# ── Pending verification ──────────────────────────────────────────────────
|
||||
from app.models.facility import Area as _AreaV
|
||||
pv_q = Issue.query.outerjoin(_AreaV, Issue.area_id == _AreaV.id).filter(
|
||||
Issue.status == 'pending_verification',
|
||||
)
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
pv_q = pv_q.filter(False)
|
||||
else:
|
||||
pv_q = pv_q.filter(db.or_(
|
||||
Issue.facility_id.in_(inspector_facility_ids),
|
||||
_AreaV.facility_id.in_(inspector_facility_ids),
|
||||
))
|
||||
elif is_customer:
|
||||
if not customer_facility_ids:
|
||||
pv_q = pv_q.filter(False)
|
||||
else:
|
||||
pv_q = pv_q.filter(db.or_(
|
||||
Issue.facility_id.in_(customer_facility_ids),
|
||||
_AreaV.facility_id.in_(customer_facility_ids),
|
||||
))
|
||||
pending_verification = pv_q.count()
|
||||
|
||||
# ── Stale in-progress inspections (started > 24h ago, not yet submitted) ──
|
||||
stale_cutoff = now - timedelta(hours=24)
|
||||
stale_q = Inspection.query.filter(
|
||||
Inspection.status == 'in_progress',
|
||||
Inspection.inspection_date < stale_cutoff,
|
||||
)
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
stale_q = stale_q.filter(False)
|
||||
else:
|
||||
stale_q = stale_q.filter(
|
||||
Inspection.facility_id.in_(inspector_facility_ids),
|
||||
Inspection.inspector_id == current_user.id,
|
||||
)
|
||||
elif is_customer:
|
||||
if customer_facility_ids:
|
||||
stale_q = stale_q.filter(Inspection.facility_id.in_(customer_facility_ids))
|
||||
else:
|
||||
stale_q = stale_q.filter(False)
|
||||
stale_in_progress = stale_q.count()
|
||||
|
||||
# ── Unassigned open issues ────────────────────────────────────────────────
|
||||
from app.models.facility import Area as _AreaU
|
||||
unassigned_q = Issue.query.outerjoin(_AreaU, Issue.area_id == _AreaU.id).filter(
|
||||
Issue.status.in_(['open', 'in_progress']),
|
||||
Issue.assigned_to.is_(None),
|
||||
)
|
||||
if is_inspector:
|
||||
if not inspector_facility_ids:
|
||||
unassigned_q = unassigned_q.filter(False)
|
||||
else:
|
||||
unassigned_q = unassigned_q.filter(db.or_(
|
||||
Issue.facility_id.in_(inspector_facility_ids),
|
||||
_AreaU.facility_id.in_(inspector_facility_ids),
|
||||
))
|
||||
elif is_customer:
|
||||
unassigned_q = unassigned_q.filter(False) # not relevant for customers
|
||||
unassigned_open = unassigned_q.count()
|
||||
|
||||
# ── Inspector activity today (admin / director / PM only) ─────────────────
|
||||
inspector_activity = []
|
||||
if is_privileged or is_project_manager:
|
||||
active_inspectors = (
|
||||
User.query
|
||||
.filter_by(role='inspector', active=True)
|
||||
.order_by(User.full_name, User.username)
|
||||
.all()
|
||||
)
|
||||
today_counts = dict(
|
||||
db.session.query(
|
||||
Inspection.inspector_id,
|
||||
func.count(Inspection.id),
|
||||
)
|
||||
.filter(
|
||||
Inspection.status == 'completed',
|
||||
Inspection.inspection_date >= today_start,
|
||||
Inspection.inspection_date < today_end,
|
||||
)
|
||||
.group_by(Inspection.inspector_id)
|
||||
.all()
|
||||
)
|
||||
inspector_activity = sorted(
|
||||
[{'name': u.display_name, 'count': today_counts.get(u.id, 0)}
|
||||
for u in active_inspectors],
|
||||
key=lambda x: (-x['count'], x['name']),
|
||||
)
|
||||
|
||||
# ── My open issues (inspector dashboard widget) ───────────────────────────
|
||||
# Issues assigned to the current inspector that are not yet resolved,
|
||||
# ordered by SLA urgency (breached first, then at-risk, then ok).
|
||||
my_issues = []
|
||||
if is_inspector:
|
||||
my_issues = (
|
||||
Issue.query
|
||||
.filter(
|
||||
Issue.assigned_to == current_user.id,
|
||||
Issue.status.in_(['open', 'in_progress']),
|
||||
)
|
||||
.order_by(Issue.reported_at.asc())
|
||||
.limit(10)
|
||||
.all()
|
||||
)
|
||||
|
||||
return render_template(
|
||||
'dashboard.html',
|
||||
today_inspections = today_inspections,
|
||||
completed_today = completed_today,
|
||||
open_issues = open_issues,
|
||||
severity_breakdown = severity_breakdown,
|
||||
resolved_today = resolved_today,
|
||||
pending_followups = pending_followups,
|
||||
issues_opened_today = issues_opened_today,
|
||||
pending_verification = pending_verification,
|
||||
stale_in_progress = stale_in_progress,
|
||||
unassigned_open = unassigned_open,
|
||||
inspector_activity = inspector_activity,
|
||||
recent_inspections = recent_inspections,
|
||||
total_facilities = total_facilities,
|
||||
total_templates = total_templates,
|
||||
total_users = total_users,
|
||||
sla_breached = sla_breached,
|
||||
sla_at_risk = sla_at_risk,
|
||||
customer_facilities = customer_facilities,
|
||||
my_issues = my_issues,
|
||||
today_str = now.strftime('%Y-%m-%d'),
|
||||
)
|
||||
|
||||
|
||||
# ── AJAX: facility score trend ────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/facility-trend')
|
||||
@login_required
|
||||
def facility_trend():
|
||||
"""Return daily avg-score data for a single facility over N days.
|
||||
|
||||
Query params:
|
||||
facility_id (int, required)
|
||||
days (int, default 30 — allowed: 30, 60, 90)
|
||||
|
||||
Response JSON:
|
||||
{ labels: ['2026-03-01', ...], data: [85.2, ...], facility: 'Name' }
|
||||
"""
|
||||
from flask import jsonify, request as req
|
||||
|
||||
facility_id = req.args.get('facility_id', type=int)
|
||||
days = req.args.get('days', 30, type=int)
|
||||
if days not in (30, 60, 90):
|
||||
days = 30
|
||||
|
||||
if not facility_id:
|
||||
return jsonify({'labels': [], 'data': [], 'facility': ''})
|
||||
|
||||
# Scope check for customer users
|
||||
if current_user.role == 'customer':
|
||||
cids = get_customer_scope(current_user) or []
|
||||
if facility_id not in cids:
|
||||
return jsonify({'labels': [], 'data': [], 'facility': ''}), 403
|
||||
|
||||
facility = db.session.get(Facility, facility_id)
|
||||
if not facility:
|
||||
return jsonify({'labels': [], 'data': [], 'facility': ''})
|
||||
|
||||
start = now_eastern() - timedelta(days=days)
|
||||
|
||||
rows = (
|
||||
db.session.query(
|
||||
func.date(Inspection.inspection_date).label('day'),
|
||||
func.avg(Inspection.overall_score).label('avg'),
|
||||
)
|
||||
.filter(
|
||||
Inspection.facility_id == facility_id,
|
||||
Inspection.status == 'completed',
|
||||
Inspection.overall_score.isnot(None),
|
||||
Inspection.inspection_date >= start,
|
||||
)
|
||||
.group_by(func.date(Inspection.inspection_date))
|
||||
.order_by(func.date(Inspection.inspection_date))
|
||||
.all()
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'labels': [str(r.day) for r in rows],
|
||||
'data': [round(float(r.avg), 2) for r in rows],
|
||||
'facility': facility.name,
|
||||
})
|
||||
|
||||
|
||||
@bp.route('/support')
|
||||
def support():
|
||||
"""Public support page — no login required. Used as App Store Connect Support URL."""
|
||||
return render_template('support.html', current_year=datetime.utcnow().year)
|
||||
Reference in New Issue
Block a user