Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
f3a5b2f
1
Parent(s): 1818cda
backend stabilization
Browse filesFiles changed (9)
1234567891011121314151617181920212223242526"""add_link_to_notifications
Revision ID: 909517d9e971Revises: 1536118577caCreate Date: 2026-04-08 10:10:55.034686
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '909517d9e971'down_revision: Union[str, None] = '1536118577ca'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.add_column('notifications', sa.Column('link', sa.String(length=512), nullable=True))
def downgrade() -> None: op.drop_column('notifications', 'link')6 unmodified lines78910111213144 unmodified lines15815916016016116216316416538 unmodified lines20420520620520720820921021125 unmodified lines2372382392402412422436 unmodified linesfrom fastapi import APIRouter, Dependsfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, func, or_, Float, descfrom sqlalchemy.orm import joinedload
from core.deps import get_db, get_current_user, get_arq_poolfrom core.llm import get_llm144 unmodified lines .options( joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver) joinedload(Ticket.resolver), joinedload(Ticket.feedback) ) .where( ((Ticket.created_by == current_user.id) | (Ticket.assigned_to == current_user.id)),38 unmodified lines .options( joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver) joinedload(Ticket.resolver), joinedload(Ticket.feedback) ) .where( Ticket.deleted_at.is_(None)25 unmodified lines from sqlalchemy import desc is_super_admin = (current_user.role == UserRole.SC_ADMIN) is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] is_global = (is_super_admin and workspace_id == "all") # 1. Global Tactical Mode (Super-Admin Only)134 unmodified lines13513613713813813914014112 unmodified lines154155156157157158159160161134 unmodified lines from arq.connections import RedisSettings settings = get_settings() redis = await create_pool(RedisSettings.from_dsn(settings.REDIS_URL)) await redis.enqueue_job("notify_mentions", str(current_user.workspace_id), ticket.title, mentions) await redis.enqueue_job("notify_mentions", str(current_user.workspace_id), ticket.title, mentions, ticket_id=str(ticket.id)) await redis.close() except Exception as e: print(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")12 unmodified lines str(ticket.created_by), str(ticket.workspace_id), "💬 Expert Response", f"An expert has replied to your ticket: '{ticket.title}'" f"An expert has replied to your ticket: '{ticket.title}'", link=f"/dashboard?ticket={ticket.id}" ) except Exception as e: logger.error(f"Failed to queue customer response notification: {e}")269 unmodified lines27027127227327327427527627741 unmodified lines31932032132132232332432516 unmodified lines34234334434434534634734818 unmodified lines367368369369370371372373382 unmodified lines7567577587587597607617627632 unmodified lines76676776876776977077177277348 unmodified lines822823824825826827828829830831832822823824833834835836837838839176 unmodified lines1016101710181007101910201021102210232 unmodified lines102610271028101610291030103110321033269 unmodified lines str(new_ticket.created_by), str(new_ticket.workspace_id), "🎟️ Ticket Created", f"We've received your request: '{new_ticket.title}'. Our team has been notified." f"We've received your request: '{new_ticket.title}'. Our team has been notified.", link=f"/dashboard?ticket={new_ticket.id}" ) logger.info(f"Ticket created: {new_ticket.id} by user {current_user.id} in workspace {current_user.workspace_id}")41 unmodified lines Ticket, (1 - Ticket.embedding.cosine_distance(query_vector)).label("sim_score") ) .options(joinedload(Ticket.creator), joinedload(Ticket.assignee)) .options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback)) .where( Ticket.deleted_at.is_(None), Ticket.embedding.isnot(None)16 unmodified lines func.plainto_tsquery('english', q) ).label("vis_score") ) .options(joinedload(Ticket.creator), joinedload(Ticket.assignee)) .options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback)) .join(Attachment, Ticket.id == Attachment.ticket_id) .where( Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q))18 unmodified lines func.plainto_tsquery('english', q) ).label("kw_score") ) .options(joinedload(Ticket.creator), joinedload(Ticket.assignee)) .options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback)) .where( Ticket.search_vector.op("@@")(func.plainto_tsquery('english', q)) )382 unmodified lines str(update_data["assigned_to"]), str(ticket.workspace_id), "Ticket Reassigned", f"Ticket '{ticket.title}' has been reassigned to you by {current_user.full_name or 'Admin'}." f"Ticket '{ticket.title}' has been reassigned to you by {current_user.full_name or 'Admin'}.", link=f"/dashboard?ticket={ticket.id}" ) # B) Notify Customer (Creator) if not self-assigning by customer if ticket.created_by != update_data["assigned_to"]:2 unmodified lines str(ticket.created_by), str(ticket.workspace_id), "👷 Expert Assigned", f"An expert has been assigned to your ticket '{ticket.title}' and is reviewing it now." f"An expert has been assigned to your ticket '{ticket.title}' and is reviewing it now.", link=f"/dashboard?ticket={ticket.id}" )
audit = AuditLog(48 unmodified lines if current_user.role not in [UserRole.SC_ADMIN, UserRole.SC_LEAD]: raise HTTPException(status_code=403, detail="Permission denied") stmt = ( select(Ticket) .options( joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver), joinedload(Ticket.feedback) ) stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.deleted_at.is_(None) .where( Ticket.id == ticket_id, Ticket.deleted_at.is_(None) ) ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)176 unmodified lines user_id=manager_user.id, workspace_id=ticket.workspace_id, title="🚨 Manual Escalation Alert", message=f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0." message=f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.", link=f"/dashboard?ticket={ticket.id}" ) # Notify Creator: We're on it!2 unmodified lines str(ticket.created_by), str(ticket.workspace_id), "⚡ Priority Boosted", f"Your ticket '{ticket.title}' has been prioritized for immediate leadership review." f"Your ticket '{ticket.title}' has been prioritized for immediate leadership review.", link=f"/dashboard?ticket={ticket.id}" )
logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")271 unmodified lines2722732742752752762772786 unmodified lines2852862872882882892902912924 unmodified lines2972982993003013023034 unmodified lines3083093103093113123133143153163173183191 unmodified line32132232332132432532632732847 unmodified lines376377378375379380381382383271 unmodified lines await db.rollback() logger.error(f"FAILURE: Unified KB indexing crashed for {article_id}: {str(e)}")
async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str):async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None): """Send notification to DB, real-time WebSocket, and simulated Email.""" async with async_session_factory() as db: # 1. Fetch User Email (Security Audit: Ensure we have a valid recipient)6 unmodified lines workspace_id=workspace_id, user_id=user_id, title=title, message=message message=message, link=link ) db.add(notification) await db.commit()4 unmodified lines "id": str(notification.id), "title": title, "message": message, "link": link, "created_at": datetime.utcnow().isoformat() }) 4 unmodified lines
logger.info(f"Triple notification sent to user {user_id} ({user_email})") async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list):async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None): """ Background task to notify multiple users about a mention. mentions: list of dicts [{"user_id": "...", "name": "..."}] """ link = f"/dashboard?ticket={ticket_id}" if ticket_id else None for mention in mentions: user_id = UUID(mention["user_id"]) if isinstance(mention["user_id"], str) else mention["user_id"] await send_triple_notification(1 unmodified line user_id=user_id, workspace_id=workspace_id, title=title, message=f"You were mentioned in a ticket message: {title}" message=f"You were mentioned in a ticket message: {title}", link=link ) logger.info(f"Mention notifications sent to {len(mentions)} users")
47 unmodified lines manager_user.id, ticket.workspace_id, "🚨 SLA Escalation Alert", f"Ticket '{ticket.title}' of priority {str(ticket.priority)} has exceeded its SLA threshold. This is an official system escalation." f"Ticket '{ticket.title}' of priority {str(ticket.priority)} has exceeded its SLA threshold. This is an official system escalation.", link=f"/dashboard?ticket={ticket.id}" ) # MARK AS ESCALATED to avoid duplicates ticket.is_escalated = now77 unmodified lines78798081828384858687888990919293949596979899100101102103104105106107108109110111112152 unmodified lines26526626726826927023924024124224327127227327427527627727827928077 unmodified lines } };
const handleNotifClick = async (n: any) => { setIsNotifOpen(false); if (!n.link) return;
// Parse deep links (e.g., /dashboard?ticket=UUID) const url = new URL(n.link, window.location.origin); const ticketId = url.searchParams.get('ticket'); if (ticketId) { try { const res = await api.get(`tickets/${ticketId}/`); onSelectTicket?.(res.data); } catch (err) { console.error("Failed to fetch ticket from notification link:", err); } } };
// Handle Deep Linking on Load useEffect(() => { const params = new URLSearchParams(window.location.search); const ticketId = params.get('ticket'); if (ticketId) { api.get(`tickets/${ticketId}/`) .then(res => onSelectTicket?.(res.data)) .catch(err => console.error("URL-based ticket load failed:", err)); } }, []);
const handleSearch = async () => { setIsSearching(true); setShowSearchDropdown(true);152 unmodified lines <div style={{ padding: 40, textAlign: "center", color: COLORS.gray400, fontSize: 13 }}>No recent activity.</div> ) : ( notifications.map(n => ( <div key={n.id} onClick={() => handleNotifClick(n)} <div key={n.id} style={{ padding: "12px 16px", borderRadius: 10, marginBottom: 4, background: n.is_read ? "transparent" : "#EFF6FF", borderLeft: n.is_read ? "3px solid transparent" : `3px solid ${COLORS.brand}` }}> style={{ padding: "12px 16px", borderRadius: 10, marginBottom: 4, background: n.is_read ? "transparent" : "#EFF6FF", borderLeft: n.is_read ? "3px solid transparent" : `3px solid ${COLORS.brand}`, cursor: n.link ? "pointer" : "default" }} > <div style={{ fontSize: 13, fontWeight: 700, color: COLORS.gray800, marginBottom: 2 }}>{n.title}</div> <div style={{ fontSize: 12, color: COLORS.gray600, lineHeight: 1.4, marginBottom: 6 }}>{n.message}</div> <div style={{ fontSize: 10, color: COLORS.gray400 }}>{new Date(n.created_at).toLocaleString()}</div>88 unmodified lines899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212371 unmodified lines19519619716919819920020120220320420520620788 unmodified lines } };
const handleNotifClick = async (n: any) => { setShowNotifications(false); if (!n.link) return;
// Parse deep links (e.g., /dashboard?ticket=UUID) try { const url = new URL(n.link, window.location.origin); const ticketId = url.searchParams.get('ticket'); if (ticketId) { const res = await api.get(`tickets/${ticketId}/`); onTicketSelect?.(res.data); } } catch (err) { console.error("Failed to parse or fetch notification link:", err); } };
// Handle Deep Linking on Load useEffect(() => { const params = new URLSearchParams(window.location.search); const ticketId = params.get('ticket'); if (ticketId) { api.get(`tickets/${ticketId}/`) .then(res => onTicketSelect?.(res.data)) .catch(err => console.error("URL-based ticket load failed:", err)); } }, []);
// We only search on Enter now, so we remove the useEffect watcher
return (71 unmodified lines <div className={styles.notifEmpty}>No new system alerts</div> ) : ( notifications.map(n => ( <div key={n.id} className={styles.notifItem} data-read={n.is_read}> <div key={n.id} className={styles.notifItem} data-read={n.is_read} onClick={() => handleNotifClick(n)} style={{ cursor: n.link ? 'pointer' : 'default' }} > <div className={styles.notifTitle}>{n.title}</div> <div className={styles.notifMsg}>{n.message}</div> <div className={styles.notifTime}>{new Date(n.created_at).toLocaleString()}</div>55 unmodified lines56575859596061626364656667686963 unmodified lines13313413513113213313655 unmodified lines lifespan=lifespan, docs_url="/docs", redoc_url="/redoc", strict_slashes=False, strict_slashes=True,)
@app.get("/health", tags=["System"])@app.get("/health/", tags=["System"])def health_check(): return {"status": "ok"}
# --- OPENTELEMETRY TRACING ---setup_telemetry(app)
63 unmodified linesapp.include_router(system.router, prefix=f"{settings.API_V1_STR}/system", tags=["System Diagnostics"])app.include_router(websockets.router, tags=["websockets"])
@app.get("/health/", tags=["System"])def health_check(): return {"status": "ok"}
17 unmodified lines1819202122232417 unmodified lines title = Column(String(255), nullable=False) message = Column(Text, nullable=False) is_read = Column(Boolean, default=False) link = Column(String(512), nullable=True) # Optional URL/Route to navigate to created_at = Column( DateTime(timezone=False), default=datetime.utcnow,alembic/versions/909517d9e971_add_link_to_notifications.pyAdded+26
api/v1/dashboard.py+6-2
api/v1/messages.py+3-2
api/v1/tickets.py+25-11
core/tasks.py+10-5
frontend/apps/customer/src/components/TopBar.tsx+39-5
frontend/apps/internal/src/components/TopBar.tsx+36-1
main.py+7-4
models/notification.py+1