""" Message endpoints: threaded messaging for tickets with BOLA protection. """ import logging logger = logging.getLogger(__name__) from typing import Any, List, Dict from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, status, Response, BackgroundTasks from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from core.deps import get_db, get_current_user, get_arq_pool from core.permissions import require_roles, ALL_SC_ROLES from models.user import User, UserRole from models.ticket import Ticket from models.message import Message from schemas.message import MessageCreate, MessageResponse router = APIRouter() async def parse_mentions(content: str, workspace_id: UUID, db: AsyncSession) -> List[Dict[str, Any]]: """ Parses @email mentions from content and returns a list of valid user dicts. """ import re emails = re.findall(r"@([\w\.-]+@[\w\.-]+\.\w+)", content) if not emails: return [] unique_emails = list(set(emails)) from models.user_workspace import UserWorkspace stmt = ( select(User) .join(UserWorkspace, User.id == UserWorkspace.user_id) .where( UserWorkspace.workspace_id == workspace_id, User.email.in_(unique_emails), User.deleted_at.is_(None) ) ) result = await db.execute(stmt) users = result.scalars().all() return [{"user_id": str(u.id), "name": u.full_name} for u in users] async def sanitize_message_response(message: Message, db: AsyncSession) -> Message: from models.user_workspace import UserWorkspace # Fetch the role for the user *in this specific workspace* stmt = ( select(User.full_name, UserWorkspace.role) .outerjoin(UserWorkspace, (User.id == UserWorkspace.user_id) & (UserWorkspace.workspace_id == message.workspace_id)) .where(User.id == message.sender_id) ) res = await db.execute(stmt) row = res.fetchone() if row: setattr(message, "sender_name", row[0]) setattr(message, "sender_role", row[1] or UserRole.CUSTOMER_USER) # Fallback to base role return message @router.post("/{ticket_id}/messages/", response_model=MessageResponse, status_code=status.HTTP_201_CREATED) async def send_message( ticket_id: UUID, payload: MessageCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), arq_pool: Any = Depends(get_arq_pool), background_tasks: BackgroundTasks = None ) -> Any: """Send a message on a ticket. Enforces BOLA protection for customers.""" is_staff = current_user.role in ALL_SC_ROLES # 1. Verify ticket access stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.deleted_at.is_(None) ) if is_staff: if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) else: # Customers can ONLY view messages for tickets they created stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) stmt = stmt.where(Ticket.created_by == current_user.id) result = await db.execute(stmt) ticket = result.scalar_one_or_none() if not ticket: raise HTTPException(status_code=404, detail="Ticket not found or access denied") # 2. Internal notes validation if payload.is_internal and not is_staff: raise HTTPException(status_code=403, detail="Only agents can post internal notes") # 3. Parse Mentions (Using ticket's workspace for Super Admin context) mentions = await parse_mentions(payload.content, ticket.workspace_id, db) new_message = Message( content=payload.content, is_internal=payload.is_internal, ticket_id=ticket_id, workspace_id=ticket.workspace_id, # Use ticket's actual workspace sender_id=current_user.id, mentions=mentions ) db.add(new_message) await db.commit() await db.refresh(new_message) # --- Observability: Record Message Event --- from core.observability import record_workflow_step await record_workflow_step( db, entity_id=ticket_id, workspace_id=current_user.workspace_id, workflow_type="LIFECYCLE", step_name="MESSAGE_ADDED", input_data={"sender_role": current_user.role, "is_internal": payload.is_internal}, output_data={"message_id": str(new_message.id)}, current_stage="CONVERSATION_UPDATE" ) await db.commit() # Trigger Notifications if mentions: try: from core.config import get_redis_settings from arq import create_pool redis = await create_pool(get_redis_settings()) 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}") # --- 3. Refresh Summarization Context --- await arq_pool.enqueue_job("auto_summarize_ticket", ticket_id) # --- 4. Notify Customer of Expert Response --- # Only if sender is staff and message is public if is_staff and not payload.is_internal and ticket.created_by != current_user.id: try: await arq_pool.enqueue_job("send_triple_notification", str(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}") # --- 5. Notify Assigned Agent of Customer Reply --- # Only if sender is NOT staff (i.e. is customer) and there is an assignee to notify if not is_staff and ticket.assigned_to: try: await arq_pool.enqueue_job("send_triple_notification", str(ticket.assigned_to), str(ticket.workspace_id), "📬 Customer Reply", f"The customer has replied to ticket: '{ticket.title}'", link=f"/dashboard?ticket={ticket.id}" ) except Exception as e: logger.error(f"Failed to queue agent reply notification: {e}") return await sanitize_message_response(new_message, db) @router.patch("/{ticket_id}/messages/{message_id}/", response_model=MessageResponse) async def edit_message( ticket_id: UUID, message_id: UUID, payload: MessageCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), arq_pool: Any = Depends(get_arq_pool) ) -> Any: """Edit a message. Only the sender can edit.""" stmt = select(Message).where( Message.id == message_id, Message.ticket_id == ticket_id, Message.deleted_at.is_(None) ) result = await db.execute(stmt) message = result.scalar_one_or_none() if not message: raise HTTPException(status_code=404, detail="Message not found") if message.sender_id != current_user.id: raise HTTPException(status_code=403, detail="You can only edit your own messages") # Update content old_content = message.content message.content = payload.content if old_content != payload.content: # Use message's workspace context mentions = await parse_mentions(payload.content, message.workspace_id, db) message.mentions = mentions db.add(message) await db.commit() await db.refresh(message) # Refresh Summary if content edited if old_content != payload.content: await arq_pool.enqueue_job("auto_summarize_ticket", ticket_id) return await sanitize_message_response(message, db) @router.delete("/{ticket_id}/messages/{message_id}/", status_code=status.HTTP_204_NO_CONTENT, response_model=None, response_class=Response) async def delete_message( ticket_id: UUID, message_id: UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Delete a message. Sender or Admins can delete.""" stmt = select(Message).where( Message.id == message_id, Message.ticket_id == ticket_id, Message.deleted_at.is_(None) ) result = await db.execute(stmt) message = result.scalar_one_or_none() if not message: raise HTTPException(status_code=404, detail="Message not found") # Permission check: Owner or Admin/Lead (Strictly within workspace) is_owner = message.sender_id == current_user.id is_admin = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.CUSTOMER_ADMIN] # HARDENING: Verify message belongs to current user's workspace (unless Super Admin) if current_user.role != UserRole.SC_ADMIN and message.workspace_id != current_user.workspace_id: raise HTTPException(status_code=403, detail="Not authorized to access messages in this workspace") if not (is_owner or is_admin): raise HTTPException(status_code=403, detail="Not authorized to delete this message") from datetime import datetime message.deleted_at = datetime.utcnow() message.deleted_by_id = current_user.id db.add(message) await db.commit() return None @router.get("/{ticket_id}/messages/", response_model=List[MessageResponse]) async def list_messages( ticket_id: UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """List all messages with optimized sender info (Single Query Join).""" from sqlalchemy.orm import aliased from models.user_workspace import UserWorkspace is_staff = current_user.role in ALL_SC_ROLES # 1. Verify ticket access stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.deleted_at.is_(None) ) if is_staff: if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) else: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) stmt = stmt.where(Ticket.created_by == current_user.id) result = await db.execute(stmt) ticket = result.scalar_one_or_none() if not ticket: raise HTTPException(status_code=404, detail="Ticket not found or access denied") # 2. Optimized Fetch: All messages + Sender Names + Sender Roles in THIS workspace Sender = aliased(User) Link = aliased(UserWorkspace) msg_stmt = ( select(Message, Sender.full_name, Link.role) .outerjoin(Sender, Message.sender_id == Sender.id) .outerjoin(Link, (Sender.id == Link.user_id) & (Link.workspace_id == ticket.workspace_id)) .where( Message.ticket_id == ticket_id, Message.deleted_at.is_(None) ) .order_by(Message.created_at.asc()) ) if not is_staff: msg_stmt = msg_stmt.where(Message.is_internal == False) result = await db.execute(msg_stmt) rows = result.all() out = [] for m, name, role in rows: setattr(m, "sender_name", name or "Unknown") setattr(m, "sender_role", role or UserRole.CUSTOMER_USER) out.append(m) return out