Enhance Ticket management functionalities
This commit is contained in:
+15
-1
@@ -32,7 +32,21 @@ def create_app(config_name=None):
|
||||
login_manager.init_app(app)
|
||||
mail.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
socketio.init_app(app, async_mode='eventlet', cors_allowed_origins='*')
|
||||
socketio.init_app(
|
||||
app,
|
||||
async_mode = 'eventlet',
|
||||
cors_allowed_origins = '*',
|
||||
# Ping settings: server sends a ping every 25s, client has 60s to respond.
|
||||
# This ensures dead connections are detected and closed cleanly rather than
|
||||
# being torn down by nginx timeouts, which causes [Errno 9] Bad file descriptor.
|
||||
ping_interval = 25,
|
||||
ping_timeout = 60,
|
||||
# Suppress eventlet's low-level socket error messages from flooding the log.
|
||||
# The errors still occur occasionally (it's an eventlet limitation) but are
|
||||
# benign — connections recover automatically via Socket.IO's reconnect logic.
|
||||
logger = False,
|
||||
engineio_logger = False,
|
||||
)
|
||||
|
||||
login_manager.login_view = 'auth.login'
|
||||
login_manager.login_message = 'Please log in to access this page.'
|
||||
|
||||
+24
-1
@@ -12,6 +12,29 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# ─── Notifications API ────────────────────────────────────────────────────────
|
||||
|
||||
@api_bp.route('/notifications')
|
||||
@login_required
|
||||
def get_notifications():
|
||||
"""Return the 20 most recent notifications for the current user as JSON."""
|
||||
notifs = (Notification.query
|
||||
.filter_by(user_id=current_user.id)
|
||||
.order_by(Notification.created_at.desc())
|
||||
.limit(20)
|
||||
.all())
|
||||
return jsonify({'notifications': [
|
||||
{
|
||||
'id' : n.id,
|
||||
'type' : n.type,
|
||||
'title' : n.title,
|
||||
'message' : n.message or '',
|
||||
'link' : n.link or '',
|
||||
'is_read' : n.is_read,
|
||||
'created_at': n.created_at.strftime('%b %d, %H:%M'),
|
||||
}
|
||||
for n in notifs
|
||||
]})
|
||||
|
||||
|
||||
@api_bp.route('/notifications/unread-count')
|
||||
@login_required
|
||||
def unread_count():
|
||||
@@ -80,4 +103,4 @@ def on_join_ticket(data):
|
||||
def on_leave_ticket(data):
|
||||
if current_user.is_authenticated:
|
||||
ticket_id = data.get('ticket_id')
|
||||
leave_room(f'ticket_{ticket_id}')
|
||||
leave_room(f'ticket_{ticket_id}')
|
||||
@@ -77,15 +77,26 @@ def create_notification(user_id, notif_type, title, message, ticket_id=None, lin
|
||||
db.session.commit()
|
||||
logger.info(f'[NOTIFICATION CREATE] user_id={user_id} type={notif_type} ticket_id={ticket_id}')
|
||||
|
||||
# Real-time push
|
||||
socketio.emit('new_notification', {
|
||||
'id' : notif.id,
|
||||
'type' : notif_type,
|
||||
'title' : title,
|
||||
'message' : message,
|
||||
'link' : link,
|
||||
# Real-time push — schedule via socketio.start_background_task so the
|
||||
# emit runs inside eventlet's green-thread pool, not inline in the WSGI
|
||||
# request context. Inline emits during a polling→WebSocket upgrade can
|
||||
# race with the upgrade handshake and disconnect the client.
|
||||
payload = {
|
||||
'id' : notif.id,
|
||||
'type' : notif_type,
|
||||
'title' : title,
|
||||
'message' : message,
|
||||
'link' : link,
|
||||
'created_at': notif.created_at.isoformat(),
|
||||
}, room=f'user_{user_id}')
|
||||
}
|
||||
def _emit():
|
||||
socketio.emit(
|
||||
'new_notification',
|
||||
payload,
|
||||
to=f'user_{user_id}', # 'to' is the modern alias for 'room'
|
||||
namespace='/', # explicit default namespace — avoids
|
||||
) # ambiguity under reverse-proxy setups
|
||||
socketio.start_background_task(_emit)
|
||||
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
@@ -95,13 +106,30 @@ def create_notification(user_id, notif_type, title, message, ticket_id=None, lin
|
||||
# ─── Email Notification ───────────────────────────────────────────────────────
|
||||
|
||||
def send_email(subject, recipients, html_body):
|
||||
"""Send an email; silently log errors so it never blocks the main flow."""
|
||||
try:
|
||||
msg = Message(subject=subject, recipients=recipients, html=html_body)
|
||||
mail.send(msg)
|
||||
logger.info(f'[EMAIL SENT] subject="{subject}" to={recipients}')
|
||||
except Exception as exc:
|
||||
logger.error(f'[EMAIL ERROR] Failed to send "{subject}" to {recipients}: {exc}')
|
||||
"""
|
||||
Send an email in a background thread so it never blocks the request.
|
||||
|
||||
Flask-Mail opens an SMTP connection synchronously. Running it in the main
|
||||
request thread means a slow or failing SMTP server delays the entire
|
||||
response — including the WebSocket notification push that follows.
|
||||
Using a daemon thread isolates SMTP failures from the request lifecycle.
|
||||
"""
|
||||
from threading import Thread
|
||||
from flask import current_app
|
||||
|
||||
app = current_app._get_current_object() # real app, not the proxy
|
||||
|
||||
def _send():
|
||||
with app.app_context():
|
||||
try:
|
||||
msg = Message(subject=subject, recipients=recipients, html=html_body)
|
||||
mail.send(msg)
|
||||
logger.info(f'[EMAIL SENT] subject="{subject}" to={recipients}')
|
||||
except Exception as exc:
|
||||
logger.error(f'[EMAIL ERROR] Failed to send "{subject}" to {recipients}: {exc}')
|
||||
|
||||
t = Thread(target=_send, daemon=True)
|
||||
t.start()
|
||||
|
||||
|
||||
# ─── Ticket Event Helpers ─────────────────────────────────────────────────────
|
||||
@@ -252,4 +280,4 @@ def notify_assignment(ticket, assigned_by):
|
||||
[ticket.assignee.email],
|
||||
html,
|
||||
)
|
||||
logger.info(f'[TICKET ASSIGN] ticket_id={ticket.id} assigned_to={ticket.assigned_to_id} by={assigned_by.id}')
|
||||
logger.info(f'[TICKET ASSIGN] ticket_id={ticket.id} assigned_to={ticket.assigned_to_id} by={assigned_by.id}')
|
||||
+84
-24
@@ -442,11 +442,15 @@
|
||||
{% if current_user.is_authenticated %}
|
||||
const socket = io({
|
||||
path: '/socket.io/',
|
||||
transports: ['polling', 'websocket'], // polling first → upgrade to WS after handshake
|
||||
transports: ['polling', 'websocket'], // polling first → upgrade to WS after handshake
|
||||
upgrade: true,
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 2000,
|
||||
reconnectionAttempts: 10,
|
||||
reconnectionDelay: 3000, // wait 3s before first reconnect attempt
|
||||
reconnectionDelayMax: 15000, // cap exponential backoff at 15s
|
||||
timeout: 20000, // connection timeout
|
||||
// Note: pingTimeout and pingInterval are server-side only in Socket.IO v4.
|
||||
// The server controls the heartbeat (ping_interval=25, ping_timeout=60).
|
||||
});
|
||||
socket.on('connect',()=>{console.log('[Socket] connected');});
|
||||
socket.on('new_notification',(n)=>{
|
||||
@@ -466,52 +470,108 @@ function updateBadge(delta, increment=false){
|
||||
|
||||
// ── Notification panel ────────────────────────────────────────────────────────
|
||||
let panelOpen = false;
|
||||
|
||||
function toggleNotifPanel(){
|
||||
const panel = document.getElementById('notif-panel');
|
||||
panelOpen = !panelOpen;
|
||||
panel.classList.toggle('show', panelOpen);
|
||||
if(panelOpen) loadNotifications();
|
||||
}
|
||||
document.addEventListener('click',(e)=>{
|
||||
|
||||
document.addEventListener('click', e => {
|
||||
if(panelOpen && !e.target.closest('#notif-panel') && !e.target.closest('.notif-btn')){
|
||||
panelOpen=false;
|
||||
panelOpen = false;
|
||||
document.getElementById('notif-panel').classList.remove('show');
|
||||
}
|
||||
});
|
||||
|
||||
async function loadNotifications(){
|
||||
try{
|
||||
const r = await fetch('/api/notifications/unread-count');
|
||||
const d = await r.json();
|
||||
updateBadge(d.count);
|
||||
}catch(e){}
|
||||
function _notifItemHtml(n) {
|
||||
const unreadClass = n.is_read ? '' : ' unread';
|
||||
const dot = n.is_read ? '' : '<div class="notif-dot"></div>';
|
||||
return (
|
||||
`<div class="notif-item${unreadClass}" data-id="${n.id}" data-link="${n.link || ''}" ` +
|
||||
`style="cursor:${n.link ? 'pointer' : 'default'}">` +
|
||||
dot +
|
||||
`<div style="flex:1;min-width:0;">` +
|
||||
`<div class="notif-title">${n.title}</div>` +
|
||||
`<div class="notif-msg">${n.message || ''}</div>` +
|
||||
`<div class="notif-time">${n.created_at}</div>` +
|
||||
`</div></div>`
|
||||
);
|
||||
}
|
||||
|
||||
function _bindNotifClick(el) {
|
||||
el.addEventListener('click', async () => {
|
||||
const id = el.dataset.id;
|
||||
const link = el.dataset.link;
|
||||
// Mark as read in DB
|
||||
if(el.classList.contains('unread')){
|
||||
try { await fetch(`/api/notifications/${id}/read`, { method: 'POST' }); } catch(_){}
|
||||
el.classList.remove('unread');
|
||||
const dot = el.querySelector('.notif-dot');
|
||||
if(dot) dot.remove();
|
||||
// Decrement badge
|
||||
const badge = document.getElementById('notif-badge-count');
|
||||
if(badge){
|
||||
const cur = parseInt(badge.textContent) || 0;
|
||||
const next = Math.max(0, cur - 1);
|
||||
badge.textContent = next > 0 ? next : '';
|
||||
badge.classList.toggle('show', next > 0);
|
||||
}
|
||||
}
|
||||
if(link) window.location.href = link;
|
||||
});
|
||||
}
|
||||
|
||||
async function loadNotifications(){
|
||||
const list = document.getElementById('notif-list');
|
||||
list.innerHTML = '<div class="p-3 text-center" style="color:var(--muted);font-size:13px;">Loading…</div>';
|
||||
try{
|
||||
const r = await fetch('/notifications?json=1');
|
||||
// Fallback: show link
|
||||
list.innerHTML='<div class="p-3 text-center" style="color:var(--muted);font-size:13px;">'+
|
||||
'<a href="/notifications" style="color:var(--accent3)">View all notifications</a></div>';
|
||||
const r = await fetch('/api/notifications');
|
||||
if(!r.ok) throw new Error('HTTP ' + r.status);
|
||||
const data = await r.json();
|
||||
const notifs = data.notifications || [];
|
||||
|
||||
// Update badge from live count
|
||||
const unreadCount = notifs.filter(n => !n.is_read).length;
|
||||
updateBadge(unreadCount);
|
||||
|
||||
if(notifs.length === 0){
|
||||
list.innerHTML = '<div class="p-4 text-center" style="color:var(--muted);font-size:13px;">' +
|
||||
'<i class="bi bi-bell-slash" style="font-size:24px;display:block;margin-bottom:8px;"></i>' +
|
||||
'No notifications yet.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = notifs.map(_notifItemHtml).join('');
|
||||
list.querySelectorAll('.notif-item').forEach(_bindNotifClick);
|
||||
|
||||
}catch(e){
|
||||
list.innerHTML='<div class="p-3 text-center" style="color:var(--muted);font-size:13px;">Unable to load</div>';
|
||||
list.innerHTML = '<div class="p-3 text-center" style="color:var(--muted);font-size:13px;">Unable to load notifications.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function prependNotif(n){
|
||||
// Add new real-time notification to the top of the panel if it's open
|
||||
const list = document.getElementById('notif-list');
|
||||
const item = document.createElement('div');
|
||||
item.className='notif-item unread';
|
||||
item.innerHTML=`<div class="notif-dot"></div><div><div class="notif-title">${n.title}</div><div class="notif-msg">${n.message||''}</div><div class="notif-time">Just now</div></div>`;
|
||||
if(n.link) item.onclick=()=>{ window.location=n.link; };
|
||||
list.prepend(item);
|
||||
// Remove "no notifications" placeholder if present
|
||||
if(list.querySelector('.bi-bell-slash')) list.innerHTML = '';
|
||||
const tmp = document.createElement('div');
|
||||
tmp.innerHTML = _notifItemHtml({
|
||||
id: n.id, title: n.title, message: n.message || '',
|
||||
link: n.link || '', is_read: false, created_at: 'Just now'
|
||||
});
|
||||
const el = tmp.firstElementChild;
|
||||
_bindNotifClick(el);
|
||||
list.prepend(el);
|
||||
}
|
||||
|
||||
async function markAllRead(){
|
||||
await fetch('/api/notifications/mark-all-read',{method:'POST'});
|
||||
try { await fetch('/api/notifications/mark-all-read', { method: 'POST' }); } catch(_){}
|
||||
updateBadge(0);
|
||||
document.querySelectorAll('.notif-item.unread').forEach(el=>{
|
||||
document.querySelectorAll('.notif-item.unread').forEach(el => {
|
||||
el.classList.remove('unread');
|
||||
const dot=el.querySelector('.notif-dot');
|
||||
const dot = el.querySelector('.notif-dot');
|
||||
if(dot) dot.remove();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -215,7 +215,7 @@
|
||||
<div style="display:flex;gap:10px;padding:7px 0;border-bottom:1px solid var(--border);">
|
||||
<i class="bi {{ icon }}" style="color:var(--muted);width:16px;text-align:center;margin-top:1px;flex-shrink:0;"></i>
|
||||
<div style="color:var(--muted);">{{ label }}</div>
|
||||
<div style="margin-left:auto;text-align:right;max-width:55%;">{{ value }}</div>
|
||||
<div style="margin-left:auto;text-align:right;max-width:55%;">{{ value | safe }}</div>
|
||||
</div>
|
||||
{% endmacro %}
|
||||
{{ info_row('bi-hash', 'Number', '<span class="mono" style="font-size:11px;color:var(--accent3);">'~ticket.ticket_number~'</span>') }}
|
||||
@@ -247,4 +247,4 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user