06/22 Fix inspection doesn't send notifications

This commit is contained in:
Nguyen Ngo
2026-06-22 12:36:15 -04:00
parent c33dcabe6f
commit 5c9f12289c
+32 -15
View File
@@ -401,7 +401,18 @@ def create_inspection():
f'#{inspection.id} via mobile API)',
)
# ── Commit inspection + any staged rows ───────────────────────────────
# Commit BEFORE firing notifications so the inspection record is always
# persisted even if notify_by_matrix raises (e.g. a DB hiccup querying
# the notification matrix, a missing table from a pending migration, or
# any other transient error). Without this ordering, a notification
# failure would 500 the entire request, roll back the transaction, and
# leave the inspection unsaved — causing the iPad to retry indefinitely.
db.session.commit()
# ── Notifications ─────────────────────────────────────────────────────
# Best-effort: log and continue on any failure. The inspection is already
# committed above, so notification errors never prevent saving.
if status == 'completed':
score_display = f'{overall_score:.1f}%' if overall_score is not None else 'N/A'
try:
@@ -411,21 +422,27 @@ def create_inspection():
except RuntimeError:
inspection_link = f'/inspections/{inspection.id}'
notify_by_matrix(
event_type = 'inspection_completed',
title = f'Inspection #{inspection.id} Completed (Mobile)',
body = (
f'{user.username} completed an inspection at '
f'{facility.name} using the "{template.name}" template. '
f'Overall score: {score_display}.'
),
link = inspection_link,
inspection_id = inspection.id,
facility_id = facility_id,
exclude_user_ids = {user.id},
)
db.session.commit()
try:
notify_by_matrix(
event_type = 'inspection_completed',
title = f'Inspection #{inspection.id} Completed (Mobile)',
body = (
f'{user.username} completed an inspection at '
f'{facility.name} using the "{template.name}" template. '
f'Overall score: {score_display}.'
),
link = inspection_link,
inspection_id = inspection.id,
facility_id = facility_id,
exclude_user_ids = {user.id},
)
db.session.commit() # persist notification rows added by notify()
except Exception as exc:
logger.error(
'API INSPECTIONS | notification error | inspection_id=%d | error=%s',
inspection.id, exc,
)
db.session.rollback() # discard any partial notification rows
# ── Post-commit audit logging ──────────────────────────────────────────
# All log_action() calls must come AFTER db.session.commit() because