Mar 04 2026: Implement some operational features: scheduled reports, issue resolution verification, etc - Phase 6
This commit is contained in:
@@ -94,6 +94,19 @@ def index():
|
||||
recent_q = recent_q.filter(False)
|
||||
recent_inspections = recent_q.limit(5).all()
|
||||
|
||||
# ── Pending follow-up inspections ────────────────────────────────────
|
||||
followup_q = Inspection.query.filter_by(
|
||||
follow_up_required=True, status='completed'
|
||||
).filter(Inspection.follow_ups == None) # noqa: E711 — SQLAlchemy usage
|
||||
if is_inspector:
|
||||
followup_q = followup_q.filter(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/supervisor) ───────────────────────────────────
|
||||
total_facilities = Facility.query.filter_by(active=True).count() if is_privileged else 0
|
||||
total_templates = InspectionTemplate.query.count() if is_privileged else 0
|
||||
@@ -183,4 +196,5 @@ def index():
|
||||
trend_data = trend_data,
|
||||
facility_perf = facility_perf,
|
||||
customer_facilities = customer_facilities,
|
||||
pending_followups = pending_followups,
|
||||
)
|
||||
|
||||
+95
-10
@@ -191,12 +191,18 @@ def index():
|
||||
else:
|
||||
q = q.filter(Inspection.facility_id.in_(customer_facility_ids))
|
||||
|
||||
status_filter = request.args.get('status', '')
|
||||
facility_filter = request.args.get('facility_id', '')
|
||||
status_filter = request.args.get('status', '')
|
||||
facility_filter = request.args.get('facility_id', '')
|
||||
follow_up_filter = request.args.get('follow_up', '')
|
||||
if status_filter:
|
||||
q = q.filter(Inspection.status == status_filter)
|
||||
if facility_filter.isdigit():
|
||||
q = q.filter(Inspection.facility_id == int(facility_filter))
|
||||
if follow_up_filter == '1':
|
||||
q = q.filter(
|
||||
Inspection.follow_up_required == True,
|
||||
Inspection.status == 'completed',
|
||||
).filter(~Inspection.follow_ups.any())
|
||||
|
||||
inspections = q.paginate(page=page, per_page=20, error_out=False)
|
||||
if current_user.role == 'customer':
|
||||
@@ -209,7 +215,8 @@ def index():
|
||||
inspections=inspections,
|
||||
facilities=facilities,
|
||||
status_filter=status_filter,
|
||||
facility_filter=facility_filter)
|
||||
facility_filter=facility_filter,
|
||||
follow_up_filter=follow_up_filter)
|
||||
|
||||
|
||||
# ── Start ─────────────────────────────────────────────────────────────────────
|
||||
@@ -225,6 +232,14 @@ def start():
|
||||
form.template_id.choices = [(t.id, t.name) for t in templates]
|
||||
form.facility_id.choices = [(f.id, f.name) for f in facilities]
|
||||
|
||||
# Pre-select template/facility when arriving from reinspect()
|
||||
from flask import session as _session
|
||||
if not form.is_submitted():
|
||||
if _session.get('reinspect_template_id'):
|
||||
form.template_id.data = _session['reinspect_template_id']
|
||||
if _session.get('reinspect_facility_id'):
|
||||
form.facility_id.data = _session['reinspect_facility_id']
|
||||
|
||||
selected_fid = form.facility_id.data or (facilities[0].id if facilities else None)
|
||||
areas = Area.query.filter_by(facility_id=selected_fid).order_by(Area.name).all() if selected_fid else []
|
||||
form.area_id.choices = [(0, '— No specific area —')] + [(a.id, a.name) for a in areas]
|
||||
@@ -237,14 +252,17 @@ def start():
|
||||
flash('This template has no form fields yet. Please build the form in the template editor first.', 'warning')
|
||||
return redirect(url_for('inspections.start'))
|
||||
|
||||
from flask import session as _session
|
||||
parent_id = _session.pop('reinspect_parent_id', None)
|
||||
inspection = Inspection(
|
||||
template_id = template.id,
|
||||
facility_id = form.facility_id.data,
|
||||
area_id = form.area_id.data or None,
|
||||
inspector_id = current_user.id,
|
||||
inspection_date = now_eastern(),
|
||||
status = 'in_progress',
|
||||
notes = form.notes.data or None,
|
||||
template_id = template.id,
|
||||
facility_id = form.facility_id.data,
|
||||
area_id = form.area_id.data or None,
|
||||
inspector_id = current_user.id,
|
||||
inspection_date = now_eastern(),
|
||||
status = 'in_progress',
|
||||
notes = form.notes.data or None,
|
||||
parent_inspection_id = parent_id,
|
||||
)
|
||||
db.session.add(inspection)
|
||||
db.session.commit()
|
||||
@@ -642,6 +660,73 @@ def export_pdf(inspection_id):
|
||||
)
|
||||
|
||||
|
||||
# ── Flag / clear follow-up required ──────────────────────────────────────────
|
||||
|
||||
@bp.route('/<int:inspection_id>/flag-followup', methods=['POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def flag_followup(inspection_id):
|
||||
"""Mark an inspection as requiring a follow-up re-inspection."""
|
||||
inspection = Inspection.query.get_or_404(inspection_id)
|
||||
note = request.form.get('follow_up_note', '').strip() or None
|
||||
|
||||
inspection.follow_up_required = True
|
||||
inspection.follow_up_note = note
|
||||
db.session.commit()
|
||||
|
||||
current_app.logger.info(
|
||||
'INSPECTION FOLLOW-UP FLAGGED | id=%s | by=%s | note=%r',
|
||||
inspection_id, current_user.username, note,
|
||||
)
|
||||
log_action(ACTION_UPDATE, 'Inspection', inspection_id,
|
||||
f'{inspection.template.name} @ {inspection.facility.name}',
|
||||
f'follow_up_required=True; note={note!r}')
|
||||
flash('Follow-up inspection required flag set.', 'warning')
|
||||
return redirect(url_for('inspections.view', inspection_id=inspection_id))
|
||||
|
||||
|
||||
@bp.route('/<int:inspection_id>/clear-followup', methods=['POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def clear_followup(inspection_id):
|
||||
"""Clear the follow-up required flag once actioned."""
|
||||
inspection = Inspection.query.get_or_404(inspection_id)
|
||||
inspection.follow_up_required = False
|
||||
inspection.follow_up_note = None
|
||||
db.session.commit()
|
||||
log_action(ACTION_UPDATE, 'Inspection', inspection_id,
|
||||
f'{inspection.template.name} @ {inspection.facility.name}',
|
||||
'follow_up_required=False (cleared)')
|
||||
flash('Follow-up flag cleared.', 'success')
|
||||
return redirect(url_for('inspections.view', inspection_id=inspection_id))
|
||||
|
||||
|
||||
# ── Start a re-inspection (linked to parent) ──────────────────────────────────
|
||||
|
||||
@bp.route('/<int:inspection_id>/reinspect')
|
||||
@login_required
|
||||
def reinspect(inspection_id):
|
||||
"""Pre-fill the Start Inspection form with the same template/facility,
|
||||
linking the new inspection to the parent via parent_inspection_id."""
|
||||
from flask import session
|
||||
parent = Inspection.query.get_or_404(inspection_id)
|
||||
|
||||
if current_user.role == 'customer':
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('inspections.index'))
|
||||
|
||||
# Store parent context in session so start() can pick it up
|
||||
session['reinspect_parent_id'] = parent.id
|
||||
session['reinspect_template_id'] = parent.template_id
|
||||
session['reinspect_facility_id'] = parent.facility_id
|
||||
flash(
|
||||
f'Starting re-inspection of #{parent.id} — '
|
||||
f'{parent.template.name} @ {parent.facility.name}.',
|
||||
'info',
|
||||
)
|
||||
return redirect(url_for('inspections.start'))
|
||||
|
||||
|
||||
# ── Delete ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/<int:inspection_id>/delete', methods=['POST'])
|
||||
|
||||
@@ -117,6 +117,14 @@ def view(issue_id):
|
||||
form.assigned_to.choices = [(0, '— Unassigned —')] + [(u.id, u.username) for u in staff]
|
||||
form.status.data = form.status.data or issue.status
|
||||
|
||||
# Extend status choices to include pending_verification
|
||||
form.status.choices = [
|
||||
('open', 'Open'),
|
||||
('in_progress', 'In Progress'),
|
||||
('pending_verification', 'Pending Verification'),
|
||||
('resolved', 'Resolved'),
|
||||
]
|
||||
|
||||
if form.validate_on_submit():
|
||||
old_status = issue.status
|
||||
old_assigned_to = issue.assigned_to
|
||||
@@ -416,4 +424,96 @@ def create():
|
||||
flash('Issue created.', 'success')
|
||||
return redirect(url_for('issues.index'))
|
||||
|
||||
|
||||
# ── Supervisor verify resolved issue ─────────────────────────────────────────
|
||||
|
||||
@bp.route('/<int:issue_id>/verify', methods=['POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def verify(issue_id):
|
||||
"""Supervisor sign-off: confirms resolution is satisfactory and closes the issue."""
|
||||
issue = Issue.query.get_or_404(issue_id)
|
||||
|
||||
if issue.status not in ('resolved', 'pending_verification'):
|
||||
flash('Only resolved or pending-verification issues can be verified.', 'warning')
|
||||
return redirect(url_for('issues.view', issue_id=issue_id))
|
||||
|
||||
note = request.form.get('verification_note', '').strip() or None
|
||||
|
||||
issue.status = 'resolved'
|
||||
issue.verified_by = current_user.id
|
||||
issue.verified_at = now_eastern()
|
||||
issue.verification_note = note
|
||||
if not issue.resolved_at:
|
||||
issue.resolved_at = now_eastern()
|
||||
|
||||
db.session.commit()
|
||||
current_app.logger.info(
|
||||
'ISSUE VERIFIED | id=%s | by=%s | note=%r',
|
||||
issue_id, current_user.username, note,
|
||||
)
|
||||
log_action(ACTION_UPDATE, 'Issue', issue_id,
|
||||
f'#{issue_id} in {issue.area.name}',
|
||||
f'verified_by={current_user.username}')
|
||||
flash(f'Issue #{issue_id} verified and closed.', 'success')
|
||||
return redirect(url_for('issues.view', issue_id=issue_id))
|
||||
|
||||
|
||||
@bp.route('/<int:issue_id>/request-verification', methods=['POST'])
|
||||
@login_required
|
||||
def request_verification(issue_id):
|
||||
"""Inspector/assignee marks the issue as pending supervisor verification."""
|
||||
issue = Issue.query.get_or_404(issue_id)
|
||||
|
||||
if current_user.role == 'customer':
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('issues.index'))
|
||||
|
||||
# Only the assignee, supervisor, or admin can request verification
|
||||
can_act = (
|
||||
current_user.role in ['admin', 'supervisor']
|
||||
or issue.assigned_to == current_user.id
|
||||
)
|
||||
if not can_act:
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('issues.view', issue_id=issue_id))
|
||||
|
||||
if issue.status not in ('in_progress', 'resolved'):
|
||||
flash('Issue must be in progress or resolved to request verification.', 'warning')
|
||||
return redirect(url_for('issues.view', issue_id=issue_id))
|
||||
|
||||
issue.status = 'pending_verification'
|
||||
db.session.commit()
|
||||
|
||||
current_app.logger.info(
|
||||
'ISSUE VERIFICATION REQUESTED | id=%s | by=%s',
|
||||
issue_id, current_user.username,
|
||||
)
|
||||
log_action(ACTION_UPDATE, 'Issue', issue_id,
|
||||
f'#{issue_id} in {issue.area.name}',
|
||||
f'status=pending_verification; requested_by={current_user.username}')
|
||||
|
||||
# Notify supervisors
|
||||
from app.utils.notifications import notify
|
||||
from app.models.notification import EVENT_ISSUE_STATUS
|
||||
supervisors = User.query.filter(User.role.in_(['admin', 'supervisor'])).all()
|
||||
for sup in supervisors:
|
||||
if sup.id != current_user.id:
|
||||
notify(
|
||||
recipient = sup,
|
||||
title = f'Issue #{issue_id} Awaiting Verification',
|
||||
body = (
|
||||
f'{current_user.username} has marked Issue #{issue_id} '
|
||||
f'({issue.severity.title()} severity) in {issue.area.name} '
|
||||
f'as pending your verification.'
|
||||
),
|
||||
link = url_for('issues.view', issue_id=issue_id),
|
||||
issue_id = issue_id,
|
||||
event_type = EVENT_ISSUE_STATUS,
|
||||
send_email = True,
|
||||
)
|
||||
db.session.commit()
|
||||
flash('Issue marked as pending verification. Supervisors have been notified.', 'info')
|
||||
return redirect(url_for('issues.view', issue_id=issue_id))
|
||||
|
||||
return render_template('issues/form.html', form=form, title='Log New Issue')
|
||||
@@ -220,6 +220,134 @@ def facility_report(facility_id):
|
||||
start=start, end=end)
|
||||
|
||||
|
||||
|
||||
# ── Facility Scorecard ────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/facility/<int:facility_id>/scorecard')
|
||||
@login_required
|
||||
def facility_scorecard(facility_id):
|
||||
"""Comprehensive per-facility scorecard: score trend, SLA compliance,
|
||||
issue breakdown by severity, inspection frequency."""
|
||||
if current_user.role not in ['admin', 'supervisor', 'project_manager', 'customer']:
|
||||
from flask import flash, redirect, url_for
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('dashboard.index'))
|
||||
|
||||
facility = Facility.query.get_or_404(facility_id)
|
||||
|
||||
if current_user.role == 'customer':
|
||||
cids = get_customer_scope(current_user) or []
|
||||
if facility_id not in cids:
|
||||
from flask import flash, redirect, url_for
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('reports.index'))
|
||||
|
||||
from app.utils.sla import sla_status, SLA_HOURS
|
||||
from datetime import timedelta
|
||||
|
||||
now = now_eastern()
|
||||
days = request.args.get('days', 90, type=int)
|
||||
if days not in (30, 60, 90, 180, 365):
|
||||
days = 90
|
||||
start = now - timedelta(days=days)
|
||||
|
||||
# ── Score trend (daily) ───────────────────────────────────────────────
|
||||
trend_rows = db.session.query(
|
||||
func.date(Inspection.inspection_date).label('day'),
|
||||
func.avg(Inspection.overall_score).label('avg'),
|
||||
func.count(Inspection.id).label('count'),
|
||||
).filter(
|
||||
Inspection.facility_id == facility_id,
|
||||
Inspection.inspection_date >= start,
|
||||
Inspection.status == 'completed',
|
||||
Inspection.overall_score.isnot(None),
|
||||
).group_by(func.date(Inspection.inspection_date)) .order_by(func.date(Inspection.inspection_date)).all()
|
||||
|
||||
trend_labels = [str(r.day) for r in trend_rows]
|
||||
trend_data = [round(float(r.avg), 2) for r in trend_rows]
|
||||
|
||||
# ── KPI summary ───────────────────────────────────────────────────────
|
||||
all_insp = Inspection.query.filter(
|
||||
Inspection.facility_id == facility_id,
|
||||
Inspection.inspection_date >= start,
|
||||
).all()
|
||||
completed_insp = [i for i in all_insp if i.status == 'completed']
|
||||
avg_score = (
|
||||
round(sum(float(i.overall_score) for i in completed_insp
|
||||
if i.overall_score is not None)
|
||||
/ len([i for i in completed_insp if i.overall_score is not None]), 2)
|
||||
if any(i.overall_score for i in completed_insp) else None
|
||||
)
|
||||
|
||||
# ── Area scores ───────────────────────────────────────────────────────
|
||||
area_scores = db.session.query(
|
||||
Area.name,
|
||||
func.avg(Inspection.overall_score).label('avg'),
|
||||
func.count(Inspection.id).label('count'),
|
||||
).join(Inspection, Area.id == Inspection.area_id) .filter(
|
||||
Inspection.facility_id == facility_id,
|
||||
Inspection.inspection_date >= start,
|
||||
Inspection.status == 'completed',
|
||||
Inspection.overall_score.isnot(None),
|
||||
).group_by(Area.id, Area.name) .order_by(func.avg(Inspection.overall_score).desc()).all()
|
||||
|
||||
# ── Open issues ───────────────────────────────────────────────────────
|
||||
open_issues = Issue.query.join(Area) .filter(Area.facility_id == facility_id, Issue.status != 'resolved') .order_by(Issue.reported_at.desc()).all()
|
||||
|
||||
# SLA compliance for closed issues in window
|
||||
closed_issues = Issue.query.join(Area).filter(
|
||||
Area.facility_id == facility_id,
|
||||
Issue.status == 'resolved',
|
||||
Issue.reported_at >= start,
|
||||
).all()
|
||||
sla_met = sum(1 for i in closed_issues
|
||||
if i.resolved_at and i.reported_at
|
||||
and (i.resolved_at - i.reported_at).total_seconds() / 3600
|
||||
<= SLA_HOURS.get(i.severity, 9999))
|
||||
sla_total = len(closed_issues)
|
||||
sla_pct = round(sla_met / sla_total * 100, 1) if sla_total else None
|
||||
|
||||
# Issue severity breakdown
|
||||
sev_counts = {}
|
||||
for sev in ('critical', 'high', 'medium', 'low'):
|
||||
sev_counts[sev] = Issue.query.join(Area).filter(
|
||||
Area.facility_id == facility_id,
|
||||
Issue.severity == sev,
|
||||
Issue.status != 'resolved',
|
||||
).count()
|
||||
|
||||
# Pending verification count
|
||||
pending_verification = Issue.query.join(Area).filter(
|
||||
Area.facility_id == facility_id,
|
||||
Issue.status == 'pending_verification',
|
||||
).count()
|
||||
|
||||
# Follow-up required inspections
|
||||
followup_required = Inspection.query.filter(
|
||||
Inspection.facility_id == facility_id,
|
||||
Inspection.follow_up_required == True,
|
||||
).order_by(Inspection.inspection_date.desc()).limit(10).all()
|
||||
|
||||
return render_template('reports/scorecard.html',
|
||||
facility = facility,
|
||||
days = days,
|
||||
start = start,
|
||||
now = now,
|
||||
total_inspections = len(all_insp),
|
||||
completed_insp = len(completed_insp),
|
||||
avg_score = avg_score,
|
||||
trend_labels = trend_labels,
|
||||
trend_data = trend_data,
|
||||
area_scores = area_scores,
|
||||
open_issues = open_issues,
|
||||
sla_pct = sla_pct,
|
||||
sla_met = sla_met,
|
||||
sla_total = sla_total,
|
||||
sev_counts = sev_counts,
|
||||
pending_verification = pending_verification,
|
||||
followup_required = followup_required,
|
||||
)
|
||||
|
||||
# ── CSV export ────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/export/inspections')
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
"""
|
||||
app/routes/scheduled_reports.py
|
||||
--------------------------------
|
||||
CRUD management for ScheduledReport configs + cron-triggered send endpoint.
|
||||
|
||||
Admin/supervisor access for management.
|
||||
The /send route is token-protected (same DIGEST_SECRET) for cron use.
|
||||
|
||||
Cron examples
|
||||
-------------
|
||||
# Daily at 07:00
|
||||
0 7 * * * curl -s -X POST https://yourdomain.com/scheduled-reports/send \
|
||||
-d "token=YOUR_DIGEST_SECRET&frequency=daily"
|
||||
|
||||
# Weekly on Monday 07:00
|
||||
0 7 * * 1 curl -s -X POST https://yourdomain.com/scheduled-reports/send \
|
||||
-d "token=YOUR_DIGEST_SECRET&frequency=weekly"
|
||||
|
||||
# Monthly on the 1st at 07:00
|
||||
0 7 1 * * curl -s -X POST https://yourdomain.com/scheduled-reports/send \
|
||||
-d "token=YOUR_DIGEST_SECRET&frequency=monthly"
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import (Blueprint, render_template, redirect, url_for, flash,
|
||||
request, jsonify, current_app)
|
||||
from flask_login import login_required, current_user
|
||||
from flask_mail import Message
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db, mail
|
||||
from app.models.scheduled_report import ScheduledReport
|
||||
from app.models.inspection import Inspection, InspectionTemplate
|
||||
from app.models.facility import Facility, Area
|
||||
from app.models.issue import Issue
|
||||
from app.models.user import User
|
||||
from app.utils.decorators import supervisor_required
|
||||
from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE
|
||||
from app.utils.time_utils import now_eastern
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
bp = Blueprint('scheduled_reports', __name__, url_prefix='/scheduled-reports')
|
||||
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def _compute_next_send(frequency: str, from_dt: datetime = None) -> datetime:
|
||||
"""Return the next send datetime for a given frequency."""
|
||||
now = from_dt or now_eastern()
|
||||
if frequency == 'daily':
|
||||
return (now + timedelta(days=1)).replace(hour=7, minute=0, second=0, microsecond=0)
|
||||
if frequency == 'weekly':
|
||||
days_ahead = 7 - now.weekday() # next Monday
|
||||
return (now + timedelta(days=days_ahead)).replace(hour=7, minute=0, second=0, microsecond=0)
|
||||
# monthly: first of next month
|
||||
if now.month == 12:
|
||||
return now.replace(year=now.year + 1, month=1, day=1, hour=7, minute=0, second=0, microsecond=0)
|
||||
return now.replace(month=now.month + 1, day=1, hour=7, minute=0, second=0, microsecond=0)
|
||||
|
||||
|
||||
def _date_window(frequency: str):
|
||||
"""Return (start, end) covering the period just elapsed for this frequency."""
|
||||
end = now_eastern()
|
||||
if frequency == 'daily':
|
||||
start = end - timedelta(days=1)
|
||||
elif frequency == 'weekly':
|
||||
start = end - timedelta(weeks=1)
|
||||
else:
|
||||
start = end - timedelta(days=30)
|
||||
return start, end
|
||||
|
||||
|
||||
def _build_report_data(report: ScheduledReport, start: datetime, end: datetime) -> dict:
|
||||
"""Assemble the data dict passed to the email template."""
|
||||
data = {
|
||||
'report': report,
|
||||
'start': start,
|
||||
'end': end,
|
||||
'facility': report.facility,
|
||||
}
|
||||
|
||||
fid_filter = [report.facility_id] if report.facility_id else None
|
||||
|
||||
def _si(q):
|
||||
if fid_filter:
|
||||
return q.filter(Inspection.facility_id.in_(fid_filter))
|
||||
return q
|
||||
|
||||
def _iq(q):
|
||||
if fid_filter:
|
||||
return q.join(Area, Issue.area_id == Area.id).filter(Area.facility_id.in_(fid_filter))
|
||||
return q
|
||||
|
||||
if report.report_type in ('summary', 'facility'):
|
||||
base = _si(Inspection.query.filter(
|
||||
Inspection.inspection_date >= start,
|
||||
Inspection.inspection_date <= end,
|
||||
))
|
||||
data['total_inspections'] = base.count()
|
||||
data['completed'] = base.filter(Inspection.status == 'completed').count()
|
||||
|
||||
avg = db.session.query(func.avg(Inspection.overall_score)).filter(
|
||||
Inspection.inspection_date >= start,
|
||||
Inspection.inspection_date <= end,
|
||||
Inspection.status == 'completed',
|
||||
Inspection.overall_score.isnot(None),
|
||||
)
|
||||
data['avg_score'] = round(float(_si(avg).scalar()), 2) if _si(avg).scalar() else None
|
||||
|
||||
data['open_issues'] = _iq(Issue.query.filter(
|
||||
Issue.status.in_(['open', 'in_progress'])
|
||||
)).count()
|
||||
|
||||
data['critical_issues'] = _iq(Issue.query.filter(
|
||||
Issue.severity.in_(['critical', 'high']),
|
||||
Issue.status != 'resolved',
|
||||
)).order_by(Issue.reported_at.desc()).limit(10).all()
|
||||
|
||||
data['facility_scores'] = db.session.query(
|
||||
Facility.name,
|
||||
func.avg(Inspection.overall_score).label('avg'),
|
||||
func.count(Inspection.id).label('count'),
|
||||
).join(Inspection, Facility.id == Inspection.facility_id).filter(
|
||||
Inspection.inspection_date >= start,
|
||||
Inspection.inspection_date <= end,
|
||||
Inspection.status == 'completed',
|
||||
Inspection.overall_score.isnot(None),
|
||||
)
|
||||
if fid_filter:
|
||||
data['facility_scores'] = data['facility_scores'].filter(Facility.id.in_(fid_filter))
|
||||
data['facility_scores'] = data['facility_scores'].group_by(Facility.id, Facility.name)\
|
||||
.order_by(func.avg(Inspection.overall_score).desc()).all()
|
||||
|
||||
if report.report_type == 'issues':
|
||||
data['issues'] = _iq(Issue.query.filter(
|
||||
Issue.status != 'resolved',
|
||||
)).order_by(Issue.severity.desc(), Issue.reported_at.asc()).all()
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def _build_csv(report: ScheduledReport, start: datetime, end: datetime) -> bytes:
|
||||
"""Return CSV bytes appropriate for the report type."""
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf)
|
||||
|
||||
fid_filter = [report.facility_id] if report.facility_id else None
|
||||
|
||||
if report.report_type == 'issues':
|
||||
writer.writerow(['ID', 'Reported At', 'Facility', 'Area', 'Severity',
|
||||
'Description', 'Status', 'Assigned To'])
|
||||
q = Issue.query
|
||||
if fid_filter:
|
||||
q = q.join(Area, Issue.area_id == Area.id).filter(Area.facility_id.in_(fid_filter))
|
||||
for i in q.filter(Issue.status != 'resolved').order_by(Issue.reported_at.desc()).all():
|
||||
writer.writerow([
|
||||
i.id,
|
||||
i.reported_at.strftime('%Y-%m-%d %H:%M'),
|
||||
i.area.facility.name,
|
||||
i.area.name,
|
||||
i.severity,
|
||||
i.description.replace('\n', ' '),
|
||||
i.status,
|
||||
i.assigned_user.username if i.assigned_user else '',
|
||||
])
|
||||
else:
|
||||
writer.writerow(['ID', 'Date', 'Facility', 'Area', 'Inspector',
|
||||
'Template', 'Score', 'Status'])
|
||||
q = Inspection.query.filter(
|
||||
Inspection.inspection_date >= start,
|
||||
Inspection.inspection_date <= end,
|
||||
)
|
||||
if fid_filter:
|
||||
q = q.filter(Inspection.facility_id.in_(fid_filter))
|
||||
for i in q.order_by(Inspection.inspection_date.desc()).all():
|
||||
writer.writerow([
|
||||
i.id,
|
||||
i.inspection_date.strftime('%Y-%m-%d %H:%M'),
|
||||
i.facility.name,
|
||||
i.area.name if i.area else '',
|
||||
i.inspector.username,
|
||||
i.template.name,
|
||||
i.overall_score or '',
|
||||
i.status,
|
||||
])
|
||||
|
||||
return buf.getvalue().encode('utf-8')
|
||||
|
||||
|
||||
def _send_report(report: ScheduledReport):
|
||||
"""Build and dispatch the email for a single ScheduledReport."""
|
||||
if not current_app.config.get('MAIL_SERVER'):
|
||||
logger.warning('SCHEDULED REPORT SKIPPED | id=%s | no MAIL_SERVER', report.id)
|
||||
return False
|
||||
|
||||
recipients = report.recipient_list()
|
||||
if not recipients:
|
||||
logger.warning('SCHEDULED REPORT SKIPPED | id=%s | no recipients', report.id)
|
||||
return False
|
||||
|
||||
frequency = report.frequency
|
||||
start, end = _date_window(frequency)
|
||||
data = _build_report_data(report, start, end)
|
||||
base_url = current_app.config.get('APP_BASE_URL', '').rstrip('/')
|
||||
|
||||
html_body = render_template('scheduled_reports/email.html',
|
||||
base_url=base_url, **data)
|
||||
text_body = render_template('scheduled_reports/email.txt',
|
||||
base_url=base_url, **data)
|
||||
|
||||
subject = (f'[JQC] {report.frequency.title()} Report — {report.name} '
|
||||
f'({start.strftime("%b %d")}–{end.strftime("%b %d, %Y")})')
|
||||
|
||||
sender = current_app.config.get(
|
||||
'MAIL_DEFAULT_SENDER',
|
||||
current_app.config.get('MAIL_USERNAME', 'noreply@janitorialqc.local'),
|
||||
)
|
||||
|
||||
msg = Message(subject=subject, sender=sender, recipients=recipients,
|
||||
body=text_body, html=html_body)
|
||||
|
||||
if report.include_csv:
|
||||
csv_bytes = _build_csv(report, start, end)
|
||||
fname = f'jqc_report_{report.frequency}_{start.strftime("%Y%m%d")}.csv'
|
||||
msg.attach(fname, 'text/csv', csv_bytes)
|
||||
|
||||
try:
|
||||
mail.send(msg)
|
||||
logger.info('SCHEDULED REPORT SENT | id=%s | name=%r | recipients=%s',
|
||||
report.id, report.name, recipients)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error('SCHEDULED REPORT FAILED | id=%s | error=%s', report.id, exc)
|
||||
return False
|
||||
|
||||
|
||||
# ── CRUD ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/')
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def index():
|
||||
reports = ScheduledReport.query.order_by(ScheduledReport.name).all()
|
||||
return render_template('scheduled_reports/index.html', reports=reports)
|
||||
|
||||
|
||||
@bp.route('/new', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def create():
|
||||
facilities = Facility.query.filter_by(active=True).order_by(Facility.name).all()
|
||||
|
||||
if request.method == 'POST':
|
||||
name = request.form.get('name', '').strip()
|
||||
report_type = request.form.get('report_type', 'summary')
|
||||
frequency = request.form.get('frequency', 'weekly')
|
||||
facility_id = request.form.get('facility_id', type=int) or None
|
||||
recipients = [e.strip() for e in request.form.get('recipients', '').split(',') if e.strip()]
|
||||
include_pdf = bool(request.form.get('include_pdf'))
|
||||
include_csv = bool(request.form.get('include_csv'))
|
||||
|
||||
if not name:
|
||||
flash('Report name is required.', 'warning')
|
||||
return render_template('scheduled_reports/form.html',
|
||||
facilities=facilities, title='New Scheduled Report')
|
||||
if not recipients:
|
||||
flash('At least one recipient email is required.', 'warning')
|
||||
return render_template('scheduled_reports/form.html',
|
||||
facilities=facilities, title='New Scheduled Report')
|
||||
|
||||
report = ScheduledReport(
|
||||
name = name,
|
||||
report_type = report_type,
|
||||
frequency = frequency,
|
||||
facility_id = facility_id,
|
||||
recipients = recipients,
|
||||
include_pdf = include_pdf,
|
||||
include_csv = include_csv,
|
||||
active = True,
|
||||
created_by = current_user.id,
|
||||
created_at = now_eastern(),
|
||||
next_send_at = _compute_next_send(frequency),
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
log_action(ACTION_CREATE, 'ScheduledReport', report.id, report.name,
|
||||
f'frequency={frequency}; recipients={len(recipients)}')
|
||||
flash(f'Scheduled report "{report.name}" created.', 'success')
|
||||
return redirect(url_for('scheduled_reports.index'))
|
||||
|
||||
return render_template('scheduled_reports/form.html',
|
||||
facilities=facilities, title='New Scheduled Report')
|
||||
|
||||
|
||||
@bp.route('/<int:report_id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def edit(report_id):
|
||||
report = ScheduledReport.query.get_or_404(report_id)
|
||||
facilities = Facility.query.filter_by(active=True).order_by(Facility.name).all()
|
||||
|
||||
if request.method == 'POST':
|
||||
report.name = request.form.get('name', '').strip() or report.name
|
||||
report.report_type = request.form.get('report_type', report.report_type)
|
||||
report.frequency = request.form.get('frequency', report.frequency)
|
||||
report.facility_id = request.form.get('facility_id', type=int) or None
|
||||
report.recipients = [e.strip() for e in request.form.get('recipients', '').split(',') if e.strip()]
|
||||
report.include_pdf = bool(request.form.get('include_pdf'))
|
||||
report.include_csv = bool(request.form.get('include_csv'))
|
||||
report.active = bool(request.form.get('active'))
|
||||
report.next_send_at = _compute_next_send(report.frequency)
|
||||
|
||||
db.session.commit()
|
||||
log_action(ACTION_UPDATE, 'ScheduledReport', report.id, report.name,
|
||||
f'frequency={report.frequency}; active={report.active}')
|
||||
flash(f'Scheduled report "{report.name}" updated.', 'success')
|
||||
return redirect(url_for('scheduled_reports.index'))
|
||||
|
||||
return render_template('scheduled_reports/form.html', report=report,
|
||||
facilities=facilities, title='Edit Scheduled Report')
|
||||
|
||||
|
||||
@bp.route('/<int:report_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def delete(report_id):
|
||||
report = ScheduledReport.query.get_or_404(report_id)
|
||||
name = report.name
|
||||
rid = report.id
|
||||
db.session.delete(report)
|
||||
db.session.commit()
|
||||
log_action(ACTION_DELETE, 'ScheduledReport', rid, name)
|
||||
flash(f'Scheduled report "{name}" deleted.', 'success')
|
||||
return redirect(url_for('scheduled_reports.index'))
|
||||
|
||||
|
||||
@bp.route('/<int:report_id>/send-now', methods=['POST'])
|
||||
@login_required
|
||||
@supervisor_required
|
||||
def send_now(report_id):
|
||||
"""Manually trigger a single report — useful for testing."""
|
||||
report = ScheduledReport.query.get_or_404(report_id)
|
||||
ok = _send_report(report)
|
||||
if ok:
|
||||
report.last_sent_at = now_eastern()
|
||||
db.session.commit()
|
||||
flash(f'Report "{report.name}" sent successfully.', 'success')
|
||||
else:
|
||||
flash(f'Failed to send report "{report.name}". Check application logs.', 'danger')
|
||||
return redirect(url_for('scheduled_reports.index'))
|
||||
|
||||
|
||||
# ── Cron endpoint ─────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/send', methods=['POST'])
|
||||
def send():
|
||||
"""Token-protected endpoint called by cron to dispatch due reports.
|
||||
|
||||
POST body: token=<DIGEST_SECRET>&frequency=daily|weekly|monthly
|
||||
"""
|
||||
token = request.form.get('token') or request.args.get('token')
|
||||
frequency = request.form.get('frequency', 'daily')
|
||||
expected = current_app.config.get('DIGEST_SECRET')
|
||||
|
||||
if not expected or token != expected:
|
||||
logger.warning('SCHEDULED REPORTS SEND REJECTED | bad/missing token')
|
||||
return jsonify({'ok': False, 'error': 'unauthorized'}), 403
|
||||
|
||||
if frequency not in ('daily', 'weekly', 'monthly'):
|
||||
return jsonify({'ok': False, 'error': 'invalid frequency'}), 400
|
||||
|
||||
now = now_eastern()
|
||||
reports = ScheduledReport.query.filter_by(active=True, frequency=frequency).all()
|
||||
# Only send reports whose next_send_at is due (or not yet set)
|
||||
due = [r for r in reports if r.next_send_at is None or r.next_send_at <= now]
|
||||
|
||||
sent, failed = 0, 0
|
||||
for report in due:
|
||||
ok = _send_report(report)
|
||||
if ok:
|
||||
report.last_sent_at = now
|
||||
report.next_send_at = _compute_next_send(frequency, now)
|
||||
sent += 1
|
||||
else:
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
|
||||
logger.info('SCHEDULED REPORTS CRON | frequency=%s | due=%s | sent=%s | failed=%s',
|
||||
frequency, len(due), sent, failed)
|
||||
return jsonify({'ok': True, 'frequency': frequency, 'sent': sent, 'failed': failed})
|
||||
Reference in New Issue
Block a user