Mar 04 2026: Implement customer's view functionalities - Phase 4

This commit is contained in:
2026-03-04 13:31:11 -05:00
parent 0a7259ae72
commit 59f46f2110
5 changed files with 276 additions and 4 deletions
+10
View File
@@ -13,6 +13,13 @@ EVENT_ISSUE_FOLLOW = 'issue_follow_update'
EVENT_INSPECTION_DONE = 'inspection_completed' EVENT_INSPECTION_DONE = 'inspection_completed'
EVENT_SLA_ALERT = 'sla_alert' EVENT_SLA_ALERT = 'sla_alert'
# ── Customer portal events ─────────────────────────────────────────────────
# Fired when an inspection completes or an issue is created/updated at a
# facility the customer is assigned to. Separate constants allow customers
# to manage these preferences independently from internal staff events.
EVENT_CUSTOMER_INSPECTION_DONE = 'customer_inspection_completed'
EVENT_CUSTOMER_ISSUE_UPDATED = 'customer_issue_updated'
ALL_EVENT_TYPES = { ALL_EVENT_TYPES = {
EVENT_ISSUE_ASSIGNED: 'Issue assigned to me', EVENT_ISSUE_ASSIGNED: 'Issue assigned to me',
EVENT_ISSUE_STATUS: 'Issue status changed', EVENT_ISSUE_STATUS: 'Issue status changed',
@@ -20,6 +27,9 @@ ALL_EVENT_TYPES = {
EVENT_ISSUE_FOLLOW: 'Updates on followed issues', EVENT_ISSUE_FOLLOW: 'Updates on followed issues',
EVENT_INSPECTION_DONE: 'Inspection completed', EVENT_INSPECTION_DONE: 'Inspection completed',
EVENT_SLA_ALERT: 'SLA at-risk / breached alerts', EVENT_SLA_ALERT: 'SLA at-risk / breached alerts',
# Customer-facing — only relevant for customer role accounts
EVENT_CUSTOMER_INSPECTION_DONE: 'Inspection completed at my facility (portal)',
EVENT_CUSTOMER_ISSUE_UPDATED: 'Issue created or updated at my facility (portal)',
} }
+35 -2
View File
@@ -15,8 +15,11 @@ from app.models.user import User
from app.utils.forms import StartInspectionForm, IssueForm from app.utils.forms import StartInspectionForm, IssueForm
from app.utils.decorators import supervisor_required from app.utils.decorators import supervisor_required
from app.utils.pdf_export import generate_inspection_pdf from app.utils.pdf_export import generate_inspection_pdf
from app.utils.notifications import notify from app.utils.notifications import notify, notify_customers_for_facility
from app.models.notification import EVENT_INSPECTION_DONE, EVENT_ISSUE_ASSIGNED from app.models.notification import (
EVENT_INSPECTION_DONE, EVENT_ISSUE_ASSIGNED,
EVENT_CUSTOMER_INSPECTION_DONE, EVENT_CUSTOMER_ISSUE_UPDATED,
)
from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE, ACTION_EXPORT from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE, ACTION_EXPORT
from app.utils.scope import get_customer_scope from app.utils.scope import get_customer_scope
@@ -347,6 +350,19 @@ def execute(inspection_id):
event_type = EVENT_INSPECTION_DONE, event_type = EVENT_INSPECTION_DONE,
send_email = True, send_email = True,
) )
# ── Notify customer portal users for this facility ──────────
notify_customers_for_facility(
facility_id = inspection.facility_id,
event_type = EVENT_CUSTOMER_INSPECTION_DONE,
title = f'Inspection Completed at {inspection.facility.name}',
body = (
f'An inspection using the "{inspection.template.name}" template '
f'was completed at {inspection.facility.name}. '
f'Overall score: {score_display}.'
),
link = url_for('inspections.view', inspection_id=inspection.id),
inspection_id = inspection.id,
)
db.session.commit() # Commit notifications db.session.commit() # Commit notifications
log_action(ACTION_UPDATE, 'Inspection', inspection.id, log_action(ACTION_UPDATE, 'Inspection', inspection.id,
f'{inspection.template.name} @ {inspection.facility.name}', f'{inspection.template.name} @ {inspection.facility.name}',
@@ -530,6 +546,23 @@ def flag_issue(inspection_id):
) )
db.session.commit() # Commit notification db.session.commit() # Commit notification
# ── Notify customer portal users for this facility ──────────
notify_customers_for_facility(
facility_id = inspection.facility_id,
event_type = EVENT_CUSTOMER_ISSUE_UPDATED,
title = f'New Issue #{issue.id} at {inspection.facility.name}',
body = (
f'A new {issue.severity.title()}-severity issue has been logged '
f'in {issue.area.name} at {inspection.facility.name} '
f'during inspection #{inspection_id}. '
f'Description: {issue.description[:120]}'
f'{"" if len(issue.description) > 120 else ""}'
),
link = url_for('issues.view', issue_id=issue.id),
issue_id = issue.id,
)
db.session.commit()
flash('Issue logged successfully.', 'success') flash('Issue logged successfully.', 'success')
return redirect(url_for('inspections.execute', inspection_id=inspection_id)) return redirect(url_for('inspections.execute', inspection_id=inspection_id))
+35 -1
View File
@@ -9,10 +9,11 @@ from app.models.user import User
from app.models.notification import ( from app.models.notification import (
EVENT_ISSUE_ASSIGNED, EVENT_ISSUE_STATUS, EVENT_ISSUE_ASSIGNED, EVENT_ISSUE_STATUS,
EVENT_ISSUE_COMMENT, EVENT_ISSUE_FOLLOW, EVENT_ISSUE_COMMENT, EVENT_ISSUE_FOLLOW,
EVENT_CUSTOMER_ISSUE_UPDATED,
) )
from app.utils.forms import IssueForm, IssueUpdateForm from app.utils.forms import IssueForm, IssueUpdateForm
from app.utils.decorators import supervisor_required from app.utils.decorators import supervisor_required
from app.utils.notifications import notify from app.utils.notifications import notify, notify_customers_for_facility
from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE from app.utils.audit import log_action, ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE
from app.utils.scope import get_customer_scope from app.utils.scope import get_customer_scope
from app.utils.sla import sla_status from app.utils.sla import sla_status
@@ -265,6 +266,22 @@ def view(issue_id):
exclude_user_ids = exclude_ids, exclude_user_ids = exclude_ids,
) )
# ── Notify customer portal users for this facility ──────────
facility_id = issue.area.facility_id if issue.area else None
if facility_id:
changes_summary = '; '.join(changes) if changes else 'updated'
notify_customers_for_facility(
facility_id = facility_id,
event_type = EVENT_CUSTOMER_ISSUE_UPDATED,
title = f'Issue #{issue.id} Updated at {issue.area.facility.name}',
body = (
f'Issue #{issue.id} ({issue.severity.title()} severity) '
f'in {issue.area.name} was updated: {changes_summary}. '
f'Current status: {issue.status.replace("_", " ").title()}.'
),
link = url_for('issues.view', issue_id=issue.id),
issue_id = issue.id,
)
db.session.commit() # Commit all notifications db.session.commit() # Commit all notifications
log_action(ACTION_UPDATE, 'Issue', issue.id, log_action(ACTION_UPDATE, 'Issue', issue.id,
f'#{issue.id} in {issue.area.name}', f'#{issue.id} in {issue.area.name}',
@@ -379,6 +396,23 @@ def create():
) )
db.session.commit() db.session.commit()
# ── Notify customer portal users for this facility ──────────
area = Area.query.get(issue.area_id)
if area:
notify_customers_for_facility(
facility_id = area.facility_id,
event_type = EVENT_CUSTOMER_ISSUE_UPDATED,
title = f'New Issue #{issue.id} at {area.facility.name}',
body = (
f'A new {issue.severity.title()}-severity issue has been logged '
f'in {area.name} at {area.facility.name}. '
f'Description: {issue.description[:120]}'
f'{"" if len(issue.description) > 120 else ""}'
),
link = url_for('issues.view', issue_id=issue.id),
issue_id = issue.id,
)
db.session.commit()
flash('Issue created.', 'success') flash('Issue created.', 'success')
return redirect(url_for('issues.index')) return redirect(url_for('issues.index'))
+97 -1
View File
@@ -32,8 +32,23 @@
</div> </div>
</div> </div>
{# ── Internal staff events ── #}
{% set internal_events = [
'issue_assigned', 'issue_status', 'issue_comment',
'issue_follow_update', 'inspection_completed', 'sla_alert'
] %}
{# ── Customer portal events ── #}
{% set customer_events = [
'customer_inspection_completed', 'customer_issue_updated'
] %}
<ul class="list-group list-group-flush"> <ul class="list-group list-group-flush">
{% for event_type, label in event_types.items() %} <li class="list-group-item bg-light py-1 px-3">
<small class="text-muted fw-semibold text-uppercase" style="font-size:.7rem;">
<i class="bi bi-people-fill me-1"></i>Internal Events
</small>
</li>
{% for event_type, label in event_types.items() if event_type in internal_events %}
{% set pref = prefs_map.get(event_type) %} {% set pref = prefs_map.get(event_type) %}
{% set email_on = pref.email_enabled if pref else True %} {% set email_on = pref.email_enabled if pref else True %}
{% set digest_on = pref.digest_mode if pref else False %} {% set digest_on = pref.digest_mode if pref else False %}
@@ -107,6 +122,87 @@
</div> </div>
</li> </li>
{% endfor %} {% endfor %}
<li class="list-group-item bg-light py-1 px-3">
<small class="text-muted fw-semibold text-uppercase" style="font-size:.7rem;">
<i class="bi bi-building me-1"></i>Customer Portal Events
</small>
</li>
{% for event_type, label in event_types.items() if event_type in customer_events %}
{% set pref = prefs_map.get(event_type) %}
{% set email_on = pref.email_enabled if pref else True %}
{% set digest_on = pref.digest_mode if pref else False %}
{% set freq = pref.digest_frequency if pref else 'daily' %}
<li class="list-group-item px-3 py-3" id="row-{{ event_type }}">
<div class="row align-items-center">
{# Event label #}
<div class="col-md-4">
<span class="fw-semibold" style="font-size:.9rem;">{{ label }}</span>
<span class="badge bg-success ms-1" style="font-size:.65rem;">Portal</span>
</div>
{# Email toggle #}
<div class="col-md-2 text-center">
<div class="form-check form-switch d-inline-block">
<input class="form-check-input email-toggle"
type="checkbox"
name="email_{{ event_type }}"
id="email_{{ event_type }}"
value="1"
data-event="{{ event_type }}"
{% if email_on %}checked{% endif %}>
<label class="form-check-label visually-hidden"
for="email_{{ event_type }}">Email</label>
</div>
</div>
{# Digest mode toggle #}
<div class="col-md-2 text-center">
<div class="form-check form-switch d-inline-block">
<input class="form-check-input digest-toggle"
type="checkbox"
name="digest_{{ event_type }}"
id="digest_{{ event_type }}"
value="1"
data-event="{{ event_type }}"
{% if digest_on %}checked{% endif %}
{% if not email_on %}disabled{% endif %}>
<label class="form-check-label visually-hidden"
for="digest_{{ event_type }}">Digest</label>
</div>
</div>
{# Digest frequency #}
<div class="col-md-3 text-center">
<select class="form-select form-select-sm freq-select"
name="freq_{{ event_type }}"
id="freq_{{ event_type }}"
style="width:auto;margin:auto;"
{% if not email_on or not digest_on %}disabled{% endif %}>
<option value="hourly" {% if freq == 'hourly' %}selected{% endif %}>Hourly</option>
<option value="daily" {% if freq == 'daily' %}selected{% endif %}>Daily</option>
</select>
</div>
{# Status label #}
<div class="col-md-1 text-end">
<span class="badge status-badge
{% if not email_on %}bg-secondary
{% elif digest_on %}bg-warning text-dark
{% else %}bg-success{% endif %}"
style="font-size:.65rem;"
id="badge-{{ event_type }}">
{% if not email_on %}Off
{% elif digest_on %}Digest
{% else %}Live{% endif %}
</span>
</div>
</div>
</li>
{% endfor %}
</ul> </ul>
</div> </div>
+99
View File
@@ -273,6 +273,105 @@ def _send_single_email(recipient, title, body, link):
# ── Digest delivery ──────────────────────────────────────────────────────────── # ── Digest delivery ────────────────────────────────────────────────────────────
# ── Customer portal notifications ─────────────────────────────────────────────
def notify_customers_for_facility(
facility_id: int,
event_type: str,
title: str,
body: str,
link: str = None,
issue_id: int = None,
inspection_id: int = None,
):
"""Dispatch in-app + email notifications to all customer users assigned
to the given facility.
Resolves assignments via CustomerAssignment rows:
- facility-scoped assignment (facility_id matches exactly)
- project-scoped assignment (facility belongs to the project, no facility_id set)
Respects each customer's NotificationPreference for the supplied event_type.
Best-effort: a failure on one recipient does not block others.
Parameters
----------
facility_id : The facility where the event occurred.
event_type : EVENT_CUSTOMER_INSPECTION_DONE or EVENT_CUSTOMER_ISSUE_UPDATED.
title : Short notification headline.
body : Full notification message.
link : Relative URL for 'View Details'.
issue_id : FK to issues.id (optional).
inspection_id : FK to inspections.id (optional).
"""
try:
from app.models.project import CustomerAssignment
from app.models.facility import Facility
from app.models.user import User
facility = Facility.query.get(facility_id)
if not facility:
logger.warning(
'notify_customers_for_facility | facility_id=%s not found', facility_id
)
return
# Collect distinct customer user IDs that have access to this facility
notified_user_ids = set()
# 1. Direct facility-scoped assignments
direct = CustomerAssignment.query.filter_by(facility_id=facility_id).all()
for a in direct:
notified_user_ids.add(a.user_id)
# 2. Project-scoped assignments (no facility_id) — if facility belongs to a project
if facility.project_id:
project_wide = CustomerAssignment.query.filter_by(
project_id=facility.project_id,
facility_id=None,
).all()
for a in project_wide:
notified_user_ids.add(a.user_id)
if not notified_user_ids:
logger.debug(
'notify_customers_for_facility | facility_id=%s | no customer assignments found',
facility_id,
)
return
for user_id in notified_user_ids:
user = User.query.get(user_id)
if not user or not user.active or user.role != 'customer':
continue
try:
notify(
recipient = user,
title = title,
body = body,
link = link,
issue_id = issue_id,
inspection_id = inspection_id,
event_type = event_type,
send_email = True,
)
logger.info(
'CUSTOMER NOTIFY | user=%s | facility_id=%s | event=%s',
user.username, facility_id, event_type,
)
except Exception as exc:
logger.error(
'CUSTOMER NOTIFY FAILED | user=%s | facility_id=%s | event=%s | error=%s',
user_id, facility_id, event_type, exc,
)
except Exception as exc:
logger.error(
'notify_customers_for_facility | unexpected error | facility_id=%s | error=%s',
facility_id, exc,
)
def send_pending_digests(frequency: str = 'daily'): def send_pending_digests(frequency: str = 'daily'):
"""Send digest emails for all users who have pending digest notifications. """Send digest emails for all users who have pending digest notifications.