533 lines
23 KiB
Python
533 lines
23 KiB
Python
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__)
|
|
|
|
|
|
# Columns the dashboard actually reads off an issue row. The cards below need
|
|
# counts and buckets, never a hydrated Issue — loading the full entity pulls the
|
|
# description TEXT and three JSON photo columns for every open issue in scope,
|
|
# on every dashboard load, and registers each one in the identity map.
|
|
# A Row exposes the same attribute names, so the severity/handler tallies and
|
|
# sla_status() work against these unchanged.
|
|
_ISSUE_CARD_COLS = (Issue.id, Issue.severity, Issue.status,
|
|
Issue.reported_at, Issue.handler_type)
|
|
|
|
|
|
@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)
|
|
# MT-16 — Monday 00:00 of the current week, for the modern dashboard's
|
|
# "submitted this week" tile. Derived from today_start so it inherits
|
|
# now_eastern() rather than mixing in a second clock.
|
|
week_start = today_start - timedelta(days=today_start.weekday())
|
|
|
|
is_inspector = current_user.is_inspector
|
|
is_privileged = current_user.role in ['admin', 'director']
|
|
is_customer = current_user.role == 'customer'
|
|
is_project_manager = current_user.role == 'project_manager'
|
|
is_auditor = current_user.role == 'auditor'
|
|
|
|
# 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()
|
|
|
|
# MT-16 — fully completed & submitted so far this week (Monday → now).
|
|
# Reuses base_q, so it inherits the same role scoping as every other tile.
|
|
submitted_this_week = base_q.filter(
|
|
Inspection.status == 'completed',
|
|
Inspection.inspection_date >= week_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.with_entities(*_ISSUE_CARD_COLS).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'),
|
|
}
|
|
# Handler breakdown (phase39) — NULL and 'internal' both mean janitorial staff
|
|
handler_breakdown = {
|
|
'internal': sum(1 for i in open_issues_all if not i.handler_type or i.handler_type == 'internal'),
|
|
'facility': sum(1 for i in open_issues_all if i.handler_type == 'facility'),
|
|
'vendor': sum(1 for i in open_issues_all if i.handler_type == 'vendor'),
|
|
}
|
|
|
|
# ── 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:
|
|
# OWNERSHIP, not authorship — see Inspection.follow_up_owned_by().
|
|
# An assigned follow-up lives on an inspection somebody else
|
|
# performed, so testing inspector_id made the card read 0 for the
|
|
# very person who had been asked to do the work.
|
|
followup_q = followup_q.filter(
|
|
Inspection.facility_id.in_(inspector_facility_ids),
|
|
Inspection.follow_up_owned_by(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.with_entities(*_ISSUE_CARD_COLS).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()
|
|
|
|
# ── In-progress inspections, all ages (MT-16) ─────────────────────────────
|
|
# stale_in_progress above counts only those older than 24h. The modern
|
|
# dashboard shows the full in-progress count as its own tile, so this is a
|
|
# separate query with the SAME role scoping rather than a reuse of stale_q.
|
|
inprog_q = Inspection.query.filter(Inspection.status == 'in_progress')
|
|
if is_inspector:
|
|
if not inspector_facility_ids:
|
|
inprog_q = inprog_q.filter(False)
|
|
else:
|
|
inprog_q = inprog_q.filter(
|
|
Inspection.facility_id.in_(inspector_facility_ids),
|
|
Inspection.inspector_id == current_user.id,
|
|
)
|
|
elif is_customer:
|
|
if customer_facility_ids:
|
|
inprog_q = inprog_q.filter(Inspection.facility_id.in_(customer_facility_ids))
|
|
else:
|
|
inprog_q = inprog_q.filter(False)
|
|
in_progress_total = inprog_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 / auditor only) ───────
|
|
inspector_activity = []
|
|
if is_privileged or is_project_manager or is_auditor:
|
|
active_inspectors = (
|
|
User.query
|
|
.filter(User.role.in_(User.INSPECTOR_ROLES), User.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()
|
|
)
|
|
|
|
# ── Scheduled inspections (phase43): upcoming / overdue ───────────────────
|
|
# Plan-mode only: 'auto' schedules materialise themselves into the
|
|
# inspections list, so surfacing them here would double-report the work.
|
|
sched_upcoming = []
|
|
sched_overdue_count = 0
|
|
# MT-16 — the modern dashboard additionally shows the total number of active
|
|
# plans ("On Schedules") and offers Continue instead of a duplicate Start
|
|
# where an inspection is already underway for that plan.
|
|
sched_total = 0
|
|
sched_open_inspections = {}
|
|
if not is_customer:
|
|
from app.models.inspection_schedule import InspectionSchedule
|
|
_today = now_eastern().date()
|
|
_sq = InspectionSchedule.query.filter(
|
|
InspectionSchedule.active.is_(True),
|
|
InspectionSchedule.mode == 'plan',
|
|
)
|
|
if is_inspector:
|
|
_sq = _sq.filter(InspectionSchedule.inspector_id == current_user.id)
|
|
_all_sched = _sq.order_by(InspectionSchedule.next_run_at.asc()).all()
|
|
sched_overdue_count = sum(1 for s in _all_sched if s.is_overdue(_today))
|
|
# Upcoming = due today through the next 7 days (overdue shown separately)
|
|
sched_upcoming = [
|
|
s for s in _all_sched
|
|
if s.next_run_at and _today <= s.next_run_at.date() <= _today + timedelta(days=7)
|
|
][:8]
|
|
sched_total = len(_all_sched) # active plan-mode schedules
|
|
# {schedule_id: inspection_id} for plans with an inspection already in
|
|
# progress. MT's FK is Inspection.inspection_schedule_id (ST calls it
|
|
# scheduled_inspection_id). Ordered ascending so that when a plan somehow
|
|
# has more than one open inspection, the dict keeps the LOWEST id — the
|
|
# original, not a later duplicate.
|
|
_sched_ids = [s.id for s in sched_upcoming if s.id]
|
|
if _sched_ids:
|
|
_open_rows = (
|
|
Inspection.query
|
|
.filter(Inspection.inspection_schedule_id.in_(_sched_ids),
|
|
Inspection.status == 'in_progress')
|
|
.order_by(Inspection.id.desc())
|
|
.all()
|
|
)
|
|
sched_open_inspections = {
|
|
r.inspection_schedule_id: r.id for r in _open_rows
|
|
}
|
|
|
|
return render_template(
|
|
'dashboard.html',
|
|
sched_upcoming = sched_upcoming,
|
|
sched_overdue_count = sched_overdue_count,
|
|
sched_total = sched_total,
|
|
sched_open_inspections = sched_open_inspections,
|
|
in_progress_total = in_progress_total,
|
|
submitted_this_week = submitted_this_week,
|
|
week_start_str = week_start.strftime('%Y-%m-%d'),
|
|
today_inspections = today_inspections,
|
|
completed_today = completed_today,
|
|
open_issues = open_issues,
|
|
severity_breakdown = severity_breakdown,
|
|
handler_breakdown = handler_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) |