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 lines789101112144 unmodified lines15715815916016116216338 unmodified lines20220320420520620720825 unmodified lines2342352362372382396 unmodified linesfrom fastapi import APIRouter, Dependsfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, func, or_, Float, descfrom 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)).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)).where(Ticket.deleted_at.is_(None)25 unmodified linesfrom sqlalchemy import descis_super_admin = (current_user.role == UserRole.SC_ADMIN)is_global = (is_super_admin and workspace_id == "all")# 1. Global Tactical Mode (Super-Admin Only)6 unmodified lines78910111213144 unmodified lines15815916016116216316416538 unmodified lines20420520620720820921021125 unmodified lines2372382392402412422436 unmodified linesfrom fastapi import APIRouter, Dependsfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, func, or_, Float, descfrom sqlalchemy.orm import joinedloadfrom 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.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.feedback)).where(Ticket.deleted_at.is_(None)25 unmodified linesfrom sqlalchemy import descis_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 lines13513613713813914014112 unmodified lines154155156157158159160134 unmodified linesfrom arq.connections import RedisSettingssettings = 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.close()except Exception as e:print(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")12 unmodified linesstr(ticket.created_by),str(ticket.workspace_id),"💬 Expert Response",f"An expert has replied to your ticket: '{ticket.title}'")except Exception as e:logger.error(f"Failed to queue customer response notification: {e}")134 unmodified lines13513613713813914014112 unmodified lines154155156157158159160161134 unmodified linesfrom arq.connections import RedisSettingssettings = 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, ticket_id=str(ticket.id))await redis.close()except Exception as e:print(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")12 unmodified linesstr(ticket.created_by),str(ticket.workspace_id),"💬 Expert Response",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 lines27027127227327427527641 unmodified lines31831932032132232332416 unmodified lines34134234334434534634718 unmodified lines366367368369370371372382 unmodified lines7557567577587597607612 unmodified lines76476576676776876977048 unmodified lines819820821822823824825826827176 unmodified lines10041005100610071008100910102 unmodified lines1013101410151016101710181019269 unmodified linesstr(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.")logger.info(f"Ticket created: {new_ticket.id} by user {current_user.id} in workspace {current_user.workspace_id}")41 unmodified linesTicket,(1 - Ticket.embedding.cosine_distance(query_vector)).label("sim_score")).options(joinedload(Ticket.creator), joinedload(Ticket.assignee)).where(Ticket.deleted_at.is_(None),Ticket.embedding.isnot(None)16 unmodified linesfunc.plainto_tsquery('english', q)).label("vis_score")).options(joinedload(Ticket.creator), joinedload(Ticket.assignee)).join(Attachment, Ticket.id == Attachment.ticket_id).where(Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q))18 unmodified linesfunc.plainto_tsquery('english', q)).label("kw_score")).options(joinedload(Ticket.creator), joinedload(Ticket.assignee)).where(Ticket.search_vector.op("@@")(func.plainto_tsquery('english', q)))382 unmodified linesstr(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'}.")# B) Notify Customer (Creator) if not self-assigning by customerif ticket.created_by != update_data["assigned_to"]:2 unmodified linesstr(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.")audit = AuditLog(48 unmodified linesif current_user.role not in [UserRole.SC_ADMIN, UserRole.SC_LEAD]:raise HTTPException(status_code=403, detail="Permission denied")stmt = select(Ticket).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 linesuser_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.")# Notify Creator: We're on it!2 unmodified linesstr(ticket.created_by),str(ticket.workspace_id),"⚡ Priority Boosted",f"Your ticket '{ticket.title}' has been prioritized for immediate leadership review.")logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")269 unmodified lines27027127227327427527627741 unmodified lines31932032132232332432516 unmodified lines34234334434534634734818 unmodified lines367368369370371372373382 unmodified lines7567577587597607617627632 unmodified lines76676776876977077177277348 unmodified lines822823824825826827828829830831832833834835836837838839176 unmodified lines101610171018101910201021102210232 unmodified lines10261027102810291030103110321033269 unmodified linesstr(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.",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 linesTicket,(1 - Ticket.embedding.cosine_distance(query_vector)).label("sim_score")).options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback)).where(Ticket.deleted_at.is_(None),Ticket.embedding.isnot(None)16 unmodified linesfunc.plainto_tsquery('english', q)).label("vis_score")).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 linesfunc.plainto_tsquery('english', q)).label("kw_score")).options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback)).where(Ticket.search_vector.op("@@")(func.plainto_tsquery('english', q)))382 unmodified linesstr(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'}.",link=f"/dashboard?ticket={ticket.id}")# B) Notify Customer (Creator) if not self-assigning by customerif ticket.created_by != update_data["assigned_to"]:2 unmodified linesstr(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.",link=f"/dashboard?ticket={ticket.id}")audit = AuditLog(48 unmodified linesif 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)).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 linesuser_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.",link=f"/dashboard?ticket={ticket.id}")# Notify Creator: We're on it!2 unmodified linesstr(ticket.created_by),str(ticket.workspace_id),"⚡ Priority Boosted",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 lines2722732742752762772786 unmodified lines2852862872882892902914 unmodified lines2962972982993003014 unmodified lines3063073083093103113123133143153161 unmodified line31831932032132232332447 unmodified lines372373374375376377378271 unmodified linesawait 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):"""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 linesworkspace_id=workspace_id,user_id=user_id,title=title,message=message)db.add(notification)await db.commit()4 unmodified lines"id": str(notification.id),"title": title,"message": message,"created_at": datetime.utcnow().isoformat()})4 unmodified lineslogger.info(f"Triple notification sent to user {user_id} ({user_email})")async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list):"""Background task to notify multiple users about a mention.mentions: list of dicts [{"user_id": "...", "name": "..."}]"""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 lineuser_id=user_id,workspace_id=workspace_id,title=title,message=f"You were mentioned in a ticket message: {title}")logger.info(f"Mention notifications sent to {len(mentions)} users")47 unmodified linesmanager_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.")# MARK AS ESCALATED to avoid duplicatesticket.is_escalated = now271 unmodified lines2722732742752762772786 unmodified lines2852862872882892902912924 unmodified lines2972982993003013023034 unmodified lines3083093103113123133143153163173183191 unmodified line32132232332432532632732847 unmodified lines376377378379380381382383271 unmodified linesawait 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, 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 linesworkspace_id=workspace_id,user_id=user_id,title=title,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 lineslogger.info(f"Triple notification sent to user {user_id} ({user_email})")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 Nonefor 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 lineuser_id=user_id,workspace_id=workspace_id,title=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 linesmanager_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.",link=f"/dashboard?ticket={ticket.id}")# MARK AS ESCALATED to avoid duplicatesticket.is_escalated = now
77 unmodified lines787980818283152 unmodified lines23623723823924024124224324424524677 unmodified lines}};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} 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}`}}><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>77 unmodified lines78798081828384858687888990919293949596979899100101102103104105106107108109110111112152 unmodified lines26526626726826927027127227327427527627727827928077 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 LoaduseEffect(() => {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 => (<divkey={n.id}onClick={() => handleNotifClick(n)}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 lines89909192939471 unmodified lines16616716816917017117288 unmodified lines}};// We only search on Enter now, so we remove the useEffect watcherreturn (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 className={styles.notifTitle}>{n.title}</div><div className={styles.notifMsg}>{n.message}</div><div className={styles.notifTime}>{new Date(n.created_at).toLocaleString()}</div>88 unmodified lines899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212371 unmodified lines19519619719819920020120220320420520620788 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 LoaduseEffect(() => {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 watcherreturn (71 unmodified lines<div className={styles.notifEmpty}>No new system alerts</div>) : (notifications.map(n => (<divkey={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 lines56575859606162636463 unmodified lines12812913013113213355 unmodified lineslifespan=lifespan,docs_url="/docs",redoc_url="/redoc",strict_slashes=False,)# --- 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"}55 unmodified lines565758596061626364656667686963 unmodified lines13313413513655 unmodified lineslifespan=lifespan,docs_url="/docs",redoc_url="/redoc",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"])
17 unmodified lines18192021222317 unmodified linestitle = Column(String(255), nullable=False)message = Column(Text, nullable=False)is_read = Column(Boolean, default=False)created_at = Column(DateTime(timezone=False),default=datetime.utcnow,17 unmodified lines1819202122232417 unmodified linestitle = 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 tocreated_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