472 lines
20 KiB
Python
472 lines
20 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__)
|
|
|
|
|
|
def _handler_split(issues):
|
|
"""Count a list of Issues by handler_type (phase35). Rows default to
|
|
'internal' when unset. Returns a dict keyed internal/facility/vendor."""
|
|
return {
|
|
'internal': sum(1 for i in issues if (i.handler_type or 'internal') == 'internal'),
|
|
'facility': sum(1 for i in issues if i.handler_type == 'facility'),
|
|
'vendor': sum(1 for i in issues if i.handler_type == 'vendor'),
|
|
}
|
|
|
|
|
|
@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)
|
|
# Start of the current week (Monday 00:00) for the "Submitted This Week" card.
|
|
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))
|
|
|
|
completed_today = base_q.filter(
|
|
Inspection.status == 'completed',
|
|
Inspection.inspection_date >= today_start,
|
|
Inspection.inspection_date < today_end,
|
|
).count()
|
|
|
|
# Fully completed & submitted so far this week (Monday → now).
|
|
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.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'),
|
|
}
|
|
# Open issues split by who handles them (phase35) — same list, no extra query.
|
|
handler_breakdown = _handler_split(open_issues_all)
|
|
|
|
# ── 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.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),
|
|
))
|
|
opened_today_all = opened_today_q.all()
|
|
issues_opened_today = len(opened_today_all)
|
|
opened_today_handler = _handler_split(opened_today_all)
|
|
|
|
# ── 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, not just stale) — "In Progress" tile ─────
|
|
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_all = unassigned_q.all()
|
|
unassigned_open = len(unassigned_all)
|
|
unassigned_handler = _handler_split(unassigned_all)
|
|
|
|
# ── 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 (phase36): upcoming / overdue ──────────────
|
|
sched_upcoming = []
|
|
sched_overdue_count = 0
|
|
sched_total = 0
|
|
sched_open_inspections = {}
|
|
if not is_customer:
|
|
from app.models.scheduled_inspection import ScheduledInspection
|
|
from app.routes.scheduled_inspections import _open_inspection_ids
|
|
_today = now.date()
|
|
_sq = ScheduledInspection.query.filter_by(active=True)
|
|
if is_inspector:
|
|
_sq = _sq.filter(ScheduledInspection.inspector_id == current_user.id)
|
|
_all_sched = _sq.order_by(ScheduledInspection.next_due_date.asc()).all()
|
|
sched_total = len(_all_sched) # active scheduled inspection plans ("On Schedules")
|
|
sched_overdue_count = sum(1 for s in _all_sched if s.next_due_date < _today)
|
|
# Upcoming = due today through the next 7 days (overdue shown separately)
|
|
sched_upcoming = [
|
|
s for s in _all_sched
|
|
if _today <= s.next_due_date <= _today + timedelta(days=7)
|
|
][:8]
|
|
# Offer Continue (not a duplicate Start) where one is already underway.
|
|
sched_open_inspections = _open_inspection_ids(sched_upcoming)
|
|
|
|
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,
|
|
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,
|
|
opened_today_handler = opened_today_handler,
|
|
pending_verification = pending_verification,
|
|
stale_in_progress = stale_in_progress,
|
|
unassigned_open = unassigned_open,
|
|
unassigned_handler = unassigned_handler,
|
|
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'),
|
|
week_start_str = week_start.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) |