Phase 3: changes inspection workflow

This commit is contained in:
2026-02-21 13:32:59 -05:00
parent e024d52915
commit 09ba576fcb
5 changed files with 918 additions and 426 deletions
+1
View File
@@ -29,6 +29,7 @@ def create_app(config_name='default'):
# render manual forms (no WTForms object) can still inject the CSRF token.
from flask_wtf.csrf import generate_csrf
app.jinja_env.globals['csrf_token'] = generate_csrf
app.jinja_env.globals['enumerate'] = enumerate
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
+31 -36
View File
@@ -6,22 +6,18 @@ import json
class InspectionTemplate(db.Model):
__tablename__ = 'inspection_templates'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False)
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
frequency = db.Column(db.Enum('daily', 'weekly', 'monthly', 'quarterly'))
created_by = db.Column(db.Integer, db.ForeignKey('users.id'))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Form builder schema — stores the full dynamic field layout as JSON
frequency = db.Column(db.Enum('daily', 'weekly', 'monthly', 'quarterly'))
created_by = db.Column(db.Integer, db.ForeignKey('users.id'))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
form_schema = db.Column(db.JSON, nullable=True)
# Relationships
checklist_items = db.relationship('ChecklistItem', backref='template', lazy='dynamic', cascade='all, delete-orphan')
inspections = db.relationship('Inspection', backref='template', lazy='dynamic')
inspections = db.relationship('Inspection', backref='template', lazy='dynamic')
def get_form_schema(self):
"""Return the form schema as a Python list, or empty list if not set."""
if self.form_schema is None:
return []
if isinstance(self.form_schema, str):
@@ -38,16 +34,15 @@ class InspectionTemplate(db.Model):
class ChecklistItem(db.Model):
__tablename__ = 'checklist_items'
id = db.Column(db.Integer, primary_key=True)
template_id = db.Column(db.Integer, db.ForeignKey('inspection_templates.id'), nullable=False)
category = db.Column(db.String(100))
id = db.Column(db.Integer, primary_key=True)
template_id = db.Column(db.Integer, db.ForeignKey('inspection_templates.id'), nullable=False)
category = db.Column(db.String(100))
item_description = db.Column(db.Text, nullable=False)
scoring_type = db.Column(db.Enum('pass_fail', 'rating_5', 'rating_10'))
weight = db.Column(db.Numeric(3, 2), default=1.00)
requires_photo = db.Column(db.Boolean, default=False)
display_order = db.Column(db.Integer)
scoring_type = db.Column(db.Enum('pass_fail', 'rating_5', 'rating_10'))
weight = db.Column(db.Numeric(3, 2), default=1.00)
requires_photo = db.Column(db.Boolean, default=False)
display_order = db.Column(db.Integer)
# Relationships
results = db.relationship('InspectionResult', backref='checklist_item', lazy='dynamic')
def __repr__(self):
@@ -57,20 +52,20 @@ class ChecklistItem(db.Model):
class Inspection(db.Model):
__tablename__ = 'inspections'
id = db.Column(db.Integer, primary_key=True)
template_id = db.Column(db.Integer, db.ForeignKey('inspection_templates.id'), nullable=False)
facility_id = db.Column(db.Integer, db.ForeignKey('facilities.id'), nullable=False)
area_id = db.Column(db.Integer, db.ForeignKey('areas.id'))
inspector_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
id = db.Column(db.Integer, primary_key=True)
template_id = db.Column(db.Integer, db.ForeignKey('inspection_templates.id'), nullable=False)
facility_id = db.Column(db.Integer, db.ForeignKey('facilities.id'), nullable=False)
area_id = db.Column(db.Integer, db.ForeignKey('areas.id'))
inspector_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
inspection_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
overall_score = db.Column(db.Numeric(5, 2))
status = db.Column(db.Enum('in_progress', 'completed', 'flagged'), default='in_progress')
notes = db.Column(db.Text)
completed_at = db.Column(db.DateTime)
overall_score = db.Column(db.Numeric(5, 2))
status = db.Column(db.Enum('in_progress', 'completed', 'flagged'), default='in_progress')
notes = db.Column(db.Text) # inspector free-text notes
form_data = db.Column(db.JSON) # filled form field responses {field_id: value}
completed_at = db.Column(db.DateTime)
# Relationships
results = db.relationship('InspectionResult', backref='inspection', lazy='dynamic', cascade='all, delete-orphan')
issues = db.relationship('Issue', backref='inspection', lazy='dynamic')
issues = db.relationship('Issue', backref='inspection', lazy='dynamic')
def __repr__(self):
return f'<Inspection {self.id} - {self.inspection_date}>'
@@ -79,13 +74,13 @@ class Inspection(db.Model):
class InspectionResult(db.Model):
__tablename__ = 'inspection_results'
id = db.Column(db.Integer, primary_key=True)
inspection_id = db.Column(db.Integer, db.ForeignKey('inspections.id'), nullable=False)
id = db.Column(db.Integer, primary_key=True)
inspection_id = db.Column(db.Integer, db.ForeignKey('inspections.id'), nullable=False)
checklist_item_id = db.Column(db.Integer, db.ForeignKey('checklist_items.id'), nullable=False)
score = db.Column(db.Numeric(5, 2))
passed = db.Column(db.Boolean)
comments = db.Column(db.Text)
photo_path = db.Column(db.String(255))
score = db.Column(db.Numeric(5, 2))
passed = db.Column(db.Boolean)
comments = db.Column(db.Text)
photo_path = db.Column(db.String(255))
def __repr__(self):
return f'<InspectionResult {self.id}>'
return f'<InspectionResult {self.id}>'
+203 -127
View File
@@ -1,4 +1,5 @@
import os
import json
import uuid
from datetime import datetime
from flask import (Blueprint, render_template, redirect, url_for,
@@ -17,6 +18,12 @@ bp = Blueprint('inspections', __name__, url_prefix='/inspections')
ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif'}
INPUT_FIELD_TYPES = {
'text', 'textarea', 'number', 'date', 'email',
'checkbox', 'checkbox_group', 'radio', 'select',
'rating', 'signature', 'image', 'table'
}
def _save_photo(file_obj, subfolder='inspection_photos'):
"""Save an uploaded photo; return the relative path or None."""
@@ -25,63 +32,133 @@ def _save_photo(file_obj, subfolder='inspection_photos'):
ext = file_obj.filename.rsplit('.', 1)[-1].lower()
if ext not in ALLOWED_EXTENSIONS:
return None
filename = f"{uuid.uuid4().hex}.{ext}"
dest_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], subfolder)
filename = f"{uuid.uuid4().hex}.{ext}"
dest_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], subfolder)
os.makedirs(dest_dir, exist_ok=True)
file_obj.save(os.path.join(dest_dir, filename))
return f"uploads/{subfolder}/{filename}"
def _compute_score(inspection):
def _collect_form_responses(form_fields):
"""
Weighted average of all scored checklist results.
pass_fail → 100 if passed else 0
rating_5 → (score / 5) * 100
rating_10 → (score / 10) * 100
Returns a Decimal-compatible float or None if no results.
Walk the submitted form data and collect responses keyed by field ID.
Returns a dict: { field_id: value_or_list_or_path }
Photo uploads are saved to disk; their path is stored as the value.
"""
results = inspection.results.join(ChecklistItem).all()
if not results:
responses = {}
for field in form_fields:
fid = field['id']
ftype = field['type']
if ftype in ('label', 'section', 'button_submit', 'button_print', 'button_email'):
continue # display-only, nothing to capture
key = f"field_{fid}"
if ftype == 'checkbox':
responses[fid] = 'true' if request.form.get(key) else 'false'
elif ftype == 'checkbox_group':
responses[fid] = request.form.getlist(key)
elif ftype == 'image':
photo_file = request.files.get(key)
path = _save_photo(photo_file, subfolder='inspection_photos')
responses[fid] = path or ''
elif ftype == 'table':
cols = field.get('col_headers') or ['Column 1']
rows = int(field.get('table_rows') or 3)
table_data = []
for r in range(rows):
row_data = {}
for c_idx, col in enumerate(cols):
cell_key = f"{key}_r{r}_c{c_idx}"
row_data[col] = request.form.get(cell_key, '')
table_data.append(row_data)
responses[fid] = table_data
elif ftype == 'rating':
responses[fid] = request.form.get(key, '0')
else:
# text, textarea, number, date, email, radio, select, signature
responses[fid] = request.form.get(key, '')
return responses
def _compute_score_from_form(form_fields, responses):
"""
Derive an overall score from rating fields and checkbox pass/fail fields.
Returns a float 0100 or None if the form has no scoreable fields.
"""
scoreable = [f for f in form_fields if f['type'] in ('rating', 'checkbox', 'radio')]
if not scoreable:
return None
total_weight = 0.0
weighted_sum = 0.0
total, earned = 0, 0
for field in scoreable:
fid = field['id']
val = responses.get(fid, '')
for r in results:
item = r.checklist_item
weight = float(item.weight or 1.0)
if field['type'] == 'rating':
try:
v = int(val)
earned += v
total += 5 # max rating is 5 stars
except (ValueError, TypeError):
total += 5
if item.scoring_type == 'pass_fail':
pts = 100.0 if r.passed else 0.0
elif item.scoring_type == 'rating_5':
pts = (float(r.score) / 5.0 * 100.0) if r.score is not None else 0.0
elif item.scoring_type == 'rating_10':
pts = (float(r.score) / 10.0 * 100.0) if r.score is not None else 0.0
else:
pts = 100.0 if r.passed else 0.0
elif field['type'] == 'checkbox':
total += 1
if val == 'true':
earned += 1
weighted_sum += pts * weight
total_weight += weight
elif field['type'] == 'radio':
# Options that look like pass/yes/ok score 1; fail/no/na score 0
total += 1
if val.lower() in ('pass', 'yes', 'ok', 'good', 'acceptable', 'compliant'):
earned += 1
return round(weighted_sum / total_weight, 2) if total_weight else None
return round((earned / total) * 100, 2) if total else None
# ── List ─────────────────────────────────────────────────────────────────────
def _validate_required(form_fields, responses):
"""Return a list of labels for required fields that have empty responses."""
missing = []
for field in form_fields:
if not field.get('required'):
continue
ftype = field['type']
if ftype in ('label', 'section', 'button_submit', 'button_print', 'button_email'):
continue
val = responses.get(field['id'])
empty = (
val is None
or val == ''
or val == 'false'
or val == '0'
or val == []
)
if empty:
missing.append(field.get('label', 'Untitled field'))
return missing
# ── List ──────────────────────────────────────────────────────────────────────
@bp.route('/')
@login_required
def index():
page = request.args.get('page', 1, type=int)
q = Inspection.query.order_by(Inspection.inspection_date.desc())
# Inspectors only see their own
if current_user.role == 'inspector':
q = q.filter(Inspection.inspector_id == current_user.id)
# Optional filters
status_filter = request.args.get('status', '')
facility_filter = request.args.get('facility_id', '', type=str)
facility_filter = request.args.get('facility_id', '')
if status_filter:
q = q.filter(Inspection.status == status_filter)
if facility_filter.isdigit():
@@ -110,34 +187,31 @@ 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]
# Area choices populated via AJAX based on selected facility
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]
if form.validate_on_submit():
template = InspectionTemplate.query.get_or_404(form.template_id.data)
# Guard: template must have a form built in the form editor
if not template.get_form_schema():
flash('This template has no form fields yet. Please build the form in the template editor first.', 'warning')
return redirect(url_for('inspections.start'))
inspection = Inspection(
template_id = form.template_id.data,
facility_id = form.facility_id.data,
area_id = form.area_id.data or None,
inspector_id = current_user.id,
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 = datetime.utcnow(),
status = 'in_progress',
notes = form.notes.data or None,
status = 'in_progress',
notes = form.notes.data or None,
)
db.session.add(inspection)
db.session.flush() # get inspection.id
# Pre-create blank InspectionResult rows for every checklist item
template = InspectionTemplate.query.get(form.template_id.data)
for item in template.checklist_items.order_by(ChecklistItem.display_order).all():
db.session.add(InspectionResult(
inspection_id = inspection.id,
checklist_item_id = item.id,
))
db.session.commit()
flash(f'Inspection started. Complete each item below.', 'success')
flash('Inspection started. Fill in the form below and submit when complete.', 'info')
return redirect(url_for('inspections.execute', inspection_id=inspection.id))
return render_template('inspections/start.html', form=form, facilities=facilities)
@@ -152,14 +226,13 @@ def areas_for_facility(facility_id):
return jsonify([{'id': a.id, 'name': a.name} for a in areas])
# ── Execute ───────────────────────────────────────────────────────────────────
# ── Execute — render and submit the template form ─────────────────────────────
@bp.route('/<int:inspection_id>/execute', methods=['GET', 'POST'])
@login_required
def execute(inspection_id):
inspection = Inspection.query.get_or_404(inspection_id)
# Inspectors can only work on their own inspections
if current_user.role == 'inspector' and inspection.inspector_id != current_user.id:
flash('Access denied.', 'danger')
return redirect(url_for('inspections.index'))
@@ -167,82 +240,85 @@ def execute(inspection_id):
if inspection.status == 'completed':
return redirect(url_for('inspections.view', inspection_id=inspection_id))
# Ordered checklist items with their result rows
results = (
InspectionResult.query
.join(ChecklistItem)
.filter(InspectionResult.inspection_id == inspection_id)
.order_by(ChecklistItem.display_order)
.all()
)
template = inspection.template
form_fields = template.get_form_schema()
# Sort fields by grid position (row then col) for logical reading order
form_fields = sorted(form_fields, key=lambda f: (f.get('row', 0), f.get('col', 0)))
# Load any previously saved draft responses
saved_responses = {}
if inspection.notes:
try:
parsed = json.loads(inspection.notes)
if isinstance(parsed, dict) and '_form_data' in parsed:
saved_responses = parsed['_form_data']
except (json.JSONDecodeError, TypeError):
pass
if request.method == 'POST':
action = request.form.get('action', 'save')
action = request.form.get('action', 'submit')
for result in results:
item = result.checklist_item
prefix = f"item_{result.id}_"
# Collect all field responses from the submitted form
responses = _collect_form_responses(form_fields)
if item.scoring_type == 'pass_fail':
passed_val = request.form.get(f"{prefix}passed", '')
result.passed = True if passed_val == 'pass' else \
False if passed_val == 'fail' else None
result.score = None
elif item.scoring_type in ('rating_5', 'rating_10'):
raw = request.form.get(f"{prefix}score", '')
try:
result.score = float(raw)
result.passed = result.score > 0
except (ValueError, TypeError):
result.score = None
result.passed = None
else:
result.passed = None
result.score = None
result.comments = request.form.get(f"{prefix}comments", '').strip() or None
# Photo upload
photo_file = request.files.get(f"{prefix}photo")
if photo_file and photo_file.filename:
path = _save_photo(photo_file)
if path:
result.photo_path = path
if action == 'complete':
# Validate all required-photo items have a photo
missing_photos = [
r for r in results
if r.checklist_item.requires_photo and not r.photo_path
]
if missing_photos:
db.session.commit()
flash(f'{len(missing_photos)} item(s) require a photo before completing.', 'warning')
if action == 'submit':
# Validate required fields
missing = _validate_required(form_fields, responses)
if missing:
# Save draft so the inspector doesn't lose their work
_save_draft(inspection, responses)
flash(
f'Please complete all required fields before submitting: '
f'{", ".join(missing[:5])}{"" if len(missing) > 5 else ""}',
'warning'
)
return redirect(url_for('inspections.execute', inspection_id=inspection_id))
inspection.overall_score = _compute_score(inspection)
# Compute score and mark complete
score = _compute_score_from_form(form_fields, responses)
inspection.overall_score = score
inspection.status = 'completed'
inspection.completed_at = datetime.utcnow()
# Persist the final form data alongside any inspector notes
_save_responses(inspection, responses)
db.session.commit()
flash('Inspection completed successfully!', 'success')
flash('Inspection submitted successfully!', 'success')
return redirect(url_for('inspections.view', inspection_id=inspection_id))
db.session.commit()
flash('Progress saved.', 'success')
return redirect(url_for('inspections.execute', inspection_id=inspection_id))
# Count answered vs total
answered = sum(1 for r in results if r.passed is not None or r.score is not None)
staff = User.query.filter(User.role.in_(['supervisor', 'inspector'])).order_by(User.username).all()
else: # save draft
_save_draft(inspection, responses)
db.session.commit()
flash('Draft saved. You can continue filling in the form later.', 'success')
return redirect(url_for('inspections.execute', inspection_id=inspection_id))
return render_template('inspections/execute.html',
inspection=inspection,
results=results,
answered=answered,
staff=staff)
form_fields=form_fields,
saved_responses=saved_responses)
# ── View (completed) ──────────────────────────────────────────────────────────
def _save_responses(inspection, responses):
"""Persist final form responses into inspection.notes as JSON."""
existing = {}
if inspection.notes:
try:
existing = json.loads(inspection.notes)
except (json.JSONDecodeError, TypeError):
existing = {'_inspector_notes': inspection.notes}
existing['_form_data'] = responses
inspection.notes = json.dumps(existing)
def _save_draft(inspection, responses):
"""Save a draft of form responses — same storage as final, just status stays in_progress."""
_save_responses(inspection, responses)
db.session.commit()
# ── View ──────────────────────────────────────────────────────────────────────
@bp.route('/<int:inspection_id>')
@login_required
@@ -253,25 +329,26 @@ def view(inspection_id):
flash('Access denied.', 'danger')
return redirect(url_for('inspections.index'))
results = (
InspectionResult.query
.join(ChecklistItem)
.filter(InspectionResult.inspection_id == inspection_id)
.order_by(ChecklistItem.display_order)
.all()
)
template = inspection.template
form_fields = sorted(template.get_form_schema(),
key=lambda f: (f.get('row', 0), f.get('col', 0)))
# Group by category
categories = {}
for r in results:
cat = r.checklist_item.category or 'General'
categories.setdefault(cat, []).append(r)
# Decode saved responses
form_data = {}
if inspection.notes:
try:
parsed = json.loads(inspection.notes)
if isinstance(parsed, dict):
form_data = parsed.get('_form_data', {})
except (json.JSONDecodeError, TypeError):
pass
issues = inspection.issues.order_by(Issue.reported_at.desc()).all()
return render_template('inspections/view.html',
inspection=inspection,
categories=categories,
form_fields=form_fields,
form_data=form_data,
issues=issues)
@@ -286,9 +363,9 @@ def flag_issue(inspection_id):
flash('Access denied.', 'danger')
return redirect(url_for('inspections.index'))
form = IssueForm()
form = IssueForm()
areas = Area.query.filter_by(facility_id=inspection.facility_id).order_by(Area.name).all()
staff = User.query.filter(User.role.in_(['supervisor','inspector'])).order_by(User.username).all()
staff = User.query.filter(User.role.in_(['supervisor', 'inspector'])).order_by(User.username).all()
form.area_id.choices = [(a.id, a.name) for a in areas]
form.assigned_to.choices = [(0, '— Unassigned —')] + [(u.id, u.username) for u in staff]
@@ -307,7 +384,6 @@ def flag_issue(inspection_id):
)
db.session.add(issue)
# Auto-flag the inspection if a high/critical issue is logged
if form.severity.data in ('high', 'critical') and inspection.status != 'completed':
inspection.status = 'flagged'
+423 -126
View File
@@ -1,161 +1,458 @@
{% extends "base.html" %}
{% block title %}Execute Inspection{% endblock %}
{% block title %}{{ inspection.template.name }} — Inspection{% endblock %}
{% block extra_css %}
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
.item-card { border-left: 4px solid #dee2e6; transition: border-color .2s; }
.item-card.answered { border-left-color: #198754; }
.item-card.flagged { border-left-color: #dc3545; }
.pass-fail-group .btn-check:checked + .btn-outline-success { background:#198754; color:#fff; }
.pass-fail-group .btn-check:checked + .btn-outline-danger { background:#dc3545; color:#fff; }
.progress-bar-label { font-size:.75rem; font-weight:600; }
.sticky-toolbar { position:sticky; top:56px; z-index:20; background:#fff; border-bottom:1px solid #dee2e6; padding:.6rem 1rem; }
body { font-family: 'DM Sans', sans-serif; background: #eef0f4; }
.insp-wrap { max-width: 1000px; margin: 0 auto; padding: 0 1rem 4rem; }
.insp-header {
background: #1a1d23; color: #fff;
padding: 1.1rem 1.75rem;
border-radius: 12px 12px 0 0;
display: flex; align-items: center; justify-content: space-between; gap: 1rem;
}
.insp-header h4 { margin:0; font-weight:600; font-size:1.05rem; }
.insp-header .sub{ font-size:.78rem; color:#94a3b8; margin-top:.2rem; }
.freq-badge {
font-size:.72rem; background:rgba(255,255,255,.15);
padding:.28rem .65rem; border-radius:20px; font-weight:500; white-space:nowrap;
}
.insp-body {
background:#fff; border:1px solid #e2e8f0; border-top:none;
border-radius: 0 0 12px 12px; padding:1.75rem; overflow-x:auto;
}
/* ── 12-col grid (matches form editor exactly) ── */
.form-grid {
display: grid;
grid-template-columns: repeat(12, 72px);
grid-auto-rows: auto;
gap: 4px 8px;
width: max-content;
}
.fg-cell {
overflow:hidden; display:flex; flex-direction:column; padding:.22rem .55rem;
}
.fg-cell .field-lbl {
font-size:.74rem; font-weight:500; color:#64748b;
margin-bottom:.2rem; display:block;
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; flex-shrink:0;
}
.required-mark { color:#dc2626; }
.help-text { font-size:.72rem; color:#64748b; margin-top:.18rem; flex-shrink:0; }
.field-error { font-size:.72rem; color:#dc2626; margin-top:.18rem; }
.fg-cell .form-control,
.fg-cell .form-select {
font-size:.76rem; padding:.2rem .4rem;
border-color:#e2e8f0; background:#f8fafc;
}
.fg-cell .form-control:focus,
.fg-cell .form-select:focus { border-color:#2563eb; background:#fff; box-shadow:none; }
.fg-cell textarea.form-control { resize:vertical; flex:1; min-height:60px; }
.fg-cell .form-check-label { font-size:.76rem; color:#64748b; }
.fg-cell .form-check-input { margin-top:.18rem; }
.fg-cell .form-check { margin-bottom:.1rem; }
.upload-zone {
border:2px dashed #cbd5e1; border-radius:6px; flex:1; min-height:60px;
display:flex; flex-direction:column; align-items:center; justify-content:center;
color:#64748b; background:#f8fafc; cursor:pointer; font-size:.74rem; gap:.2rem;
transition:border-color .18s, background .18s; position:relative;
}
.upload-zone:hover { border-color:#2563eb; background:#eff6ff; color:#2563eb; }
.upload-zone input[type=file] {
position:absolute; inset:0; opacity:0; cursor:pointer; width:100%; height:100%;
}
.upload-zone i { font-size:1.1rem; }
.upload-zone .file-name { font-size:.7rem; color:#2563eb; max-width:100%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.signature-pad-wrap {
flex:1; min-height:80px; border-radius:6px; border:1px solid #e2e8f0;
background:#f8fafc; position:relative; overflow:hidden;
}
.signature-pad-wrap canvas { width:100%; height:100%; cursor:crosshair; display:block; }
.sig-clear {
position:absolute; top:4px; right:4px;
font-size:.65rem; padding:.15rem .4rem;
background:rgba(255,255,255,.85); border:1px solid #cbd5e1; border-radius:4px;
cursor:pointer; color:#64748b;
}
.sig-clear:hover { color:#dc2626; border-color:#dc2626; }
.rating-stars { display:flex; gap:.25rem; align-items:center; padding-top:.08rem; }
.rating-stars button {
border:none; background:none; font-size:1.45rem; color:#cbd5e1;
cursor:pointer; padding:0; line-height:1; transition:color .12s;
}
.rating-stars button:hover,
.rating-stars button.on { color:#f59e0b; }
.section-divider {
height:100%; display:flex; align-items:center; padding:0;
border-top:2px solid #e2e8f0; padding-top:.4rem;
}
.section-divider strong { font-weight:700; color:#374151; font-size:.95rem; }
.tbl-field { width:100%; border-collapse:collapse; font-size:.8rem; }
.tbl-field th {
background:#f1f5f9; font-weight:600; color:#374151;
padding:.3rem .5rem; border:1px solid #e2e8f0; white-space:nowrap; font-size:.78rem;
}
.tbl-field td { border:1px solid #e2e8f0; padding:.15rem .25rem; }
.tbl-input { width:100%; border:none; outline:none; font-size:.8rem; padding:.1rem .2rem; background:transparent; }
.tbl-input:focus { background:#eff6ff; }
/* existing photo thumbnail */
.photo-thumb { max-height:60px; border-radius:4px; margin-bottom:.25rem; }
/* sticky footer bar */
.insp-footer {
position:sticky; bottom:0; background:#1a1d23;
border-radius:0 0 12px 12px;
padding:.75rem 1.75rem;
display:flex; align-items:center; justify-content:space-between; gap:1rem;
margin-top:1.5rem;
}
.insp-footer .meta { color:#94a3b8; font-size:.8rem; }
.insp-footer .meta strong { color:#e2e8f0; }
</style>
{% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data" id="inspectionForm">
<div class="insp-wrap mt-3">
<form method="post" enctype="multipart/form-data" id="inspectionForm" novalidate>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
{# Sticky toolbar #}
<div class="sticky-toolbar d-flex align-items-center gap-3 mb-4">
<div class="flex-grow-1">
<h5 class="mb-0">{{ inspection.template.name }}</h5>
<small class="text-muted">{{ inspection.facility.name }}{% if inspection.area %} · {{ inspection.area.name }}{% endif %}</small>
</div>
<div class="text-center" style="min-width:120px;">
<div class="progress" style="height:8px;">
<div class="progress-bar bg-success" style="width:{{ (answered / results|length * 100)|int if results else 0 }}%"></div>
{# ── Header ── #}
<div class="insp-header">
<div>
<h4><i class="bi bi-clipboard-check"></i> {{ inspection.template.name }}</h4>
<div class="sub">
{{ inspection.facility.name }}
{% if inspection.area %} · {{ inspection.area.name }}{% endif %}
&nbsp;·&nbsp; Inspector: <strong style="color:#e2e8f0;">{{ inspection.inspector.username }}</strong>
</div>
<span class="progress-bar-label text-muted">{{ answered }}/{{ results|length }} answered</span>
</div>
<a href="{{ url_for('inspections.flag_issue', inspection_id=inspection.id) }}"
class="btn btn-sm btn-outline-danger">
<i class="bi bi-exclamation-triangle"></i> Flag Issue
</a>
<button type="submit" name="action" value="save" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-floppy"></i> Save
</button>
<button type="submit" name="action" value="complete" class="btn btn-success"
onclick="return confirm('Mark this inspection as complete?')">
<i class="bi bi-check-circle"></i> Complete
</button>
<div class="d-flex gap-2 align-items-center">
<span class="freq-badge">{{ inspection.template.frequency|title }}</span>
<a href="{{ url_for('inspections.flag_issue', inspection_id=inspection.id) }}"
class="btn btn-sm btn-outline-danger btn-outline-light">
<i class="bi bi-exclamation-triangle"></i> Flag Issue
</a>
</div>
</div>
{% if inspection.notes %}
<div class="alert alert-info py-2"><i class="bi bi-sticky"></i> <strong>Notes:</strong> {{ inspection.notes }}</div>
{% endif %}
{# ── Form body ── #}
<div class="insp-body">
{% if form_fields %}
{% set ns = namespace(current_cat='') %}
{% for result in results %}
{% set item = result.checklist_item %}
{% if item.category != ns.current_cat %}
{% set ns.current_cat = item.category %}
<h5 class="text-primary border-bottom pb-1 mt-4 mb-3">
<i class="bi bi-folder2"></i> {{ item.category or 'General' }}
</h5>
{% endif %}
<div class="form-grid">
{% for field in form_fields %}
{% set fid = field.id %}
{% set saved = saved_responses.get(fid, '') %}
{% set is_answered = result.passed is not none or result.score is not none %}
<div class="card shadow-sm mb-3 item-card {{ 'answered' if is_answered }}">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start mb-2">
<div>
<span class="fw-semibold">{{ item.item_description }}</span>
{% if item.requires_photo %}
<span class="badge bg-warning text-dark ms-1"><i class="bi bi-camera"></i> Photo required</span>
{% endif %}
<div class="fg-cell"
style="grid-column: {{ field.col }} / span {{ field.colSpan }};
grid-row: {{ field.row }} / span {{ field.rowSpan }};">
{# ── Section label (display only) ── #}
{% if field.type == 'section' %}
<div class="section-divider"><strong>{{ field.label }}</strong></div>
{# ── Static label ── #}
{% elif field.type == 'label' %}
{% set fs_map = {'small':'0.78rem','normal':'0.9rem','large':'1.05rem','x-large':'1.25rem'} %}
<div style="font-size:{{ fs_map.get(field.font_size or 'normal','0.9rem') }};
font-weight:{{ field.font_weight or 'normal' }};
color:#374151;line-height:1.5;white-space:pre-wrap;overflow:hidden;height:100%;">
{{ field.text_content or '' }}
</div>
<span class="badge bg-secondary text-uppercase" style="font-size:.65rem;">{{ item.scoring_type|replace('_',' ') }}</span>
</div>
{# ── Pass/Fail ── #}
{% if item.scoring_type == 'pass_fail' %}
<div class="pass-fail-group d-flex gap-2 mb-2">
<input class="btn-check" type="radio" name="item_{{ result.id }}_passed"
id="pass_{{ result.id }}" value="pass" {{ 'checked' if result.passed == true }}>
<label class="btn btn-outline-success btn-sm" for="pass_{{ result.id }}">
<i class="bi bi-check-lg"></i> Pass
</label>
<input class="btn-check" type="radio" name="item_{{ result.id }}_passed"
id="fail_{{ result.id }}" value="fail" {{ 'checked' if result.passed == false }}>
<label class="btn btn-outline-danger btn-sm" for="fail_{{ result.id }}">
<i class="bi bi-x-lg"></i> Fail
</label>
</div>
{# ── Submit / Print / Email buttons (display in preview; no action needed here) ── #}
{% elif field.type in ('button_submit','button_print','button_email') %}
{# rendered by the sticky footer instead #}
{# ── Rating 5 ── #}
{% elif item.scoring_type == 'rating_5' %}
<div class="mb-2">
<label class="form-label small">Rating (15)</label>
<div class="d-flex gap-2">
{% for v in [1,2,3,4,5] %}
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="item_{{ result.id }}_score"
id="r5_{{ result.id }}_{{ v }}" value="{{ v }}"
{{ 'checked' if result.score == v }}>
<label class="form-check-label" for="r5_{{ result.id }}_{{ v }}">{{ v }}</label>
</div>
{# ── Text ── #}
{% elif field.type == 'text' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<input type="text" class="form-control" name="field_{{ fid }}"
value="{{ saved }}" placeholder="{{ field.placeholder or '' }}"
{% if field.required %}required{% endif %}>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Textarea ── #}
{% elif field.type == 'textarea' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<textarea class="form-control" name="field_{{ fid }}"
placeholder="{{ field.placeholder or '' }}"
{% if field.required %}required{% endif %}>{{ saved }}</textarea>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Number ── #}
{% elif field.type == 'number' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<input type="number" class="form-control" name="field_{{ fid }}"
value="{{ saved }}" placeholder="{{ field.placeholder or '' }}"
{% if field.required %}required{% endif %}>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Date ── #}
{% elif field.type == 'date' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<input type="date" class="form-control" name="field_{{ fid }}"
value="{{ saved }}" {% if field.required %}required{% endif %}>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Email ── #}
{% elif field.type == 'email' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<input type="email" class="form-control" name="field_{{ fid }}"
value="{{ saved }}" placeholder="{{ field.placeholder or 'name@example.com' }}"
{% if field.required %}required{% endif %}>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Checkbox ── #}
{% elif field.type == 'checkbox' %}
<div class="form-check mt-1">
<input class="form-check-input" type="checkbox" name="field_{{ fid }}"
id="f_{{ fid }}" value="true" {{ 'checked' if saved == 'true' }}>
<label class="form-check-label" for="f_{{ fid }}">
{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}
</label>
</div>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Checkbox group ── #}
{% elif field.type == 'checkbox_group' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
{% for opt in field.options %}
<div class="form-check">
<input class="form-check-input" type="checkbox" name="field_{{ fid }}"
id="cg_{{ fid }}_{{ loop.index0 }}" value="{{ opt }}"
{{ 'checked' if opt in (saved if saved is iterable and saved is not string else []) }}>
<label class="form-check-label" for="cg_{{ fid }}_{{ loop.index0 }}">{{ opt }}</label>
</div>
{% endfor %}
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Radio ── #}
{% elif field.type == 'radio' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
{% for opt in field.options %}
<div class="form-check">
<input class="form-check-input" type="radio" name="field_{{ fid }}"
id="rg_{{ fid }}_{{ loop.index0 }}" value="{{ opt }}"
{{ 'checked' if saved == opt }}>
<label class="form-check-label" for="rg_{{ fid }}_{{ loop.index0 }}">{{ opt }}</label>
</div>
{% endfor %}
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Select / Dropdown ── #}
{% elif field.type == 'select' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<select class="form-select" name="field_{{ fid }}" {% if field.required %}required{% endif %}>
<option value="">— Select —</option>
{% for opt in field.options %}
<option value="{{ opt }}" {{ 'selected' if saved == opt }}>{{ opt }}</option>
{% endfor %}
</select>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Rating (stars) ── #}
{% elif field.type == 'rating' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<div class="rating-stars" data-rating="{{ saved or 0 }}">
<input type="hidden" name="field_{{ fid }}" id="rating_input_{{ fid }}" value="{{ saved or 0 }}">
{% for i in range(1, 6) %}
<button type="button" data-val="{{ i }}" data-target="rating_input_{{ fid }}"
class="{{ 'on' if (saved|int) >= i }}"
onclick="setRating(this)"></button>
{% endfor %}
</div>
</div>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Rating 10 ── #}
{% elif item.scoring_type == 'rating_10' %}
<div class="mb-2">
<label class="form-label small">Rating (110)</label>
<div class="d-flex flex-wrap gap-2">
{% for v in range(1,11) %}
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="item_{{ result.id }}_score"
id="r10_{{ result.id }}_{{ v }}" value="{{ v }}"
{{ 'checked' if result.score == v }}>
<label class="form-check-label" for="r10_{{ result.id }}_{{ v }}">{{ v }}</label>
</div>
{% endfor %}
{# ── Image / Photo upload ── #}
{% elif field.type == 'image' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
{% if saved %}
<img src="{{ url_for('static', filename=saved) }}" class="photo-thumb" alt="Uploaded photo">
{% endif %}
<div class="upload-zone">
<input type="file" name="field_{{ fid }}" accept="image/*"
onchange="showFileName(this)">
<i class="bi bi-cloud-upload"></i>
<span>Click or drag to upload</span>
<span class="file-name" id="fname_{{ fid }}">
{% if saved %}{{ saved.split('/')[-1] }}{% endif %}
</span>
</div>
</div>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Signature ── #}
{% elif field.type == 'signature' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<div class="signature-pad-wrap">
<canvas id="sig_{{ fid }}" data-field="field_{{ fid }}"></canvas>
<button type="button" class="sig-clear" onclick="clearSig('sig_{{ fid }}')">Clear</button>
<input type="hidden" name="field_{{ fid }}" id="field_{{ fid }}" value="{{ saved }}">
</div>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{# ── Table ── #}
{% elif field.type == 'table' %}
<label class="field-lbl">{{ field.label }}{% if field.required %}<span class="required-mark"> *</span>{% endif %}</label>
<div style="overflow:auto;flex:1;min-height:0;">
<table class="tbl-field">
<thead><tr>
{% for hdr in (field.col_headers or ['Column 1','Column 2','Column 3']) %}
<th>{{ hdr }}</th>
{% endfor %}
</tr></thead>
<tbody>
{% set tbl_data = saved if saved is iterable and saved is not string else [] %}
{% for r in range(field.table_rows or 3) %}
<tr>
{% set row_data = tbl_data[r] if r < tbl_data|length else {} %}
{% for hdr in (field.col_headers or ['Column 1','Column 2','Column 3']) %}{% set c_idx = loop.index0 %}
<td>
<input type="text" class="tbl-input"
name="field_{{ fid }}_r{{ r }}_c{{ c_idx }}"
value="{{ row_data.get(hdr, '') }}">
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if field.help_text %}<div class="help-text">{{ field.help_text }}</div>{% endif %}
{% endif %}
<div class="row g-2">
<div class="col-md-6">
<textarea class="form-control form-control-sm" name="item_{{ result.id }}_comments"
rows="2" placeholder="Comments (optional)">{{ result.comments or '' }}</textarea>
</div>
<div class="col-md-6">
{% if result.photo_path %}
<div class="mb-1">
<img src="{{ url_for('static', filename=result.photo_path) }}"
class="img-thumbnail" style="max-height:80px;" alt="Photo">
</div>
{% endif %}
<input type="file" class="form-control form-control-sm"
name="item_{{ result.id }}_photo" accept="image/*">
</div>
</div>
</div>
{% endfor %}
</div>
{% endfor %}
{# Bottom submit bar #}
<div class="d-flex justify-content-end gap-2 mt-4 pb-4">
<button type="submit" name="action" value="save" class="btn btn-outline-secondary">
<i class="bi bi-floppy"></i> Save Progress
</button>
<button type="submit" name="action" value="complete" class="btn btn-success btn-lg"
onclick="return confirm('Mark this inspection as complete? This cannot be undone.')">
<i class="bi bi-check-circle-fill"></i> Complete Inspection
</button>
{% else %}
<div class="text-center py-5 text-muted">
<i class="bi bi-layout-text-sidebar-reverse" style="font-size:2.5rem;opacity:.3;"></i>
<p class="mt-2 mb-0">This template has no form fields. Please add fields in the template editor.</p>
</div>
{% endif %}
</div>
{# ── Sticky footer ── #}
<div class="insp-footer">
<div class="meta">
Started: <strong>{{ inspection.inspection_date.strftime('%Y-%m-%d %H:%M') }}</strong>
&nbsp;·&nbsp; Template: <strong>{{ inspection.template.name }}</strong>
</div>
<div class="d-flex gap-2">
<button type="submit" name="action" value="draft" class="btn btn-sm btn-outline-light">
<i class="bi bi-floppy"></i> Save Draft
</button>
<button type="submit" name="action" value="submit" class="btn btn-success"
onclick="collectSignatures(); return confirmSubmit();">
<i class="bi bi-check-circle-fill"></i> Submit Inspection
</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block extra_js %}
<script>
// Auto-mark item cards as answered on interaction
document.querySelectorAll('input[type=radio]').forEach(r => {
r.addEventListener('change', () => {
const card = r.closest('.item-card');
if (card) card.classList.add('answered');
// ── Rating stars ─────────────────────────────────────────────────────────────
function setRating(btn) {
const group = btn.closest('.rating-stars');
const val = parseInt(btn.dataset.val);
const input = document.getElementById(btn.dataset.target);
group.dataset.rating = val;
if (input) input.value = val;
group.querySelectorAll('button').forEach(b => {
b.classList.toggle('on', parseInt(b.dataset.val) <= val);
});
}
// ── File upload label ─────────────────────────────────────────────────────────
function showFileName(input) {
const wrap = input.closest('.upload-zone');
const label = wrap ? wrap.querySelector('.file-name') : null;
if (label && input.files.length) {
label.textContent = input.files[0].name;
}
}
// ── Signature pads ────────────────────────────────────────────────────────────
const sigPads = {};
document.querySelectorAll('[id^="sig_"]').forEach(canvas => {
const fid = canvas.id;
const input = document.getElementById(canvas.dataset.field);
const ctx = canvas.getContext('2d');
let drawing = false;
// size canvas to its container
const resize = () => {
const w = canvas.parentElement.clientWidth;
const h = canvas.parentElement.clientHeight || 80;
canvas.width = w;
canvas.height = h;
ctx.strokeStyle = '#0f172a';
ctx.lineWidth = 1.8;
ctx.lineCap = 'round';
};
resize();
new ResizeObserver(resize).observe(canvas.parentElement);
// Restore saved signature
if (input && input.value && input.value.startsWith('data:')) {
const img = new Image();
img.onload = () => ctx.drawImage(img, 0, 0);
img.src = input.value;
}
canvas.addEventListener('mousedown', e => { drawing = true; ctx.beginPath(); ctx.moveTo(...pos(e, canvas)); });
canvas.addEventListener('mousemove', e => { if (!drawing) return; ctx.lineTo(...pos(e, canvas)); ctx.stroke(); });
canvas.addEventListener('mouseup', () => { drawing = false; if (input) input.value = canvas.toDataURL(); });
canvas.addEventListener('mouseleave', () => { drawing = false; });
// Touch
canvas.addEventListener('touchstart', e => { e.preventDefault(); drawing = true; ctx.beginPath(); ctx.moveTo(...pos(e.touches[0], canvas)); });
canvas.addEventListener('touchmove', e => { e.preventDefault(); if (!drawing) return; ctx.lineTo(...pos(e.touches[0], canvas)); ctx.stroke(); });
canvas.addEventListener('touchend', e => { drawing = false; if (input) input.value = canvas.toDataURL(); });
sigPads[fid] = { ctx, canvas, input };
});
function pos(e, canvas) {
const r = canvas.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
}
function clearSig(id) {
const p = sigPads[id];
if (!p) return;
p.ctx.clearRect(0, 0, p.canvas.width, p.canvas.height);
if (p.input) p.input.value = '';
}
function collectSignatures() {
// Ensure all signature canvases flush their dataURL to hidden inputs
Object.values(sigPads).forEach(p => {
if (p.input && p.canvas.width > 0) {
p.input.value = p.canvas.toDataURL();
}
});
}
// ── Submit confirmation ───────────────────────────────────────────────────────
function confirmSubmit() {
return confirm('Submit this inspection? This action cannot be undone.');
}
</script>
{% endblock %}
+260 -137
View File
@@ -1,141 +1,264 @@
{% extends "base.html" %}
{% block title %}Inspection #{{ inspection.id }}{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h2>Inspection Report</h2>
<p class="text-muted mb-0">{{ inspection.template.name }} · {{ inspection.inspection_date.strftime('%B %d, %Y %H:%M') }}</p>
</div>
<div class="d-flex gap-2">
{% if current_user.role in ['admin','supervisor'] %}
<form method="post" action="{{ url_for('inspections.delete', inspection_id=inspection.id) }}"
onsubmit="return confirm('Delete this inspection?')">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash3"></i> Delete</button>
</form>
{% endif %}
<a href="{{ url_for('inspections.index') }}" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-arrow-left"></i> Back
</a>
</div>
</div>
{% block title %}Inspection #{{ inspection.id }} — Results{% endblock %}
{# Summary cards #}
<div class="row mb-4">
<div class="col-md-3">
<div class="card text-center shadow-sm h-100">
<div class="card-body">
<p class="text-muted small mb-1">Overall Score</p>
{% if inspection.overall_score %}
<h2 class="fw-bold text-{{ 'success' if inspection.overall_score >= 90 else 'warning' if inspection.overall_score >= 70 else 'danger' }}">
{{ inspection.overall_score }}%
</h2>
{% else %}<h2 class="text-muted"></h2>{% endif %}
</div>
</div>
</div>
<div class="col-md-3">
<div class="card text-center shadow-sm h-100">
<div class="card-body">
<p class="text-muted small mb-1">Status</p>
<span class="badge fs-6 bg-{{ 'success' if inspection.status == 'completed' else 'danger' if inspection.status == 'flagged' else 'secondary' }}">
{{ inspection.status|replace('_',' ')|title }}
</span>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card text-center shadow-sm h-100">
<div class="card-body">
<p class="text-muted small mb-1">Facility / Area</p>
<p class="fw-semibold mb-0">{{ inspection.facility.name }}</p>
<small class="text-muted">{{ inspection.area.name if inspection.area else '—' }}</small>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card text-center shadow-sm h-100">
<div class="card-body">
<p class="text-muted small mb-1">Inspector</p>
<p class="fw-semibold mb-0">{{ inspection.inspector.username }}</p>
{% if inspection.completed_at %}
<small class="text-muted">Completed {{ inspection.completed_at.strftime('%Y-%m-%d %H:%M') }}</small>
{% endif %}
</div>
</div>
</div>
</div>
{% block extra_css %}
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
body { font-family:'DM Sans', sans-serif; background:#eef0f4; }
.insp-wrap { max-width:1000px; margin:0 auto; padding:0 1rem 4rem; }
.insp-header {
background:#1a1d23; color:#fff; padding:1.1rem 1.75rem;
border-radius:12px 12px 0 0;
display:flex; align-items:center; justify-content:space-between; gap:1rem;
}
.insp-header h4 { margin:0; font-weight:600; font-size:1.05rem; }
.insp-header .sub { font-size:.78rem; color:#94a3b8; margin-top:.2rem; }
.score-badge {
font-size:1.5rem; font-weight:700; padding:.4rem 1rem;
border-radius:8px; min-width:80px; text-align:center;
}
.insp-body {
background:#fff; border:1px solid #e2e8f0; border-top:none;
border-radius:0 0 12px 12px; padding:1.75rem; overflow-x:auto;
}
.meta-row { display:flex; flex-wrap:wrap; gap:1.5rem; margin-bottom:1.5rem; padding-bottom:1rem; border-bottom:1px solid #e2e8f0; }
.meta-item { display:flex; flex-direction:column; }
.meta-item .lbl { font-size:.72rem; color:#94a3b8; font-weight:500; text-transform:uppercase; letter-spacing:.04em; }
.meta-item .val { font-size:.9rem; color:#0f172a; font-weight:500; margin-top:.1rem; }
{% if inspection.notes %}
<div class="alert alert-light border mb-4"><strong>Notes:</strong> {{ inspection.notes }}</div>
{% endif %}
{# Checklist results by category #}
{% for category, results in categories.items() %}
<div class="card shadow-sm mb-3">
<div class="card-header bg-light">
<h6 class="mb-0"><i class="bi bi-folder2"></i> {{ category }}</h6>
</div>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr><th>Item</th><th>Type</th><th>Result</th><th>Comments</th><th>Photo</th></tr>
</thead>
<tbody>
{% for r in results %}
<tr>
<td>{{ r.checklist_item.item_description }}</td>
<td><span class="badge bg-secondary" style="font-size:.65rem;">{{ r.checklist_item.scoring_type|replace('_',' ') }}</span></td>
<td>
{% if r.checklist_item.scoring_type == 'pass_fail' %}
{% if r.passed is none %}<span class="text-muted"></span>
{% elif r.passed %}<span class="badge bg-success">Pass</span>
{% else %}<span class="badge bg-danger">Fail</span>{% endif %}
{% else %}
{% if r.score is not none %}<strong>{{ r.score }}</strong>
{% else %}<span class="text-muted"></span>{% endif %}
{% endif %}
</td>
<td><small class="text-muted">{{ r.comments or '—' }}</small></td>
<td>
{% if r.photo_path %}
<a href="{{ url_for('static', filename=r.photo_path) }}" target="_blank">
<img src="{{ url_for('static', filename=r.photo_path) }}" style="max-height:40px;" class="img-thumbnail">
</a>
{% else %}—{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endfor %}
{# Issues #}
{% if issues %}
<div class="card shadow-sm mt-4">
<div class="card-header bg-danger text-white">
<h6 class="mb-0"><i class="bi bi-exclamation-triangle"></i> Issues Logged ({{ issues|length }})</h6>
</div>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr><th>Severity</th><th>Area</th><th>Description</th><th>Status</th><th></th></tr>
</thead>
<tbody>
{% for issue in issues %}
<tr>
<td><span class="badge bg-{{ 'danger' if issue.severity in ['critical','high'] else 'warning text-dark' if issue.severity == 'medium' else 'secondary' }}">{{ issue.severity|title }}</span></td>
<td>{{ issue.area.name }}</td>
<td>{{ issue.description[:80] }}{% if issue.description|length > 80 %}…{% endif %}</td>
<td><span class="badge bg-{{ 'success' if issue.status == 'resolved' else 'warning text-dark' if issue.status == 'in_progress' else 'secondary' }}">{{ issue.status|replace('_',' ')|title }}</span></td>
<td><a href="{{ url_for('issues.view', issue_id=issue.id) }}" class="btn btn-sm btn-outline-secondary">View</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
/* Grid (read-only, same geometry as editor) */
.form-grid {
display:grid; grid-template-columns:repeat(12,72px);
grid-auto-rows:auto; gap:4px 8px; width:max-content;
}
.fg-cell { overflow:hidden; display:flex; flex-direction:column; padding:.22rem .55rem; }
.fg-cell .field-lbl { font-size:.74rem; font-weight:500; color:#64748b; margin-bottom:.2rem; display:block; }
.fg-cell .field-val {
font-size:.82rem; color:#0f172a; background:#f8fafc;
border:1px solid #e2e8f0; border-radius:5px;
padding:.25rem .4rem; flex:1; min-height:28px; word-break:break-word;
white-space:pre-wrap;
}
.fg-cell .field-val.empty { color:#94a3b8; font-style:italic; }
.section-divider { height:100%; display:flex; align-items:center; border-top:2px solid #e2e8f0; padding-top:.4rem; }
.section-divider strong { font-weight:700; color:#374151; font-size:.95rem; }
.rating-display { color:#f59e0b; font-size:1.1rem; letter-spacing:.05rem; }
.tbl-view { width:100%; border-collapse:collapse; font-size:.8rem; }
.tbl-view th { background:#f1f5f9; font-weight:600; color:#374151; padding:.3rem .5rem; border:1px solid #e2e8f0; font-size:.78rem; }
.tbl-view td { border:1px solid #e2e8f0; padding:.25rem .5rem; color:#0f172a; }
.photo-thumb { max-height:120px; border-radius:6px; border:1px solid #e2e8f0; }
.sig-img { max-height:80px; border-radius:4px; border:1px solid #e2e8f0; background:#fff; }
</style>
{% endblock %}
{% block content %}
<div class="insp-wrap mt-3">
{# ── Action bar ── #}
<div class="d-flex justify-content-between align-items-center mb-3">
<a href="{{ url_for('inspections.index') }}" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-arrow-left"></i> Back to Inspections
</a>
<div class="d-flex gap-2">
<button onclick="window.print()" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-printer"></i> Print
</button>
{% if current_user.role in ['admin','supervisor'] %}
<form method="post" action="{{ url_for('inspections.delete', inspection_id=inspection.id) }}"
onsubmit="return confirm('Delete this inspection permanently?')">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash3"></i> Delete</button>
</form>
{% endif %}
</div>
</div>
{# ── Header ── #}
<div class="insp-header">
<div>
<h4><i class="bi bi-clipboard-check"></i> {{ inspection.template.name }}</h4>
<div class="sub">
{{ inspection.facility.name }}{% if inspection.area %} · {{ inspection.area.name }}{% endif %}
&nbsp;·&nbsp; Inspector: <strong style="color:#e2e8f0;">{{ inspection.inspector.username }}</strong>
</div>
</div>
<div class="d-flex align-items-center gap-2">
<span class="badge bg-{{ 'success' if inspection.status == 'completed' else 'danger' if inspection.status == 'flagged' else 'secondary' }} fs-6">
{{ inspection.status|replace('_',' ')|title }}
</span>
{% if inspection.overall_score is not none %}
<div class="score-badge bg-{{ 'success' if inspection.overall_score >= 90 else 'warning' if inspection.overall_score >= 70 else 'danger' }} text-white">
{{ inspection.overall_score }}%
</div>
{% endif %}
</div>
</div>
<div class="insp-body">
{# ── Meta row ── #}
<div class="meta-row">
<div class="meta-item">
<span class="lbl">Date</span>
<span class="val">{{ inspection.inspection_date.strftime('%B %d, %Y %H:%M') }}</span>
</div>
{% if inspection.completed_at %}
<div class="meta-item">
<span class="lbl">Completed</span>
<span class="val">{{ inspection.completed_at.strftime('%B %d, %Y %H:%M') }}</span>
</div>
{% endif %}
<div class="meta-item">
<span class="lbl">Template</span>
<span class="val">{{ inspection.template.name }}</span>
</div>
<div class="meta-item">
<span class="lbl">Frequency</span>
<span class="val">{{ inspection.template.frequency|title }}</span>
</div>
</div>
{# ── Form field responses ── #}
{% if form_fields %}
<div class="form-grid">
{% for field in form_fields %}
{% set fid = field.id %}
{% set val = form_data.get(fid) %}
<div class="fg-cell"
style="grid-column: {{ field.col }} / span {{ field.colSpan }};
grid-row: {{ field.row }} / span {{ field.rowSpan }};">
{% if field.type == 'section' %}
<div class="section-divider"><strong>{{ field.label }}</strong></div>
{% elif field.type == 'label' %}
{% set fs_map = {'small':'0.78rem','normal':'0.9rem','large':'1.05rem','x-large':'1.25rem'} %}
<div style="font-size:{{ fs_map.get(field.font_size or 'normal','0.9rem') }};
font-weight:{{ field.font_weight or 'normal' }};color:#374151;
line-height:1.5;white-space:pre-wrap;overflow:hidden;height:100%;">
{{ field.text_content or '' }}
</div>
{% elif field.type in ('button_submit','button_print','button_email') %}
{# not shown in read-only view #}
{% elif field.type == 'image' %}
<span class="field-lbl">{{ field.label }}</span>
{% if val %}
<a href="{{ url_for('static', filename=val) }}" target="_blank">
<img src="{{ url_for('static', filename=val) }}" class="photo-thumb" alt="Photo">
</a>
{% else %}
<div class="field-val empty">No photo uploaded</div>
{% endif %}
{% elif field.type == 'signature' %}
<span class="field-lbl">{{ field.label }}</span>
{% if val and val.startswith('data:') %}
<img src="{{ val }}" class="sig-img" alt="Signature">
{% else %}
<div class="field-val empty">No signature</div>
{% endif %}
{% elif field.type == 'rating' %}
<span class="field-lbl">{{ field.label }}</span>
<div class="field-val">
{% if val %}
<span class="rating-display">
{% for i in range(1, 6) %}{{ '★' if i <= (val|int) else '☆' }}{% endfor %}
</span>
<span class="text-muted ms-1" style="font-size:.75rem;">({{ val }}/5)</span>
{% else %}
<span class="empty">Not rated</span>
{% endif %}
</div>
{% elif field.type == 'checkbox' %}
<span class="field-lbl">{{ field.label }}</span>
<div class="field-val">
{% if val == 'true' %}
<span class="text-success"><i class="bi bi-check-circle-fill"></i> Checked</span>
{% else %}
<span class="text-muted"><i class="bi bi-circle"></i> Unchecked</span>
{% endif %}
</div>
{% elif field.type == 'checkbox_group' %}
<span class="field-lbl">{{ field.label }}</span>
<div class="field-val">
{% if val %}
{% for item in (val if val is iterable and val is not string else []) %}
<span class="badge bg-primary me-1">{{ item }}</span>
{% else %}
<span class="empty">None selected</span>
{% endfor %}
{% else %}
<span class="empty">None selected</span>
{% endif %}
</div>
{% elif field.type == 'table' %}
<span class="field-lbl">{{ field.label }}</span>
{% if val and val is iterable and val is not string %}
<div style="overflow:auto;">
<table class="tbl-view">
<thead><tr>
{% for hdr in (field.col_headers or ['Column 1']) %}<th>{{ hdr }}</th>{% endfor %}
</tr></thead>
<tbody>
{% for row in val %}
<tr>
{% for hdr in (field.col_headers or ['Column 1']) %}
<td>{{ row.get(hdr, '') }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="field-val empty">No data</div>
{% endif %}
{% else %}
{# text, textarea, number, date, email, radio, select ── #}
<span class="field-lbl">{{ field.label }}</span>
<div class="field-val {{ 'empty' if not val }}">{{ val or 'Not answered' }}</div>
{% endif %}
</div>
{% endfor %}
</div>
{% else %}
<p class="text-muted">No form fields found for this template.</p>
{% endif %}
{# ── Issues ── #}
{% if issues %}
<hr class="mt-4">
<h6 class="text-danger"><i class="bi bi-exclamation-triangle"></i> Issues Logged ({{ issues|length }})</h6>
<div class="table-responsive">
<table class="table table-sm table-hover">
<thead class="table-light">
<tr><th>Severity</th><th>Area</th><th>Description</th><th>Status</th><th></th></tr>
</thead>
<tbody>
{% for issue in issues %}
<tr>
<td><span class="badge bg-{{ 'danger' if issue.severity in ['critical','high'] else 'warning text-dark' if issue.severity == 'medium' else 'secondary' }}">{{ issue.severity|title }}</span></td>
<td>{{ issue.area.name }}</td>
<td>{{ issue.description[:80] }}{% if issue.description|length > 80 %}…{% endif %}</td>
<td><span class="badge bg-{{ 'success' if issue.status == 'resolved' else 'warning text-dark' if issue.status == 'in_progress' else 'secondary' }}">{{ issue.status|replace('_',' ')|title }}</span></td>
<td><a href="{{ url_for('issues.view', issue_id=issue.id) }}" class="btn btn-sm btn-outline-secondary">View</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
</div>
{% endblock %}