Feb 02 2026: implement notification system
This commit is contained in:
+21
-1
@@ -31,10 +31,29 @@ def create_app(config_name='default'):
|
|||||||
app.jinja_env.globals['csrf_token'] = generate_csrf
|
app.jinja_env.globals['csrf_token'] = generate_csrf
|
||||||
app.jinja_env.globals['enumerate'] = enumerate
|
app.jinja_env.globals['enumerate'] = enumerate
|
||||||
|
|
||||||
|
# ── Inject unread notification count into every template context ──────
|
||||||
|
# This powers the red badge on the navbar bell icon without requiring
|
||||||
|
# individual routes to pass the count manually.
|
||||||
|
from flask_login import current_user
|
||||||
|
|
||||||
|
@app.context_processor
|
||||||
|
def inject_notification_count():
|
||||||
|
try:
|
||||||
|
if current_user.is_authenticated:
|
||||||
|
from app.models.notification import Notification
|
||||||
|
count = Notification.query.filter_by(
|
||||||
|
user_id=current_user.id, is_read=False
|
||||||
|
).count()
|
||||||
|
return {'unread_notification_count': count}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return {'unread_notification_count': 0}
|
||||||
|
|
||||||
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
||||||
|
|
||||||
from app.routes import auth, dashboard, inspections, templates, reports, facilities
|
from app.routes import auth, dashboard, inspections, templates, reports, facilities
|
||||||
from app.routes import issues # Phase 3
|
from app.routes import issues # Phase 3
|
||||||
|
from app.routes import notifications # Notification system
|
||||||
|
|
||||||
app.register_blueprint(auth.bp)
|
app.register_blueprint(auth.bp)
|
||||||
app.register_blueprint(dashboard.bp)
|
app.register_blueprint(dashboard.bp)
|
||||||
@@ -43,6 +62,7 @@ def create_app(config_name='default'):
|
|||||||
app.register_blueprint(reports.bp)
|
app.register_blueprint(reports.bp)
|
||||||
app.register_blueprint(facilities.bp)
|
app.register_blueprint(facilities.bp)
|
||||||
app.register_blueprint(issues.bp)
|
app.register_blueprint(issues.bp)
|
||||||
|
app.register_blueprint(notifications.bp)
|
||||||
|
|
||||||
# ── Error handler: 413 Request Entity Too Large ───────────────────────
|
# ── Error handler: 413 Request Entity Too Large ───────────────────────
|
||||||
# Nginx can return 413 before Flask sees the request; this handler covers
|
# Nginx can return 413 before Flask sees the request; this handler covers
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ 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
|
||||||
|
|
||||||
bp = Blueprint('inspections', __name__, url_prefix='/inspections')
|
bp = Blueprint('inspections', __name__, url_prefix='/inspections')
|
||||||
|
|
||||||
@@ -308,6 +309,29 @@ def execute(inspection_id):
|
|||||||
_save_responses(inspection, responses)
|
_save_responses(inspection, responses)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
# ── Notify supervisors/admins that an inspection was completed ──
|
||||||
|
supervisors = User.query.filter(
|
||||||
|
User.role.in_(['admin', 'supervisor'])
|
||||||
|
).all()
|
||||||
|
inspection_link = url_for('inspections.view', inspection_id=inspection.id)
|
||||||
|
score_display = f'{score:.1f}%' if score is not None else 'N/A'
|
||||||
|
for supervisor in supervisors:
|
||||||
|
if supervisor.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = supervisor,
|
||||||
|
title = f'Inspection #{inspection.id} Completed',
|
||||||
|
body = (
|
||||||
|
f'{current_user.username} completed an inspection at '
|
||||||
|
f'{inspection.facility.name} using the '
|
||||||
|
f'"{inspection.template.name}" template. '
|
||||||
|
f'Overall score: {score_display}.'
|
||||||
|
),
|
||||||
|
link = inspection_link,
|
||||||
|
inspection_id = inspection.id,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
db.session.commit() # Commit notifications
|
||||||
|
|
||||||
flash('Inspection submitted successfully!', 'success')
|
flash('Inspection submitted successfully!', 'success')
|
||||||
return redirect(url_for('inspections.view', inspection_id=inspection_id))
|
return redirect(url_for('inspections.view', inspection_id=inspection_id))
|
||||||
|
|
||||||
@@ -411,6 +435,31 @@ def flag_issue(inspection_id):
|
|||||||
inspection.status = 'flagged'
|
inspection.status = 'flagged'
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
current_app.logger.info(
|
||||||
|
'ISSUE FLAGGED | issue_id=%s | inspection_id=%s | severity=%s | assigned_to=%s | by=%s',
|
||||||
|
issue.id, inspection_id, issue.severity, issue.assigned_to, current_user.username
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Notify the assignee of the flagged issue ─────────────────────
|
||||||
|
if issue.assigned_to:
|
||||||
|
assignee = User.query.get(issue.assigned_to)
|
||||||
|
if assignee and assignee.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = assignee,
|
||||||
|
title = f'New Issue #{issue.id} Assigned to You',
|
||||||
|
body = (
|
||||||
|
f'A {issue.severity.title()}-severity issue was flagged during '
|
||||||
|
f'inspection #{inspection_id} at {inspection.facility.name} '
|
||||||
|
f'and assigned to you. '
|
||||||
|
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,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
db.session.commit() # Commit notification
|
||||||
|
|
||||||
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))
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from app.models.facility import Facility, Area
|
|||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
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
|
||||||
|
|
||||||
bp = Blueprint('issues', __name__, url_prefix='/issues')
|
bp = Blueprint('issues', __name__, url_prefix='/issues')
|
||||||
|
|
||||||
@@ -59,6 +60,9 @@ def view(issue_id):
|
|||||||
form.status.data = form.status.data or issue.status
|
form.status.data = form.status.data or issue.status
|
||||||
|
|
||||||
if form.validate_on_submit():
|
if form.validate_on_submit():
|
||||||
|
old_status = issue.status
|
||||||
|
old_assigned_to = issue.assigned_to
|
||||||
|
|
||||||
issue.status = form.status.data
|
issue.status = form.status.data
|
||||||
|
|
||||||
# Only admin/supervisor can reassign; inspectors can only update status
|
# Only admin/supervisor can reassign; inspectors can only update status
|
||||||
@@ -100,6 +104,79 @@ def view(issue_id):
|
|||||||
'ISSUE UPDATED | id=%s | status=%s | result_photos_added=%s | comment=%s | updated_by=%s',
|
'ISSUE UPDATED | id=%s | status=%s | result_photos_added=%s | comment=%s | updated_by=%s',
|
||||||
issue.id, issue.status, len(new_photos), bool(comment_body), current_user.username
|
issue.id, issue.status, len(new_photos), bool(comment_body), current_user.username
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ── Notifications ────────────────────────────────────────────────
|
||||||
|
issue_link = url_for('issues.view', issue_id=issue.id)
|
||||||
|
new_assigned_to = issue.assigned_to
|
||||||
|
|
||||||
|
# 1. Notify the assignee when status changes
|
||||||
|
if old_status != issue.status and new_assigned_to:
|
||||||
|
assignee = User.query.get(new_assigned_to)
|
||||||
|
if assignee and assignee.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = assignee,
|
||||||
|
title = f'Issue #{issue.id} Status Updated',
|
||||||
|
body = (
|
||||||
|
f'Issue in {issue.area.name} was updated from '
|
||||||
|
f'"{old_status.replace("_", " ").title()}" to '
|
||||||
|
f'"{issue.status.replace("_", " ").title()}" '
|
||||||
|
f'by {current_user.username}.'
|
||||||
|
),
|
||||||
|
link = issue_link,
|
||||||
|
issue_id = issue.id,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Notify newly assigned user when the assignee changes
|
||||||
|
if (old_assigned_to != new_assigned_to) and new_assigned_to:
|
||||||
|
new_assignee = User.query.get(new_assigned_to)
|
||||||
|
if new_assignee and new_assignee.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = new_assignee,
|
||||||
|
title = f'Issue #{issue.id} Assigned to You',
|
||||||
|
body = (
|
||||||
|
f'You have been assigned Issue #{issue.id} '
|
||||||
|
f'({issue.severity.title()} severity) in {issue.area.name}. '
|
||||||
|
f'Current status: {issue.status.replace("_", " ").title()}.'
|
||||||
|
),
|
||||||
|
link = issue_link,
|
||||||
|
issue_id = issue.id,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Notify the previously assigned user when unassigned
|
||||||
|
if old_assigned_to and old_assigned_to != new_assigned_to:
|
||||||
|
old_assignee = User.query.get(old_assigned_to)
|
||||||
|
if old_assignee and old_assignee.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = old_assignee,
|
||||||
|
title = f'Issue #{issue.id} Unassigned',
|
||||||
|
body = (
|
||||||
|
f'You have been removed from Issue #{issue.id} '
|
||||||
|
f'in {issue.area.name} by {current_user.username}.'
|
||||||
|
),
|
||||||
|
link = issue_link,
|
||||||
|
issue_id = issue.id,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Notify the assignee when a comment is added (if not the commenter)
|
||||||
|
if comment_body and new_assigned_to:
|
||||||
|
commentee = User.query.get(new_assigned_to)
|
||||||
|
if commentee and commentee.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = commentee,
|
||||||
|
title = f'New Comment on Issue #{issue.id}',
|
||||||
|
body = (
|
||||||
|
f'{current_user.username} added a comment on Issue #{issue.id}: '
|
||||||
|
f'"{comment_body[:120]}{"…" if len(comment_body) > 120 else ""}"'
|
||||||
|
),
|
||||||
|
link = issue_link,
|
||||||
|
issue_id = issue.id,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
|
||||||
|
db.session.commit() # Commit notifications
|
||||||
flash('Issue updated.', 'success')
|
flash('Issue updated.', 'success')
|
||||||
return redirect(url_for('issues.view', issue_id=issue_id))
|
return redirect(url_for('issues.view', issue_id=issue_id))
|
||||||
|
|
||||||
@@ -134,6 +211,30 @@ def create():
|
|||||||
)
|
)
|
||||||
db.session.add(issue)
|
db.session.add(issue)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
current_app.logger.info(
|
||||||
|
'ISSUE CREATED | id=%s | severity=%s | area_id=%s | assigned_to=%s | created_by=%s',
|
||||||
|
issue.id, issue.severity, issue.area_id, issue.assigned_to, current_user.username
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Notify the assignee of the new issue ────────────────────────
|
||||||
|
if issue.assigned_to:
|
||||||
|
assignee = User.query.get(issue.assigned_to)
|
||||||
|
if assignee and assignee.id != current_user.id:
|
||||||
|
notify(
|
||||||
|
recipient = assignee,
|
||||||
|
title = f'New Issue #{issue.id} Assigned to You',
|
||||||
|
body = (
|
||||||
|
f'A new {issue.severity.title()}-severity issue has been logged '
|
||||||
|
f'in {issue.area.name} and assigned to you. '
|
||||||
|
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,
|
||||||
|
send_email = True,
|
||||||
|
)
|
||||||
|
db.session.commit() # Commit notification
|
||||||
|
|
||||||
flash('Issue created.', 'success')
|
flash('Issue created.', 'success')
|
||||||
return redirect(url_for('issues.index'))
|
return redirect(url_for('issues.index'))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# app/routes/notifications.py
|
||||||
|
import logging
|
||||||
|
from flask import Blueprint, jsonify, request, abort
|
||||||
|
from flask_login import login_required, current_user
|
||||||
|
from app import db
|
||||||
|
from app.models.notification import Notification
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
bp = Blueprint('notifications', __name__, url_prefix='/notifications')
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/feed')
|
||||||
|
@login_required
|
||||||
|
def feed():
|
||||||
|
"""Return the 20 most recent notifications for the current user as JSON.
|
||||||
|
Used by the navbar bell icon to populate the dropdown.
|
||||||
|
"""
|
||||||
|
notifs = (
|
||||||
|
Notification.query
|
||||||
|
.filter_by(user_id=current_user.id)
|
||||||
|
.order_by(Notification.created_at.desc())
|
||||||
|
.limit(20)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
unread_count = Notification.query.filter_by(
|
||||||
|
user_id=current_user.id, is_read=False
|
||||||
|
).count()
|
||||||
|
|
||||||
|
items = []
|
||||||
|
for n in notifs:
|
||||||
|
items.append({
|
||||||
|
'id': n.id,
|
||||||
|
'title': n.title,
|
||||||
|
'body': n.body,
|
||||||
|
'link': n.link,
|
||||||
|
'is_read': n.is_read,
|
||||||
|
'created_at': n.created_at.strftime('%b %d, %Y %I:%M %p'),
|
||||||
|
})
|
||||||
|
|
||||||
|
return jsonify({'notifications': items, 'unread_count': unread_count})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/<int:notif_id>/mark-read', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
def mark_read(notif_id):
|
||||||
|
"""Mark a single notification as read."""
|
||||||
|
notif = Notification.query.get_or_404(notif_id)
|
||||||
|
if notif.user_id != current_user.id:
|
||||||
|
abort(403)
|
||||||
|
notif.is_read = True
|
||||||
|
db.session.commit()
|
||||||
|
logger.info(
|
||||||
|
'NOTIFICATION READ | id=%s | user=%s',
|
||||||
|
notif_id, current_user.username,
|
||||||
|
)
|
||||||
|
return jsonify({'ok': True})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/mark-all-read', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
def mark_all_read():
|
||||||
|
"""Mark all unread notifications for the current user as read."""
|
||||||
|
updated = (
|
||||||
|
Notification.query
|
||||||
|
.filter_by(user_id=current_user.id, is_read=False)
|
||||||
|
.update({'is_read': True})
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
logger.info(
|
||||||
|
'NOTIFICATIONS ALL READ | user=%s | count=%s',
|
||||||
|
current_user.username, updated,
|
||||||
|
)
|
||||||
|
return jsonify({'ok': True, 'marked': updated})
|
||||||
+217
-1
@@ -12,6 +12,61 @@
|
|||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/ipad_responsive.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='css/ipad_responsive.css') }}">
|
||||||
{% block extra_css %}{% endblock %}
|
{% block extra_css %}{% endblock %}
|
||||||
|
<style>
|
||||||
|
/* ── Notification bell styles ── */
|
||||||
|
.notif-bell-wrapper {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
.notif-badge {
|
||||||
|
position: absolute;
|
||||||
|
top: 2px;
|
||||||
|
right: 2px;
|
||||||
|
font-size: 0.6rem;
|
||||||
|
min-width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
line-height: 16px;
|
||||||
|
padding: 0 4px;
|
||||||
|
border-radius: 8px;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.notif-dropdown {
|
||||||
|
width: 360px;
|
||||||
|
max-height: 480px;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.notif-item {
|
||||||
|
border-left: 3px solid transparent;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.notif-item.unread {
|
||||||
|
border-left-color: #0d6efd;
|
||||||
|
background-color: #f0f6ff;
|
||||||
|
}
|
||||||
|
.notif-item:hover {
|
||||||
|
background-color: #e8f0fe;
|
||||||
|
}
|
||||||
|
.notif-title {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
.notif-body {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: #555;
|
||||||
|
white-space: normal;
|
||||||
|
}
|
||||||
|
.notif-time {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
color: #999;
|
||||||
|
}
|
||||||
|
.notif-empty {
|
||||||
|
padding: 24px;
|
||||||
|
text-align: center;
|
||||||
|
color: #aaa;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
{% if current_user.is_authenticated %}
|
{% if current_user.is_authenticated %}
|
||||||
@@ -49,7 +104,42 @@
|
|||||||
</li>
|
</li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</ul>
|
</ul>
|
||||||
<ul class="navbar-nav">
|
<ul class="navbar-nav align-items-center">
|
||||||
|
|
||||||
|
<!-- ── Notification Bell ── -->
|
||||||
|
<li class="nav-item dropdown me-2">
|
||||||
|
<a class="nav-link position-relative notif-bell-wrapper"
|
||||||
|
href="#"
|
||||||
|
id="notifDropdown"
|
||||||
|
role="button"
|
||||||
|
data-bs-toggle="dropdown"
|
||||||
|
aria-expanded="false"
|
||||||
|
title="Notifications">
|
||||||
|
<i class="bi bi-bell fs-5"></i>
|
||||||
|
{% if unread_notification_count > 0 %}
|
||||||
|
<span class="badge bg-danger notif-badge" id="notif-count-badge">
|
||||||
|
{{ unread_notification_count if unread_notification_count <= 99 else '99+' }}
|
||||||
|
</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="badge bg-danger notif-badge d-none" id="notif-count-badge"></span>
|
||||||
|
{% endif %}
|
||||||
|
</a>
|
||||||
|
<div class="dropdown-menu dropdown-menu-end notif-dropdown shadow" id="notif-dropdown-menu">
|
||||||
|
<div class="d-flex justify-content-between align-items-center px-3 py-2 border-bottom">
|
||||||
|
<span class="fw-semibold" style="font-size:0.9rem;">Notifications</span>
|
||||||
|
<button class="btn btn-link btn-sm p-0 text-muted text-decoration-none"
|
||||||
|
id="mark-all-read-btn"
|
||||||
|
style="font-size:0.75rem;">
|
||||||
|
Mark all as read
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div id="notif-list">
|
||||||
|
<div class="notif-empty">Loading…</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<!-- ── End Notification Bell ── -->
|
||||||
|
|
||||||
<li class="nav-item dropdown">
|
<li class="nav-item dropdown">
|
||||||
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
|
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
|
||||||
<i class="bi bi-person-circle"></i> {{ current_user.username }}
|
<i class="bi bi-person-circle"></i> {{ current_user.username }}
|
||||||
@@ -83,5 +173,131 @@
|
|||||||
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
{% block extra_js %}{% endblock %}
|
{% block extra_js %}{% endblock %}
|
||||||
|
|
||||||
|
{% if current_user.is_authenticated %}
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const FEED_URL = '{{ url_for("notifications.feed") }}';
|
||||||
|
const MARK_READ_BASE = '/notifications/';
|
||||||
|
const MARK_ALL_URL = '{{ url_for("notifications.mark_all_read") }}';
|
||||||
|
const CSRF_TOKEN = '{{ csrf_token() }}';
|
||||||
|
const POLL_INTERVAL = 60000; // 60 seconds
|
||||||
|
|
||||||
|
const badge = document.getElementById('notif-count-badge');
|
||||||
|
const listEl = document.getElementById('notif-list');
|
||||||
|
const markAllBtn = document.getElementById('mark-all-read-btn');
|
||||||
|
|
||||||
|
function updateBadge(count) {
|
||||||
|
if (count > 0) {
|
||||||
|
badge.textContent = count > 99 ? '99+' : count;
|
||||||
|
badge.classList.remove('d-none');
|
||||||
|
} else {
|
||||||
|
badge.textContent = '';
|
||||||
|
badge.classList.add('d-none');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderNotifications(notifications) {
|
||||||
|
if (!notifications.length) {
|
||||||
|
listEl.innerHTML = '<div class="notif-empty"><i class="bi bi-check2-circle me-1"></i>You\'re all caught up!</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
listEl.innerHTML = notifications.map(n => `
|
||||||
|
<a href="${n.link || '#'}"
|
||||||
|
class="d-block text-decoration-none text-dark notif-item px-3 py-2 border-bottom ${n.is_read ? '' : 'unread'}"
|
||||||
|
data-notif-id="${n.id}"
|
||||||
|
data-link="${n.link || ''}">
|
||||||
|
<div class="notif-title">${escapeHtml(n.title)}</div>
|
||||||
|
<div class="notif-body">${escapeHtml(n.body)}</div>
|
||||||
|
<div class="notif-time">${escapeHtml(n.created_at)}</div>
|
||||||
|
</a>
|
||||||
|
`).join('');
|
||||||
|
|
||||||
|
// Mark as read on click
|
||||||
|
listEl.querySelectorAll('.notif-item').forEach(el => {
|
||||||
|
el.addEventListener('click', function (e) {
|
||||||
|
const id = this.dataset.notifId;
|
||||||
|
const link = this.dataset.link;
|
||||||
|
e.preventDefault();
|
||||||
|
markRead(id, () => {
|
||||||
|
this.classList.remove('unread');
|
||||||
|
if (link) window.location.href = link;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(str) {
|
||||||
|
if (!str) return '';
|
||||||
|
return str.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchNotifications() {
|
||||||
|
fetch(FEED_URL, { credentials: 'same-origin' })
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
updateBadge(data.unread_count);
|
||||||
|
// Only re-render if dropdown is open to avoid disrupting user
|
||||||
|
const dropdownEl = document.getElementById('notifDropdown');
|
||||||
|
const isOpen = dropdownEl.getAttribute('aria-expanded') === 'true';
|
||||||
|
if (isOpen) renderNotifications(data.notifications);
|
||||||
|
// Store for rendering when opened
|
||||||
|
window._jqcNotifications = data.notifications;
|
||||||
|
})
|
||||||
|
.catch(() => {}); // Silently fail — non-critical
|
||||||
|
}
|
||||||
|
|
||||||
|
function markRead(id, callback) {
|
||||||
|
fetch(`${MARK_READ_BASE}${id}/mark-read`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-CSRFToken': CSRF_TOKEN, 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'same-origin',
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(() => { if (callback) callback(); fetchNotifications(); })
|
||||||
|
.catch(() => { if (callback) callback(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render stored notifications when dropdown opens
|
||||||
|
document.getElementById('notifDropdown').addEventListener('show.bs.dropdown', function () {
|
||||||
|
if (window._jqcNotifications) {
|
||||||
|
renderNotifications(window._jqcNotifications);
|
||||||
|
} else {
|
||||||
|
fetchNotifications();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mark all read button
|
||||||
|
markAllBtn.addEventListener('click', function (e) {
|
||||||
|
e.stopPropagation();
|
||||||
|
fetch(MARK_ALL_URL, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-CSRFToken': CSRF_TOKEN },
|
||||||
|
credentials: 'same-origin',
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(() => {
|
||||||
|
updateBadge(0);
|
||||||
|
// Mark all items visually as read
|
||||||
|
listEl.querySelectorAll('.notif-item.unread').forEach(el => el.classList.remove('unread'));
|
||||||
|
if (window._jqcNotifications) {
|
||||||
|
window._jqcNotifications.forEach(n => n.is_read = true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initial fetch + periodic polling
|
||||||
|
fetchNotifications();
|
||||||
|
setInterval(fetchNotifications, POLL_INTERVAL);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% endif %}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -44,11 +44,16 @@ class Config:
|
|||||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
SESSION_COOKIE_SAMESITE = 'Lax'
|
||||||
|
|
||||||
# ── Mail ────────────────────────────────────────────────────────────────
|
# ── Mail ────────────────────────────────────────────────────────────────
|
||||||
MAIL_SERVER = os.environ.get('MAIL_SERVER')
|
MAIL_SERVER = os.environ.get('MAIL_SERVER')
|
||||||
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 587)
|
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 587)
|
||||||
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS', 'true').lower() in ('true', 'on', '1')
|
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS', 'true').lower() in ('true', 'on', '1')
|
||||||
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
|
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
|
||||||
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
|
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
|
||||||
|
MAIL_DEFAULT_SENDER = os.environ.get('MAIL_DEFAULT_SENDER', 'noreply@janitorialqc.local')
|
||||||
|
|
||||||
|
# ── Application base URL (used in email "View Details" links) ───────────
|
||||||
|
# Set this to your production domain, e.g. https://qc.yourcompany.com
|
||||||
|
APP_BASE_URL = os.environ.get('APP_BASE_URL', '')
|
||||||
|
|
||||||
|
|
||||||
class DevelopmentConfig(Config):
|
class DevelopmentConfig(Config):
|
||||||
|
|||||||
Reference in New Issue
Block a user