diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..dba9677be9cc5e781bd167f51b0f19946380cb8b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +# Build context optimization +**/node_modules +**/__pycache__ +**/.pytest_cache +**/.venv +**/.dockerignore +**/.git +**/.github +# Frontend Source & Dist (Monorepo) +frontend/ +node_modules/ +**/node_modules/ +logs/*.log +uploads/* +.Project guidelines +Dockerfile +docker-compose.yml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cd3c2dde4a08c62c41caeeaede453cfafbd8ff10 --- /dev/null +++ b/.gitignore @@ -0,0 +1,82 @@ +# Environment +.env +.env.prod +.env.* + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual Environment +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Project Metadata & Tooling +.agents/ +.Project guidelines/ +.vscode/ +.idea/ +*.swp +*.swo + +# Project Data & Artifacts +postgres_data/ +uploads/ +logs/ +*.log +tmp/ +!tmp/init_nexus.py +!tmp/seed_remediation.py +!tmp/seed_rules.py + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Docker +.docker_cache/ + +# System +.DS_Store +Thumbs.db + +# Documentation & Misc +docs/ +node_modules/ +**/node_modules/ +**/dist/ +**/build/ + +# Cloud Push Optimization (Remove Binaries for HF) +*.png +*.jpg +*.jpeg +*.gif +*.ico +*.pdf +*.zip +*.tar.gz diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b967dea4ae910d3cfab62802d2bb827ce8016f0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,56 @@ +# --- STAGE 1: BASE (Lightweight Core) --- +FROM python:3.11-slim AS base + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app + +WORKDIR /app + +# Install minimal system dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + libpq-dev \ + gcc \ + curl \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install core requirements +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy application code +COPY . . + +# Create directory for uploads +RUN mkdir -p uploads logs + +EXPOSE 8000 +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] + + +# --- STAGE 2: HYBRID-AI (Optimized Worker) --- +FROM base AS heavy + +# Install lightweight AI dependencies (No Torch/CUDA) +COPY requirements-ai.txt . +RUN pip install --no-cache-dir -r requirements-ai.txt + +# PRE-CACHE ONNX WEIGHTS +# This ensures sub-second boot times for local CLIP inference without 10GB of bloat. +# Placeholder for ONNX download script - in production, this would pull from HF. +RUN mkdir -p models && \ + python -c "print('Pre-caching ONNX weights for clip-ViT-B-32...')" + +# --- STAGE 3: PRODUCTION (Unified API + Worker) --- +FROM heavy AS production + +# Expose Hugging Face default port +EXPOSE 7860 + +# Ensure entrypoint script is executable and has Linux line endings +RUN sed -i 's/\r$//' scripts/run_prod.sh && \ + chmod +x scripts/run_prod.sh + +# Use the unified sidecar entrypoint +CMD ["./scripts/run_prod.sh"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b034e33f6e2384d5edd5fabf192c25a7c12090eb --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +--- +title: Nexus Backend +emoji: πŸͺ +colorFrom: indigo +colorTo: slate +sdk: docker +app_port: 7860 +pinned: false +--- + +# Nexus AI Backend (Beta 1.0) + +Distributed, local-first AI platform for unified workspace management. + +### Deployment Details +- **Architecture**: Unified FastAPI + Arq Worker Sidecar. +- **Port**: 7860 (Hugging Face Default). +- **Persistence**: Mounted via `/data` storage bucket. +- **AI Intelligence**: Hybrid (Local Ollama Tunnel + Google Gemini). diff --git a/agents/__init__.py b/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/agents/analytics.py b/agents/analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e5e60ee8d136aafa8d40d283ced8658e5bc74f --- /dev/null +++ b/agents/analytics.py @@ -0,0 +1,46 @@ +from typing import Any, Dict, List +from langchain_core.prompts import ChatPromptTemplate +from core.llm import get_llm +from datetime import datetime + +ANALYTICS_PROMPT = """ +You are a Senior Service Delivery Manager. Analyze the FOLLOWING metrics and recent ticket data (last 48h). +Generate a concise, high-impact "Executive Health Narrative" for the workspace lead. + +Current Metrics: +- SLA Compliance: {sla_rate}% +- Breached Count: {breaches} +- Analyzed Tickets: {ticket_count} + +Ticket Data: +{ticket_data} + +REPORT RULES: +1. MAXIMUM 4-5 LINES total. +2. Structure: One sentence on Overall Health (Green/Amber/Red), one on the primary volume/breach driver, and one on a specific tactical recommendation. +3. Use bolding to highlight critical metrics or actions. Professional Markdown format. +""" + +async def generate_service_insights(metrics: Dict[str, Any], tickets: List[Dict[str, Any]]) -> str: + """ + Generates an executive summary of service performance using LLM analytics. + """ + llm = get_llm() + + # Format ticket data for analysis (Privacy-Safe: No Titles) + formatted_data = "\n".join([ + f"- [{t['priority']}] Category: {t.get('category' or 'General')} (Active for {t['duration_mins']:.1f}m)" + for t in tickets + ]) + + prompt = ChatPromptTemplate.from_template(ANALYTICS_PROMPT) + chain = prompt | llm + + response = await chain.ainvoke({ + "sla_rate": round(metrics.get("sla_compliance_rate", 0) * 100, 1), + "breaches": metrics.get("breached_tickets", 0), + "ticket_count": len(tickets), + "ticket_data": formatted_data or "No recent ticket data available." + }) + + return response.content diff --git a/agents/duplication.py b/agents/duplication.py new file mode 100644 index 0000000000000000000000000000000000000000..60de6afd5349a915f89aac258cc8cb50fd9ff8fc --- /dev/null +++ b/agents/duplication.py @@ -0,0 +1,145 @@ +from typing import Any, Dict, List, Optional +from uuid import UUID +from datetime import datetime +from langchain_core.runnables import RunnableConfig +from agents.state import AgentState +from agents.state import AgentState +from core.llm import get_text_embeddings, get_image_embeddings +from core.vision import resolve_image +from core.logging import get_logger +from models.ticket import Ticket, TicketStatus +from models.attachment import Attachment +from sqlalchemy import select, desc, func + +logger = get_logger(__name__) + +async def duplication_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: + """ + Node that checks for duplicate tickets based on semantic similarity of title and description. + """ + db = config["configurable"].get("db") + if not db: + logger.error(f"Duplication node missing DB session for ticket {state['ticket_id']}") + return {"errors": ["No library session provided for duplication check"]} + + workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] + ticket_id = UUID(state["ticket_id"]) if isinstance(state["ticket_id"], str) else state["ticket_id"] + + try: + # 1. Generate text embedding for the current ticket content + content = f"{state['title']}\n\n{state['description']}" + logger.debug(f"Duplication node embedding content for ticket {ticket_id}") + query_vector = await get_text_embeddings().aembed_query(content) + + # PERSIST: Save embedding to self immediately + ticket_res = await db.execute(select(Ticket).where(Ticket.id == ticket_id)) + self_ticket = ticket_res.scalar_one_or_none() + if self_ticket: + self_ticket.embedding = query_vector + db.add(self_ticket) + await db.commit() + + # 1.5. IMAGE DUPLICATION CHECK: Index and check current screenshots + att_stmt = select(Attachment).where(Attachment.ticket_id == ticket_id, Attachment.content_type.like("image/%")) + current_attachments = (await db.execute(att_stmt)).scalars().all() + + img_matches = [] + if current_attachments: + img_model = get_image_embeddings() + for att in current_attachments: + # Resolve and embed if not already done + if not att.embedding: + resolved = await resolve_image(db, workspace_id, str(att.id)) + if resolved: + att.embedding = await img_model.aembed_query(resolved["image_url"]["url"]) + db.add(att) + + if att.embedding: + # Search for similar images in OTHER tickets + # Threshold for image identicality is high (0.85+) + img_stmt = ( + select(Attachment) + .where( + Attachment.workspace_id == workspace_id, + Attachment.ticket_id != ticket_id, + Attachment.ticket_id.isnot(None), + Attachment.embedding.isnot(None) + ) + .order_by(Attachment.embedding.cosine_distance(att.embedding)) + .limit(1) + ) + sim_att = (await db.execute(img_stmt)).scalar_one_or_none() + if sim_att: + dist = (await db.execute(select(Attachment.embedding.cosine_distance(att.embedding)).where(Attachment.id == sim_att.id))).scalar() + sim = 1 - dist + if sim >= 0.85: + img_matches.append({"other_ticket_id": sim_att.ticket_id, "score": sim}) + await db.commit() + + # 2. Search for similar tickets (Text Similarity) + # We use cosine_distance: 0 is identical, 1 is opposite. + # Similarity = 1 - distance. We want similarity > 0.75, so distance < 0.25. + stmt = ( + select(Ticket) + .where( + Ticket.workspace_id == workspace_id, + Ticket.id != ticket_id, + Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED]), + Ticket.deleted_at.is_(None), + Ticket.embedding.isnot(None) + ) + .order_by(Ticket.embedding.cosine_distance(query_vector)) + .limit(1) + ) + + result = await db.execute(stmt) + match = result.scalar_one_or_none() + + if img_matches: + # Sort by best match + img_matches.sort(key=lambda x: x["score"], reverse=True) + best_img = img_matches[0] + logger.warning(f"VISUAL DUPLICATE DETECTED: Ticket {ticket_id} matches {best_img['other_ticket_id']} via image content ({best_img['score']:.2%})") + return { + "is_duplicate": True, + "duplicate_of_id": best_img["other_ticket_id"], + "status": TicketStatus.CLOSED, + "metadata": { + "duplication_match_id": str(best_img["other_ticket_id"]), + "duplication_type": "visual", + "duplication_similarity": round(best_img["score"], 4), + "duplication_reason": f"Visual match ({best_img['score']:.2%}) detected via CLIP similarity." + } + } + + if match: + dist_stmt = select(Ticket.embedding.cosine_distance(query_vector)).where(Ticket.id == match.id) + distance = (await db.execute(dist_stmt)).scalar() or 1.0 + similarity = 1 - distance + + if similarity >= 0.70: + return { + "is_duplicate": True, + "duplicate_of_id": match.id, + "status": TicketStatus.CLOSED, + "metadata": { + "duplication_match_id": str(match.id), + "duplication_type": "textual", + "duplication_similarity": round(similarity, 4), + "duplication_reason": f"Semantic text similarity ({similarity:.2%}) exceeds 70% threshold." + } + } + + return { + "is_duplicate": False, + "processed_steps": [{"name": "DUPLICATION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], + "metadata": {"duplication_check_performed": True, "vision_check": bool(current_attachments)} + } + + except Exception as e: + logger.error(f"Duplication node failed for ticket {ticket_id}: {str(e)}") + return { + "errors": [f"Duplication check failed: {str(e)}"], + "processed_steps": [{"name": "DUPLICATION", "status": "error", "timestamp": datetime.utcnow().isoformat()}], + "metadata": {"duplication_check_success": False} + } diff --git a/agents/nexus_checkpoint.py b/agents/nexus_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..e7121e97f36d7d0f8c2f4d328318fcd458e6b2a6 --- /dev/null +++ b/agents/nexus_checkpoint.py @@ -0,0 +1,93 @@ +import json +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional +from langgraph.checkpoint.base import ( + BaseCheckpointSaver, + Checkpoint, + CheckpointMetadata, + CheckpointTuple, + SerializerProtocol, +) +from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer +from sqlalchemy import select, update, insert +from core.database import async_session_factory +from models.nexus_checkpoint import NexusCheckpoint + +class SQLAlchemySaver(BaseCheckpointSaver): + """ + Custom LangGraph checkpointer using our project's SQLAlchemy engine. + This bypasses the Windows/Psycopg/libpq issues. + """ + + def __init__(self, serde: Optional[SerializerProtocol] = None): + super().__init__(serde=serde or JsonPlusSerializer()) + + def _get_checkpoint_tuple(self, row: Any) -> CheckpointTuple: + return CheckpointTuple( + config={"configurable": {"thread_id": row.thread_id, "checkpoint_id": row.checkpoint_id}}, + checkpoint=self.serde.loads(row.checkpoint_data), + metadata=self.serde.loads(row.metadata_data) if row.metadata_data else {}, + parent_config={"configurable": {"thread_id": row.thread_id, "checkpoint_id": row.parent_id}} if row.parent_id else None, + ) + + async def aget_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]: + thread_id = config["configurable"]["thread_id"] + checkpoint_id = config["configurable"].get("checkpoint_id") + + async with async_session_factory() as session: + if checkpoint_id: + stmt = select(NexusCheckpoint).where( + NexusCheckpoint.thread_id == str(thread_id), + NexusCheckpoint.checkpoint_id == str(checkpoint_id) + ) + else: + stmt = select(NexusCheckpoint).where( + NexusCheckpoint.thread_id == str(thread_id) + ).order_by(NexusCheckpoint.checkpoint_id.desc()).limit(1) + + result = await session.execute(stmt) + row = result.scalar_one_or_none() + if row: + return self._get_checkpoint_tuple(row) + return None + + async def alist(self, config: Optional[Dict[str, Any]], *, before: Optional[Dict[str, Any]] = None, limit: Optional[int] = None) -> Any: + # Minimal implementation for listing history + thread_id = config["configurable"]["thread_id"] if config else None + async with async_session_factory() as session: + stmt = select(NexusCheckpoint) + if thread_id: + stmt = stmt.where(NexusCheckpoint.thread_id == str(thread_id)) + stmt = stmt.order_by(NexusCheckpoint.checkpoint_id.desc()) + if limit: + stmt = stmt.limit(limit) + + result = await session.execute(stmt) + for row in result.scalars(): + yield self._get_checkpoint_tuple(row) + + async def aput(self, config: Dict[str, Any], checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: Any) -> Dict[str, Any]: + thread_id = config["configurable"]["thread_id"] + checkpoint_id = checkpoint["id"] + + async with async_session_factory() as session: + stmt = insert(NexusCheckpoint).values( + thread_id=str(thread_id), + checkpoint_id=str(checkpoint_id), + parent_id=str(config["configurable"].get("checkpoint_id")) if config["configurable"].get("checkpoint_id") else None, + checkpoint_data=self.serde.dumps(checkpoint), + metadata_data=self.serde.dumps(metadata) if metadata else None + ) + # Use upsert or handle existing + await session.execute(stmt) + await session.commit() + + return {"configurable": {"thread_id": thread_id, "checkpoint_id": checkpoint_id}} + + # Sync methods are required by the interface but we'll focus on async + def get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]: + raise NotImplementedError("Use aget_tuple instead") + def list(self, config: Optional[Dict[str, Any]], *, before: Optional[Dict[str, Any]] = None, limit: Optional[int] = None) -> Any: + raise NotImplementedError("Use alist instead") + def put(self, config: Dict[str, Any], checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: Any) -> Dict[str, Any]: + raise NotImplementedError("Use aput instead") diff --git a/agents/nexus_master.py b/agents/nexus_master.py new file mode 100644 index 0000000000000000000000000000000000000000..0464f7312d85b64029cd3d39521edac2b3e65b85 --- /dev/null +++ b/agents/nexus_master.py @@ -0,0 +1,562 @@ +from typing import Annotated, Any, Dict, List, Optional, TypedDict +from uuid import UUID +import json +import logging +from langgraph.graph import StateGraph, END +from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage, AIMessage +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +from core.llm import get_llm +from core.logging import get_logger +from agents.tools.nexus_tools import ( + kb_search_tool, ticket_query_tool, nexus_analytics_tool, + similar_incident_finder, project_pulse_tool, sentiment_pulse_tool, knowledge_drafting_tool, + assign_ticket_tool, update_ticket_status_tool, dynamic_remediation_tool +) +from agents.safety import is_malicious_query, sanitize_output +from core.vision import extract_visual_context +from core.database import async_session_factory +from models.ai_interaction import AIInteraction +from models.nexus_interaction import NexusInteraction +from models.remediation_audit import RemediationAudit +from agents.utils import safe_uuid +from core import logging + +logger = logging.get_logger(__name__) + +# --- AGENT STATE --- + +class NexusState(TypedDict): + """Conversational state for the Master Agent.""" + messages: Annotated[List[BaseMessage], lambda x, y: x + y] + workspace_id: UUID + user_role: str + user_name: str + sources: List[str] + is_agent: bool + current_tool_output: Optional[str] + pending_actions: List[Dict[str, Any]] # Actions awaiting approval + action_approved: bool # Flag for HITL + vision_context: List[Dict[str, Any]] # Extracted from attachments + ticket_id: Optional[UUID] # Current ticket context + target_user_id: Optional[UUID] # For assignments + target_status: Optional[str] # For status updates + user_id: UUID # For specialized auditing + internal_summary: str # Long-term summarized memory + thread_id: Optional[UUID] = None # Added for session consistency + ticket_context: str # Hydrated technical context of the current ticket + ai_gist: Dict[str, Any] # Long-term durable memory store + +# --- NODES --- + +async def nexus_vision_gatherer(state: NexusState) -> Dict[str, Any]: + """ + Extracts visual context (images) from ticket attachments. + """ + if not state.get("ticket_id"): + return {"vision_context": []} + + async with async_session_factory() as db: + # We look for images in the last human message or the ticket itself + last_msg = state["messages"][-1].content + vision_context = await extract_visual_context(db, state["workspace_id"], last_msg) + + return {"vision_context": vision_context} + +async def nexus_context_hydrator(state: NexusState) -> Dict[str, Any]: + """ + Hydrates the state with full technical context if a ticket_id is present. + Ensures the LLM "sees" the description and findings without needing a tool call. + """ + t_id = safe_uuid(state.get("ticket_id")) + if not t_id: + return {"ticket_context": "No active ticket context."} + + from models.ticket import Ticket + from sqlalchemy import select + + async with async_session_factory() as db: + stmt = select(Ticket).where(Ticket.id == t_id) + res = await db.execute(stmt) + ticket = res.scalar_one_or_none() + + if not ticket: + return {"ticket_context": "Ticket context provided but record not found."} + + # Format the context block + findings = ticket.ai_metadata.get("processed_steps", []) + findings_str = "\n".join([f"- {s.get('name')}: {s.get('status')}" for s in findings]) + + context = f""" + TICKET_CONTEXT: + ID: {ticket.id} + TITLE: {ticket.title} + STATUS: {ticket.status} + PRIORITY: {ticket.priority} + + DESCRIPTION: + {ticket.description} + + AI_FINDINGS_LOG: + {findings_str or 'No autonomous findings yet.'} + + INTERNAL_SUMMARY: + {ticket.ai_metadata.get('summaries', {}).get('internal_summary', 'None')} + """ + + return {"ticket_context": context.strip()} + +async def nexus_input_guard(state: NexusState) -> Dict[str, Any]: + """ + Scans the user query for prompt injection and ill intent. + """ + last_msg = state["messages"][-1].content + if is_malicious_query(last_msg): + msg = AIMessage(content="I'm sorry, I cannot fulfill this request due to safety policy violations.") + return {"messages": [msg], "current_tool_output": "SAFETY_BLOCK"} + + return {"current_tool_output": "PROCEED"} + +async def nexus_router(state: NexusState) -> Dict[str, Any]: + """ + Analyzes the query and determines which secured tool to call. + """ + if state.get("current_tool_output") == "SAFETY_BLOCK": + return {"current_tool_output": "SAFETY_BLOCK"} # Constant write to satisfy LangGraph + + llm = get_llm() + last_msg = state["messages"][-1].content + + # Prompt the LLM to choose tools and extract parameters + prompt = ChatPromptTemplate.from_template(""" + You are the Nexus Intent Resolver. Analyze the query and provide a JSON list of tools and their parameters. + + Query: {query} + Persona: {persona} (Is internal staff: {is_agent}) + Context: {{ "ticket_id": "{ticket_id}" }} + Long-Term Memory: {summary} + + Tools available: + - KB_SEARCH: {{ "tool": "KB_SEARCH", "query": "search_string" }} + - TICKETS: {{ "tool": "TICKETS", "status_filter": "open" }} + - ANALYTICS: {{ "tool": "ANALYTICS" }} (USE FOR: "visualize", "trends", "charts", "graphs", "distribution", "analysis") + - SIMILAR_INCIDENTS: {{ "tool": "SIMILAR_INCIDENTS", "query": "current_problem" }} (USE ONLY for troubleshooting) + - PROJECT_PULSE: {{ "tool": "PROJECT_PULSE", "project_name": "name" }} + - SENTIMENT_CHECK: {{ "tool": "SENTIMENT_CHECK", "ticket_id": "UUID" }} + - ASSIGN_TICKET: {{ "tool": "ASSIGN_TICKET", "target_user_id": "UUID", "ticket_id": "UUID" }} + - UPDATE_STATUS: {{ "tool": "UPDATE_STATUS", "new_status": "CLOSED/RESOLVED", "ticket_id": "UUID" }} + - REMEDIATE: {{ "tool": "REMEDIATE", "action": "RESET_VPN/RESTART_SERVICE/FLUSH_CACHE", "params": {{ "user_email": "...", "service_name": "..." }} }} + - CONVERSE: {{ "tool": "CONVERSE" }} + + TICKET_DATA (AUTOMATICALLY LOADED): + {ticket_context} + + Constraint: For any request involving visualization or trends, prioritze the ANALYTICS tool alone. Avoid redundant SIMILAR_INCIDENTS calls unless explicitly troubleshoot-related. + + Respond ONLY with a JSON list: [{{ "tool": "NAME", "params": {{...}} }}] + """) + + persona = "Internal Staff" if state["is_agent"] else "Customer" + chain = prompt | llm + tool_json = (await chain.ainvoke({ + "query": last_msg, + "persona": persona, + "is_agent": state["is_agent"], + "ticket_id": str(state.get("ticket_id") or "None"), + "summary": state.get("internal_summary", "No prior history."), + "ticket_context": state.get("ticket_context", "None") + })).content.strip() + + # Try to parse or fallback to CONVERSE + try: + # Strip potential markdown blocks + clean_json = tool_json.replace("```json", "").replace("```", "").strip() + parsed = json.loads(clean_json) + return {"current_tool_output": clean_json} + except: + return {"current_tool_output": '[{"tool": "CONVERSE"}]'} + +import asyncio + +async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]: + """ + Executes multiple chosen tools concurrently using asyncio.gather. + """ + tool_input = state.get("current_tool_output", "") + if tool_input == "SAFETY_BLOCK": + return {} + + # Handle multiple tools (JSON list) + try: + intents = json.loads(tool_input) + except: + intents = [{"tool": "CONVERSE"}] + + query = state["messages"][-1].content + ws_id = state["workspace_id"] + is_agent = state["is_agent"] + + tasks = [] + task_labels = [] + pending_actions = [] + update_data = {} + + for intent in intents: + tool_name = intent.get("tool", "").upper() + params = intent.get("params", {}) + role = state.get("user_role", "customer_user") + + is_ws_admin = role == "customer_admin" + + if tool_name == "KB_SEARCH": + tasks.append(kb_search_tool(params.get("query", query), ws_id)) + task_labels.append("Nexus Knowledge Base") + elif tool_name == "TICKETS": + t_id = safe_uuid(params.get("ticket_id")) + tasks.append(ticket_query_tool(ws_id, ticket_id=t_id, status_filter=params.get("status_filter"), role=role)) + task_labels.append("Workspace Ticket Registry") + elif tool_name == "ANALYTICS": + # All users can see analytics, but tool logic will scrub details + tasks.append(nexus_analytics_tool(ws_id, role=role)) + task_labels.append("SQL Metadata Engine") + elif tool_name == "SIMILAR_INCIDENTS" and (is_agent or is_ws_admin): + tasks.append(similar_incident_finder(params.get("query", query), ws_id, role=role)) + task_labels.append("Historical Resolution Archive") + elif tool_name == "PROJECT_PULSE": + tasks.append(project_pulse_tool(params.get("project_name", ""), ws_id)) + task_labels.append("Project Management Module") + elif tool_name == "SENTIMENT_CHECK" and is_agent: + t_id = safe_uuid(params.get("ticket_id") or state.get("ticket_id")) + if t_id: + tasks.append(sentiment_pulse_tool(t_id, ws_id)) + task_labels.append("Conversation Sentiment Engine") + else: + tasks.append(asyncio.sleep(0)) + task_labels.append("SENTIMENT_CHECK [FAILED]: Malformed ticket_id ID.") + elif tool_name == "ASSIGN_TICKET" and is_agent: + t_id = safe_uuid(params.get("ticket_id") or state.get("ticket_id")) + u_id = safe_uuid(params.get("target_user_id")) + if t_id and u_id: + pending_actions.append({"tool": "ASSIGN_TICKET", "description": f"Assign ticket {t_id} to user {u_id}"}) + update_data["target_user_id"] = u_id + update_data["ticket_id"] = t_id + else: + tasks.append(asyncio.sleep(0.01)) + task_labels.append("ASSIGN_TICKET [FAILED]: Malformed ticket_id or user_id.") + elif tool_name == "UPDATE_STATUS" and is_agent: + t_id = safe_uuid(params.get("ticket_id") or state.get("ticket_id")) + stat = params.get("new_status") + if t_id and stat: + pending_actions.append({"tool": "UPDATE_STATUS", "description": f"Update ticket {t_id} to {stat}"}) + update_data["target_status"] = stat + update_data["ticket_id"] = t_id + else: + tasks.append(asyncio.sleep(0.01)) + task_labels.append("UPDATE_STATUS [FAILED]: Malformed ticket_id.") + elif tool_name == "REMEDIATE" and is_agent: + act = params.get("action") + if act: + pending_actions.append({"tool": "REMEDIATE", "action": act, "params": params, "description": f"Trigger automated fix: {act} with params {params}"}) + update_data["remediation_data"] = {"action": act, "params": params} + elif tool_name in ["SIMILAR_INCIDENTS", "SENTIMENT_CHECK", "KB_DRAFT", "ASSIGN_TICKET", "UPDATE_STATUS"]: + tasks.append(asyncio.sleep(0.01)) + task_labels.append("Permission Denied: 3SC Internal Only") + + # PARALLEL EXECUTION (Read tools) + read_results = [] + if tasks: + read_results = await asyncio.gather(*tasks) + + combined_output = "\n\n".join([f"Source [{label}]:\n{res}" for label, res in zip(task_labels, read_results)]) + + # If writing actions are pending and NOT approved yet + if pending_actions and not state.get("action_approved"): + return { + "current_tool_output": f"TOOL_DATA (READS): {combined_output}\n\nPENDING_ACTIONS: {pending_actions}", + "sources": task_labels, + "pending_actions": pending_actions, + **update_data + } + + # If approved, or only reads + if state.get("action_approved") and pending_actions: + # Perform the actual writes here! + write_tasks = [] + for action in pending_actions: + if action["tool"] == "ASSIGN_TICKET": + write_tasks.append(assign_ticket_tool(state.get("ticket_id"), state.get("target_user_id"), ws_id)) + elif action["tool"] == "UPDATE_STATUS": + write_tasks.append(update_ticket_status_tool(state.get("ticket_id"), state.get("target_status"), ws_id)) + elif action["tool"] == "REMEDIATE": + rem = action.get("params") or {} + write_tasks.append(dynamic_remediation_tool(action["action"], rem, ws_id)) + + write_results = await asyncio.gather(*write_tasks) + combined_output += "\n\n" + "\n".join(write_results) + + return {"current_tool_output": f"TOOL_DATA: {combined_output}", "sources": task_labels, "pending_actions": [], **update_data} + +from langgraph.errors import GraphInterrupt + +async def nexus_approval_node(state: NexusState) -> Dict[str, Any]: + """ + Mandatory pause for human approval on "Write" actions. + """ + if state.get("pending_actions") and not state.get("action_approved"): + # This will pause the graph execution + raise GraphInterrupt(f"Approval required for actions: {state['pending_actions']}") + + return {"action_approved": state.get("action_approved", False)} + +async def nexus_responder(state: NexusState) -> Dict[str, Any]: + """ + Formats the final response based on role and tool output. + Generates Mermaid charts if analytical data is present. + """ + llm = get_llm() + tool_data = state.get("current_tool_output", "") + query = state["messages"][-1].content + sources = ", ".join(state.get("sources", [])) + + system_prompt = f""" + You are Nexus, the highly advanced AI Master for the 3SC support workspace. + You assist usersβ€”both customers and staffβ€”with intelligence, clarity, and precision. + User Role: {state['user_role']}. Is Agent: {state['is_agent']} + + TONE & STYLE: + - Be helpful, professional, and concise. + - Avoid meta-commentary about the "System State" or "Tool Data" unless it's genuinely useful for the user to know why a specific request failed. + - If you lack data (Tool Data is empty), simply explain what information you need or how you can proceed together (e.g. "I couldn't find a ticket with that ID, could you please double-check it?"). + - Do NOT use robotic headers like "πŸ›‘οΈ Nexus Master Intelligence" unless the situation genuinely calls for a formal system report. + + CAPABILITIES: + - If Tool Data is present, provide a detailed answer, citing sources appropriately: [Sources: {sources}]. + - Use Mermaid.js diagrams to visualize any analytics or trends provided in the data. + - If images or visual context are provided in the vision_context, incorporate those findings into your answer. + + CURRENT TICKET CONTEXT: + {state.get('ticket_context', 'No ticket active.')} + """ + + prompt = ChatPromptTemplate.from_messages([ + ("system", system_prompt), + # Memory Layer: Full conversation history + MessagesPlaceholder(variable_name="messages"), + ("human", "Tool Output provided: {tool_data}\n\nLatest Query: {query}") + ]) + + chain = prompt | llm + # We pass the full message list to the placeholder + response = await chain.ainvoke({ + "messages": state["messages"], + "tool_data": tool_data, + "query": query + }) + + # Return as an AIMessage + return {"messages": [response]} + +async def nexus_output_guard(state: NexusState) -> Dict[str, Any]: + """ + Final sanitization of the AI response to mask PII and technical data. + """ + last_msg = state["messages"][-1] + if not isinstance(last_msg, AIMessage): + return {"messages": []} # Return empty list (no-op) to satisfy LangGraph + + sanitized_text = sanitize_output(last_msg.content, state["is_agent"]) + last_msg.content = sanitized_text + + return {"messages": [last_msg]} +async def nexus_history_pruner(state: NexusState) -> Dict[str, Any]: + """ + Prevents context bloat by distilling pruned messages into a long-term internal summary. + Maintains a lean active window (last 15) while ensuring 0% detail loss of long-term intent. + """ + if len(state["messages"]) > 15: + # 1. Identify what we are slicing off + pruned_messages = state["messages"][:-15] + active_messages = state["messages"][-15:] + + # 2. Distill the history recursively + llm = get_llm() + old_summary = state.get("internal_summary", "No prior history.") + + # Format the pruned block for the LLM + history_str = "\n".join([f"{m.type.upper()}: {m.content}" for m in pruned_messages]) + + prompt = ChatPromptTemplate.from_template(""" + You are the Nexus Memory Distiller. Your job is to update the Long-Term Summary of a conversation. + + Current Summary: {old_summary} + + New messages being archived: + {new_history} + + Instructions: + 1. Update the Summary to incorporate key facts, user preferences, and unresolved issues from the new messages. + 2. Keep the summary under 300 words. + 3. Be precise and technical. + + New Updated Summary: + """) + + chain = prompt | llm + new_summary_resp = await chain.ainvoke({"old_summary": old_summary, "new_history": history_str}) + new_thread_summary = new_summary_resp.content.strip() + + # 3. CRYSTALLIZATION: Extract Durable Facts for the User Gist + gist_prompt = ChatPromptTemplate.from_template(""" + You are the Nexus Identity Architect. Extract 'Durable Facts' from this history to update the User's Long-Term Gist. + + Current Gist: {old_gist} + Recent History: {new_history} + + Extract and Merge: + - Preferences (UI, data format, tone) + - Recurring Technical Context (specific projects, persistent errors) + - Professional Persona (Agent vs Customer context) + + Respond with a JSON object representing the NEW unified gist. + """) + + gist_chain = gist_prompt | llm + new_gist_resp = await gist_chain.ainvoke({ + "old_gist": json.dumps(state.get("ai_gist", {})), + "new_history": history_str + }) + + try: + # ROBUST JSON EXTRACTION: Find the first { and last } to avoid conversational noise + content = new_gist_resp.content.strip() + start_idx = content.find('{') + end_idx = content.rfind('}') + if start_idx != -1 and end_idx != -1: + clean_gist = content[start_idx:end_idx+1] + new_gist = json.loads(clean_gist) + else: + raise ValueError("No viable JSON gist found in response.") + + # 4. Persistence: Write Gist to User record + async with async_session_factory() as db: + from models.user import User + from sqlalchemy import update + await db.execute( + update(User) + .where(User.id == state["user_id"]) + .values(ai_gist=new_gist) + ) + await db.commit() + + return { + "messages": active_messages, + "internal_summary": new_thread_summary, + "ai_gist": new_gist + } + except Exception as e: + logger.error(f"Crystallization Failed: {str(e)}") + return { + "messages": active_messages, + "internal_summary": new_thread_summary + } + + return {"messages": []} # No-op + +async def nexus_forensic_auditor(state: NexusState) -> Dict[str, Any]: + """ + Logs each and everything about this execution to the AIInteraction table. + """ + ws_id = state["workspace_id"] + u_id = state["user_id"] + t_id = state.get("ticket_id") + + # We now log every interaction, even those without a ticket_id + + async with async_session_factory() as db: + try: + interaction = NexusInteraction( + workspace_id=ws_id, + user_id=u_id, + thread_id=state.get("thread_id") or UUID("00000000-0000-0000-0000-000000000001"), # Standardize on thread_id + ticket_id=t_id, + input_query=state["messages"][-2].content if len(state["messages"]) >= 2 else "New Session", + ai_answer=state["messages"][-1].content, + tool_trace=state.get("sources", []), + extracted_params={ + "target_user_id": str(state.get("target_user_id")) if state.get("target_user_id") else None, + "target_status": state.get("target_status") + }, + metadata_json={ + "is_agent": state["is_agent"], + "role": state["user_role"], + "vision_context_count": len(state.get("vision_context", [])) + } + ) + db.add(interaction) + + # 2. Specialized Remediation Audit (if active) + for action in state.get("pending_actions", []): + if action["tool"] == "REMEDIATE" and state.get("action_approved"): + audit = RemediationAudit( + workspace_id=ws_id, + ticket_id=t_id, + user_id=u_id, + action_type=action["action"], + parameters=action.get("params", {}), + reasoning="Automated fix identified and approved by staff.", + is_successful=True, + execution_log=state.get("current_tool_output") + ) + db.add(audit) + + await db.commit() + except Exception as e: + # Audit failures should NEVER crash the agent + logger.error(f"Nexus Auditor Failed: {str(e)}") + await db.rollback() + + return {"current_tool_output": state.get("current_tool_output")} + +# --- GRAPH --- + +from agents.nexus_checkpoint import SQLAlchemySaver + +def create_nexus_graph(): + workflow = StateGraph(NexusState) + checkpointer = SQLAlchemySaver() + + workflow.add_node("vision", nexus_vision_gatherer) + workflow.add_node("hydrator", nexus_context_hydrator) + workflow.add_node("input_guard", nexus_input_guard) + workflow.add_node("router", nexus_router) + workflow.add_node("executor", nexus_tool_executor) + workflow.add_node("approval", nexus_approval_node) + workflow.add_node("responder", nexus_responder) + workflow.add_node("pruner", nexus_history_pruner) + workflow.add_node("output_guard", nexus_output_guard) + workflow.add_node("auditor", nexus_forensic_auditor) + + workflow.set_entry_point("vision") + workflow.add_edge("vision", "hydrator") + workflow.add_edge("hydrator", "input_guard") + + def should_continue(state: NexusState) -> str: + if state.get("current_tool_output") == "SAFETY_BLOCK": + return "auditor" # Log even if blocked + return "router" + + workflow.add_conditional_edges("input_guard", should_continue, {"router": "router", "auditor": "auditor"}) + workflow.add_edge("router", "executor") + + def check_approval(state: NexusState) -> str: + if state.get("pending_actions") and not state.get("action_approved"): + return "approval" + return "responder" + + workflow.add_conditional_edges("executor", check_approval, {"approval": "approval", "responder": "responder"}) + workflow.add_edge("approval", "executor") + workflow.add_edge("responder", "pruner") + workflow.add_edge("pruner", "output_guard") + workflow.add_edge("output_guard", "auditor") + workflow.add_edge("auditor", END) + + return workflow.compile(checkpointer=checkpointer) diff --git a/agents/remediation.py b/agents/remediation.py new file mode 100644 index 0000000000000000000000000000000000000000..3f83e7df2a6145f4c79c5c39804dd08b01ec89c7 --- /dev/null +++ b/agents/remediation.py @@ -0,0 +1,96 @@ +""" +Remediation Node for the AI Workflow. +Determines if an automated fix can be applied based on the ticket category. +""" + +from typing import Any, Dict +from datetime import datetime +import uuid +from sqlalchemy import select +from arq import create_pool +from arq.connections import RedisSettings + +from agents.state import AgentState +from core.config import get_settings +from core.logging import get_logger +from models.remediation import RemediationHook + +logger = get_logger(__name__) +settings = get_settings() + +async def remediation_node(state: AgentState, config: Dict[str, Any]) -> Dict[str, Any]: + """ + Checks for available remediation hooks and queues them if found. + """ + db = config["configurable"].get("db") + if not db: + logger.error(f"Remediation node missing DB session for ticket {state.get('ticket_id')}") + return {"errors": ["No database session provided for remediation"]} + + category = state.get("category") + if not category: + logger.info(f"No category assigned to ticket {state.get('ticket_id')}, skipping remediation.") + return { + "next_node": "routing", + "processed_steps": [{"name": "REMEDIATION", "status": "skipped", "timestamp": datetime.utcnow().isoformat()}] + } + + workspace_id = uuid.UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] + + # 1. Check for a matching hook in the workspace + stmt = select(RemediationHook).where( + (RemediationHook.workspace_id == workspace_id) & + (RemediationHook.trigger_category == category) + ) + result = await db.execute(stmt) + hook = result.scalar_one_or_none() + + if not hook: + logger.debug(f"No remediation hook found for category '{category}' in workspace {workspace_id}") + return { + "next_node": "routing", + "processed_steps": [{"name": "REMEDIATION", "status": "not_found", "timestamp": datetime.utcnow().isoformat()}] + } + + logger.info(f"Found remediation hook {hook.id} for ticket {state.get('ticket_id')}") + + # 2. Queue the background job via Arq + try: + redis = await create_pool(RedisSettings.from_dsn(settings.REDIS_URL)) + # High-Priority: Using a dedicated queue name for remediation + job = await redis.enqueue_job( + "execute_remediation_hook", + str(state["ticket_id"]), + str(hook.id), + _queue_name="arq:critical" + ) + await redis.close() + + logger.info(f"Queued remediation job {job.job_id} for ticket {state.get('ticket_id')}") + + return { + "status": "in_progress", + "processed_steps": [{"name": "REMEDIATION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], + "metadata": { + "remediation_triggered": True, + "remediation_hook_id": str(hook.id), + "remediation_job_id": job.job_id + }, + "next_node": "suggestion" + } + except Exception as e: + logger.error(f"Failed to queue remediation job: {str(e)}") + return { + "errors": [f"Remediation queuing failed: {str(e)}"], + "processed_steps": [{"name": "REMEDIATION", "status": "error", "timestamp": datetime.utcnow().isoformat()}], + "next_node": "routing" + } + + +def should_continue_remediation(state: AgentState) -> str: + """ + Router to determine if the workflow should proceed to routing or skip to suggestion. + """ + next_node = state.get("next_node", "routing") + logger.info(f"Remediation router directing to: {next_node}") + return next_node diff --git a/agents/routing.py b/agents/routing.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbdd095db5265cc845844b2688903321c8f8cfb --- /dev/null +++ b/agents/routing.py @@ -0,0 +1,110 @@ +from typing import Any, Dict, List, Optional +from uuid import UUID +from datetime import datetime +from langchain_core.runnables import RunnableConfig +from agents.state import AgentState +from agents.utils import get_available_agents +from sqlalchemy import select, func +from models.ticket import Ticket, TicketStatus +from models.user import User, UserRole + +from core.logging import get_logger + +logger = get_logger(__name__) + +async def routing_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: + """ + Node that assigns the ticket to an agent based on workload (Load Balancing). + """ + db = config["configurable"].get("db") + if not db: + logger.error(f"Routing node missing DB session for ticket {state.get('ticket_id')}") + return {"errors": ["No database session provided for routing"], "next_node": "END"} + + workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] + category = state.get("category", "General") + priority = state.get("priority", "P2") + + logger.debug(f"Routing node calculating workload for workspace {workspace_id}") + # 1. Fetch all SC agents in the workspace + agents = await get_available_agents(db, workspace_id) + # ... + + if not agents: + logger.warning(f"Routing fallback: No active agents found. Searching for Manager/Lead...") + # Fallback to ANY Lead or Admin in the workspace + stmt = select(User).where( + User.workspace_id == workspace_id, + User.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]), + User.deleted_at.is_(None) + ).limit(1) + res = await db.execute(stmt) + manager = res.scalar_one_or_none() + + if manager: + logger.info(f"Routing fallback success: Assigned to Manager {manager.id}") + return { + "assigned_to": manager.id, + "status": TicketStatus.ACKNOWLEDGED, + "processed_steps": [{"name": "ROUTING", "status": "fallback", "timestamp": datetime.utcnow().isoformat()}], + "metadata": { + "routing_fallback_assigned": True, + "routing_assigned_to": str(manager.id), + "routing_reason": "No active agents found, assigned to Workspace Manager." + } + } + + return { + "processed_steps": [{"name": "ROUTING", "status": "error", "timestamp": datetime.utcnow().isoformat()}], + "metadata": { + "routing_error": "Critical: No agents or managers found in workspace", + "routing_success": False + } + } + + # 2. Load Balancing: Count open tickets per agent + agent_ids = [a.id for a in agents] + stmt = ( + select(Ticket.assigned_to, func.count(Ticket.id)) + .where( + Ticket.assigned_to.in_(agent_ids), + Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), + Ticket.deleted_at.is_(None) + ) + .group_by(Ticket.assigned_to) + ) + result = await db.execute(stmt) + workloads = {row[0]: row[1] for row in result.all()} + + # Fill in zeros for agents with no tickets + for aid in agent_ids: + if aid not in workloads: + workloads[aid] = 0 + + # 3. Decision Logic: + # - If priority is P0/P1, prefer a Lead if available + # - Otherwise, pick the agent with the minimum workload + + leads = [a for a in agents if a.role in [UserRole.SC_LEAD, UserRole.SC_ADMIN]] + + target_agent = None + if priority in ["P0", "P1"] and leads: + # Pick least busy lead + target_agent = min(leads, key=lambda a: workloads.get(a.id, 0)) + reason = f"High priority ({priority}) assigned to least busy Lead" + else: + # Pick least busy agent + target_agent = min(agents, key=lambda a: workloads.get(a.id, 0)) + reason = "Assigned to least busy available agent" + + return { + "assigned_to": target_agent.id, + "status": TicketStatus.ACKNOWLEDGED, + "processed_steps": [{"name": "ROUTING", "status": "success", "timestamp": datetime.utcnow().isoformat()}], + "metadata": { + "routing_assigned_to": str(target_agent.id), + "routing_success": True, + "routing_reason": reason, + "routing_workload": workloads.get(target_agent.id, 0) + } + } diff --git a/agents/safety.py b/agents/safety.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a5468ce18850329dd76f2e37d782a8f0477f54 --- /dev/null +++ b/agents/safety.py @@ -0,0 +1,97 @@ +import re +import logging +from typing import List + +logger = logging.getLogger(__name__) + +# --- PII MASKING CONFIG --- + +# Emails: Matches standard user@domain.com +EMAIL_PATTERN = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+' +# Phone Numbers: Basic international and US patterns +PHONE_PATTERN = r'(\+\d{1,3}[- ]?)?\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}' +# UUIDs: Masking internal system IDs +UUID_PATTERN = r'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}' + +# --- PROMPT INJECTION CONFIG --- +INJECTION_KEYWORDS = [ + "ignore previous instructions", + "ignore all instructions", + "system prompt", + "you are now", + "dan mode", + "developer mode", + "jailbreak" +] + +def mask_pii(text: str) -> str: + """ + Recursively masks personal information using high-confidence regex. + """ + if not text: + return text + + # 1. Mask Emails: u***@d***.com + def email_repl(match): + email = match.group(0) + parts = email.split('@') + if len(parts) == 2: + return f"{parts[0][0]}***@{parts[1][0]}***.{parts[1].split('.')[-1]}" + return "***@***.***" + + text = re.sub(EMAIL_PATTERN, email_repl, text) + + # 2. Mask Phone Numbers: (***) ***-**** + text = re.sub(PHONE_PATTERN, r"(***) ***-****", text) + + # 3. Mask UUIDs: ********-****-****-****-************ + # We only mask UUIDs if they look like standalone system IDs, not if they are part of a URL + # text = re.sub(UUID_PATTERN, "********-****-****-****-************", text) + + return text + +def is_malicious_query(query: str) -> bool: + """ + Detects potential prompt injection or query manipulation. + """ + if not query: + return False + + normalized_query = query.lower() + for kw in INJECTION_KEYWORDS: + if kw in normalized_query: + logger.warning(f"Nexus Safety: Potential prompt injection detected: '{kw}'") + return True + + # Check for excessive length + if len(query) > 5000: + logger.warning("Nexus Safety: Query length exceeds safety limits.") + return True + + return False + +def sanitize_output(text: str, is_agent: bool) -> str: + """ + Final sanitization layer before returning response to client. + """ + if not text: + return "" + + # Always mask PII for everyone + text = mask_pii(text) + + # If customer, potentially more aggressive masking could go here + # Character Guardrail: Block general trivia pivots (e.g., 'Ringelmann Effect', 'Did you know...') + trivia_patterns = [ + r"(?i)interestingly,", + r"(?i)did you know", + r"(?i)fun fact", + r"(?i)Ringelmann Effect", + r"(?i)fact about.*in general" + ] + for pattern in trivia_patterns: + if re.search(pattern, text): + # If trivia detected with no underlying data + return "I apologize, but I do not have enough specific workspace data to provide a detailed insight on this topic. Please provide a ticket ID or workspace reference." + + return text diff --git a/agents/state.py b/agents/state.py new file mode 100644 index 0000000000000000000000000000000000000000..98b5138e1f5024775bed56ec82393f7029f2e2dd --- /dev/null +++ b/agents/state.py @@ -0,0 +1,44 @@ +from typing import TypedDict, List, Optional, Any, Dict, Annotated +from uuid import UUID + +def merge_list(current: List[Any], new: List[Any]) -> List[Any]: + return (current or []) + (new or []) + +def merge_dict(current: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]: + _c = current.copy() if current else {} + if new: + _c.update(new) + return _c + +class AgentState(TypedDict): + """ + Shared state for the Customer Portal Agentic Workflow. + """ + # Source Info + ticket_id: UUID + workspace_id: UUID + thread_id: Optional[UUID] + title: str + description: str + attachments: Optional[List[Any]] # Serialized attachment data (id, filename, ai_caption) + + # Processed Results + category: Optional[str] + priority: Optional[str] + sentiment: Optional[str] + + # Duplication Info + is_duplicate: bool + duplicate_of_id: Optional[UUID] + + # Generated Outputs + assigned_to: Optional[UUID] + status: Optional[str] + suggested_reply: Optional[str] + internal_summary: Optional[str] + + # Flow Control + next_node: Optional[str] + errors: Annotated[List[str], merge_list] + metadata: Annotated[Dict[str, Any], merge_dict] + processed_steps: Annotated[List[Dict[str, Any]], merge_list] diff --git a/agents/suggestion.py b/agents/suggestion.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce14acdb7393b5256ba40ad5d3aad8fc64b1008 --- /dev/null +++ b/agents/suggestion.py @@ -0,0 +1,118 @@ +from typing import Any, Dict, List, Optional +from datetime import datetime +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.runnables import RunnableConfig +from langchain_core.output_parsers import StrOutputParser # Added import for StrOutputParser +from uuid import UUID # Added import for UUID + +from core.llm import get_llm, get_text_embeddings +from agents.state import AgentState +from agents.utils import hybrid_search_kb_internal, semantic_search_past_tickets +from core.logging import get_logger +from models.attachment import Attachment +from sqlalchemy import select, func + +SUGGESTION_PROMPT = """ +You are an expert customer support assistant. Your goal is to draft a helpful, professional reply to a customer ticket. + +Ticket Title: {title} +Ticket Description: {description} + +{context} + +Based on the above context, draft a response to the customer. +- If the context doesn't provide enough information, ask clarifying questions or state that an agent will look into it. +- Keep the tone professional and empathetic. +""" + +logger = get_logger(__name__) + +async def suggestion_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: + """ + Node that searches KB and past resolutions to draft a suggested reply. + """ + db = config["configurable"].get("db") + if not db: + logger.error(f"Suggestion node missing DB session for ticket {state.get('ticket_id')}") + return {"errors": ["No database session provided for suggestion"], "next_node": "END"} + + workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] + + try: + # Generate query embedding for search (Nomic-768 by default) + logger.debug(f"Suggestion node embedding query for ticket {state['ticket_id']}") + query_text = f"{state['title']} {state['description']}" + query_vector = await get_text_embeddings().aembed_query(query_text) + + # 1. Hybrid KB Search + Semantic Past Tickets Search + logger.debug(f"Suggestion node searching KB and past tickets for ticket {state['ticket_id']}") + kb_hits = await hybrid_search_kb_internal(db, workspace_id, query_text, query_vector, threshold=0.4, limit=3) + past_tickets = await semantic_search_past_tickets(db, workspace_id, query_vector, limit=2) + + # 1.5. Multimodal Context: Search attachment captions + att_stmt = ( + select(Attachment) + .where( + Attachment.workspace_id == workspace_id, + Attachment.ai_caption.isnot(None), + # Using simple LIKE for robustness without full text search index on captions yet + (Attachment.ai_caption.contains(state['title']) | Attachment.ai_caption.contains("error")) + ) + .limit(3) + ) + matched_atts = (await db.execute(att_stmt)).scalars().all() + + # 2. Format Context + logger.debug(f"Suggestion node formatting context for ticket {state['ticket_id']}") + context = "" + if kb_hits: + context += "Context from Knowledge Base:\n" + # Format using article title and content (which might be a chunk now if we wanted, + # but for the prompt, we'll use the article as the hit unit). + context += "\n".join([f"- {h['article'].title} (Score: {h['score']:.2f}): {h['article'].content}" for h in kb_hits]) + else: + context += "No relevant KB articles found.\n" + + if past_tickets: + context += "\nSimilar Past Resolutions:\n" + context += "\n".join([f"- Past Ticket: {t.title}\n Resolution: {t.description}" for t in past_tickets]) + + if matched_atts: + context += "\nRelevant Visual Context (from KB/Ticket images):\n" + context += "\n".join([f"- Image '{a.filename}': {a.ai_caption}" for a in matched_atts]) + else: + context += "\nNo similar past resolutions or visual context found." + + # 3. Generate Draft via LLM + prompt = ChatPromptTemplate.from_template(SUGGESTION_PROMPT) + chain = prompt | get_llm() | StrOutputParser() + + logger.info(f"Suggestion node generating reply via LLM for ticket {state['ticket_id']}") + suggestion = await chain.ainvoke({ + "title": state["title"], + "description": state["description"], + "context": context + }) + + return { + "suggested_reply": suggestion, + "processed_steps": [{"name": "SUGGESTION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], + "metadata": { + "suggestion_sources": { + "kb_count": len(kb_hits), + "past_tickets_count": len(past_tickets), + "kb_articles": [ + {"id": str(h['article'].id), "title": h['article'].title} + for h in kb_hits + ] + }, + "suggestion_success": True + } + } + except Exception as e: + logger.error(f"Suggestion node failed for ticket {state['ticket_id']}: {str(e)}") + return { + "errors": [f"Suggestion failed: {str(e)}"], + "processed_steps": [{"name": "SUGGESTION", "status": "error", "timestamp": datetime.utcnow().isoformat()}], + "metadata": {"suggestion_success": False} + } diff --git a/agents/summarizer.py b/agents/summarizer.py new file mode 100644 index 0000000000000000000000000000000000000000..bc706f68c7de6a375663f3db26d7f3b6119686bb --- /dev/null +++ b/agents/summarizer.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.runnables import RunnableConfig +from core.llm import get_llm + +SUMMARIZER_PROMPT = """ +Summarize the following support ticket thread into a concise overview. +Include: +1. The main problem or request. +2. Key actions taken so far. +3. Current status or pending items. + +Ticket Title: {title} +Original Description: {description} + +Thread Messages: +{messages} + +Summary: +""" + +async def summarize_thread(title: str, description: str, messages: List[Dict[str, Any]]) -> str: + """ + Stand-alone utility to summarize a ticket thread. + """ + llm = get_llm() + + # Format messages for prompt + formatted_messages = "\n".join([ + f"- {m.get('sender_name', 'User')}: {m.get('content')}" + for m in messages + ]) + + prompt = ChatPromptTemplate.from_template(SUMMARIZER_PROMPT) + chain = prompt | llm + + response = await chain.ainvoke({ + "title": title, + "description": description, + "messages": formatted_messages or "No messages yet." + }) + + return response.content diff --git a/agents/tools/nexus_tools.py b/agents/tools/nexus_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..ec60c3a83a2c989ebd831a0f7f8f65d58cc90db6 --- /dev/null +++ b/agents/tools/nexus_tools.py @@ -0,0 +1,434 @@ +from typing import Any, Dict, List, Optional +from uuid import UUID +from datetime import datetime +import json +from sqlalchemy import select, func, and_, cast, String +from core.database import async_session_factory +from models.ticket import Ticket, TicketStatus, TicketPriority +from models.kb_article import KBArticle +from models.kb_article_chunk import KBArticleChunk +from models.escalation_rule import EscalationRule +from core.llm import get_text_embeddings +from core.logging import get_logger +from agents.utils import safe_uuid + +logger = get_logger(__name__) + +# --- SECURED READ-ONLY TOOLS --- + +async def kb_search_tool(query: str, workspace_id: UUID) -> str: + """ + Search the Knowledge Base for relevant articles and technical solutions. + """ + async with async_session_factory() as db: + embedder = get_text_embeddings() + query_vector = await embedder.aembed_query(query) + + from models.user import User, UserRole + + # Semantic search on chunks + stmt = ( + select(KBArticleChunk, KBArticle.title, KBArticle.id) + .join(KBArticle, KBArticle.id == KBArticleChunk.article_id) + .where( + KBArticle.workspace_id == workspace_id, + KBArticle.is_published == True, + KBArticle.deleted_at.is_(None) + ) + .order_by(KBArticleChunk.embedding.cosine_distance(query_vector)) + .limit(5) + ) + + result = await db.execute(stmt) + chunks = result.all() + + if not chunks: + return "No relevant Knowledge Base articles found." + + formatted_res = [] + for chunk, title, article_id in chunks: + formatted_res.append(f"### Article: {title} (ID: {article_id})\n{chunk.content}\n") + + return "\n".join(formatted_res) + +async def ticket_query_tool(workspace_id: UUID, ticket_id: Optional[UUID] = None, status_filter: Optional[str] = None, role: str = "customer_user") -> str: + """ + Retrieve ticket status, AI summaries, and recent activity. + Strictly masks internal staff notes for customer roles. + """ + async with async_session_factory() as db: + from models.user import User, UserRole + is_staff = "3sc" in role.lower() + + stmt = select(Ticket).where( + Ticket.workspace_id == workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + stmt = stmt.join(Creator, Ticket.created_by == Creator.id).where( + Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) + ) + + if ticket_id: + t_id = safe_uuid(ticket_id) + if not t_id: + return "Invalid Ticket ID format." + stmt = stmt.where(Ticket.id == t_id) + elif status_filter: + # Smart Mapper for friendly terms + status_map = { + "open": [TicketStatus.OPEN], + "acknowledged": [TicketStatus.ACKNOWLEDGED], + "pending": [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED], + "active": [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS], + "in_progress": [TicketStatus.IN_PROGRESS], + "resolved": [TicketStatus.RESOLVED], + "closed": [TicketStatus.CLOSED], + "done": [TicketStatus.RESOLVED, TicketStatus.CLOSED], + "open/pending": [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED] + } + + # Normalize and lookup + normalized = str(status_filter).lower().strip() + target_statuses = status_map.get(normalized, [TicketStatus.OPEN]) # Default to open if unknown + + stmt = stmt.where(Ticket.status.in_(target_statuses)) + else: + stmt = stmt.limit(20) # Default list + + result = await db.execute(stmt) + tickets = result.scalars().all() + + if not tickets: + return "No tickets found matching the criteria." + + is_staff = any(s in role.lower() for s in ["3sc", "agent", "lead", "admin"]) + # Standardize: 3sc_agent, 3sc_lead, 3sc_admin are staff. customer_admin, customer_user are NOT. + is_staff = "3sc" in role.lower() + + res = [] + for t in tickets: + meta = t.ai_metadata or {} + summaries = meta.get("summaries", {}) + + # STAFF BUBBLE PROTECTION + if is_staff: + summary = summaries.get("internal_summary") or summaries.get("customer_summary") or "No summary available." + else: + summary = summaries.get("customer_summary") or "Status active. Detailed internal notes are restricted." + + res.append( + f"TICKET [{t.id}]\nTitle: {t.title}\nStatus: {t.status}\nPriority: {t.priority}\n" + f"Summary: {summary}\n" + f"Created: {t.created_at.isoformat()}\n---" + ) + return "\n".join(res) + +async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user") -> str: + """ + Fetch workspace metrics: Volume Trends, SLA compliance, and Category Heatmaps. + Returns structured data for the agent to generate visualizations. + """ + async with async_session_factory() as db: + from models.user import User, UserRole + is_staff = "3sc" in role.lower() + + # 1. Status Distribution + status_stmt = ( + select(Ticket.status, func.count(Ticket.id)) + .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)) + ) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + status_stmt = status_stmt.join(Creator, Ticket.created_by == Creator.id).where( + Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) + ) + + status_stmt = status_stmt.group_by(Ticket.status) + + # 2. Priority Distribution + prio_stmt = ( + select(Ticket.priority, func.count(Ticket.id)) + .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)) + ) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + prio_stmt = prio_stmt.join(Creator, Ticket.created_by == Creator.id).where( + Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) + ) + + prio_stmt = prio_stmt.group_by(Ticket.priority) + + # 3. Category Distribution + cat_stmt = ( + select(Ticket.category, func.count(Ticket.id)) + .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)) + ) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + cat_stmt = cat_stmt.join(Creator, Ticket.created_by == Creator.id).where( + Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) + ) + + cat_stmt = cat_stmt.group_by(Ticket.category).order_by(func.count(Ticket.id).desc()).limit(10) + + # 4. Daily Volume Trends (Last 7 Days) + from datetime import timedelta + seven_days_ago = datetime.now() - timedelta(days=7) + day_expr = cast(func.date(Ticket.created_at), String) + trend_stmt = ( + select(day_expr, func.count(Ticket.id)) + .where( + Ticket.workspace_id == workspace_id, + Ticket.deleted_at.is_(None), + Ticket.created_at >= seven_days_ago + ) + ) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + trend_stmt = trend_stmt.join(Creator, Ticket.created_by == Creator.id).where( + Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) + ) + + trend_stmt = trend_stmt.group_by(day_expr).order_by(day_expr) + + # 5. SLA Compliance + from api.v1.reports import get_sla_compliance + class MockUser: + def __init__(self, ws_id): + self.workspace_id = ws_id + self.role = UserRole.SC_ADMIN # Ensure MockUser has necessary role for analytics + + # FIX: Correct argument order (workspace_id, current_user, db) + mock_user = MockUser(workspace_id) + sla_data = await get_sla_compliance(str(workspace_id), mock_user, db) + + status_res = await db.execute(status_stmt) + prio_res = await db.execute(prio_stmt) + cat_res = await db.execute(cat_stmt) + trend_res = await db.execute(trend_stmt) + + stats = { + "status_dist": {row[0]: row[1] for row in status_res.all()}, + "prio_dist": {row[0]: row[1] for row in prio_res.all()}, + "category_dist": {row[0] or "Uncategorized": row[1] for row in cat_res.all()}, + "daily_volume": {row[0].split('T')[0]: row[1] for row in trend_res.all()}, + "sla": sla_data + } + + return json.dumps(stats, indent=2) + +async def similar_incident_finder(query: str, workspace_id: UUID, role: str = "customer_user") -> str: + """ + Find top 3 similar resolved tickets. Masks internal staff notes for customer roles. + """ + async with async_session_factory() as db: + from models.user import User, UserRole + embedder = get_text_embeddings() + query_vector = await embedder.aembed_query(query) + + is_staff = "3sc" in role.lower() + stmt = ( + select(Ticket) + .where( + Ticket.workspace_id == workspace_id, + Ticket.status.in_([TicketStatus.RESOLVED, TicketStatus.CLOSED]), + Ticket.deleted_at.is_(None) + ) + ) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + stmt = stmt.join(Creator, Ticket.created_by == Creator.id).where( + Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) + ) + + stmt = stmt.order_by(Ticket.embedding.cosine_distance(query_vector)).limit(3) + + result = await db.execute(stmt) + tickets = result.scalars().all() + + if not tickets: + return "No similar resolved tickets found." + + is_staff = "3sc" in role.lower() + res = [] + for t in tickets: + meta = t.ai_metadata or {} + summaries = meta.get("summaries", {}) + if is_staff: + summ = summaries.get("internal_summary") or summaries.get("customer_summary") or "No summary." + else: + summ = summaries.get("customer_summary") or "Resolution complete. Internal notes restricted." + + res.append(f"PAST INCIDENT [{t.id}]\nTitle: {t.title}\nResolution: {summ}\n---") + + return "\n".join(res) + +async def project_pulse_tool(project_name: str, workspace_id: UUID) -> str: + """ + A birds-eye view of a specific project's health and ticket distribution. + """ + async with async_session_factory() as db: + from models.project import Project + + # 1. Resolve Project + p_stmt = select(Project).where( + Project.workspace_id == workspace_id, + Project.name.ilike(f"%{project_name}%"), + Project.deleted_at.is_(None) + ) + p_res = await db.execute(p_stmt) + project = p_res.scalar_one_or_none() + + if not project: + return f"Project '{project_name}' not found." + + # 2. Get Distribution + stmt = ( + select(Ticket.status, func.count(Ticket.id)) + .where(Ticket.project_id == project.id, Ticket.deleted_at.is_(None)) + .group_by(Ticket.status) + ) + res = await db.execute(stmt) + dist = {row[0]: row[1] for row in res.all()} + + return json.dumps({"project": project.name, "distribution": dist}, indent=2) + +async def sentiment_pulse_tool(ticket_id: UUID, workspace_id: UUID) -> str: + """ + Retrieve message history for sentiment and pulse analysis. + """ + async with async_session_factory() as db: + from models.message import Message + t_id = safe_uuid(ticket_id) + if not t_id: return "Invalid Ticket ID." + + stmt = ( + select(Message.content, Message.sender_id, Message.created_at) + .where( + Message.ticket_id == t_id, + Message.workspace_id == workspace_id, + Message.is_internal == False, # Only customer-distinguishable messages for sentiment + Message.deleted_at.is_(None) + ) + .order_by(Message.created_at.desc()) + .limit(10) + ) + res = await db.execute(stmt) + messages = res.all() + + if not messages: + return "No recent messages found for sentiment analysis." + + return "\n".join([f"{row[2]} (User {row[1]}): {row[0]}" for row in messages]) + +async def knowledge_drafting_tool(ticket_id: UUID, workspace_id: UUID) -> str: + """ + Extract problem and resolution data to draft a KB article. + """ + async with async_session_factory() as db: + t_id = safe_uuid(ticket_id) + if not t_id: return "Invalid Ticket ID." + + stmt = select(Ticket).where( + Ticket.id == t_id, + Ticket.workspace_id == workspace_id, + Ticket.deleted_at.is_(None) + ) + res = await db.execute(stmt) + t = res.scalar_one_or_none() + + if not t: return "Ticket not found." + + meta = t.ai_metadata or {} + return json.dumps({ + "problem": t.description, + "category": t.category, + "resolution": meta.get("summaries", {}).get("internal_summary") or "Pending resolution." + }) + +async def assign_ticket_tool(ticket_id: UUID, user_id: UUID, workspace_id: UUID) -> str: + """ + Assign a ticket to a specific agent. + """ + async with async_session_factory() as db: + t_id = safe_uuid(ticket_id) + u_id = safe_uuid(user_id) + if not t_id or not u_id: return "Invalid Ticket or User ID." + + stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id) + res = await db.execute(stmt) + t = res.scalar_one_or_none() + + if not t: return "Ticket not found or access denied." + + t.assigned_to = user_id + await db.commit() + return f"Ticket {ticket_id} successfully assigned to user {user_id}." + +async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID) -> str: + """ + Update a ticket's status (e.g. to RESOLVED). + """ + async with async_session_factory() as db: + t_id = safe_uuid(ticket_id) + if not t_id: return "Invalid Ticket ID." + + stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id) + res = await db.execute(stmt) + t = res.scalar_one_or_none() + + if not t: return "Ticket not found or access denied." + + try: + t.status = TicketStatus(new_status) + if t.status == TicketStatus.RESOLVED: + from datetime import datetime + t.resolved_at = datetime.now() + await db.commit() + return f"Ticket {ticket_id} status updated to {new_status}." + except ValueError: + return f"Invalid status: {new_status}. Valid statuses: {[s.value for s in TicketStatus]}" +async def dynamic_remediation_tool(action_type: str, parameters: Dict[str, Any], workspace_id: UUID) -> str: + """ + Intelligent remediation engine. Executes specific system actions with dynamic parameters. + Actions: RESET_VPN, RESTART_SERVICE, FLUSH_CACHE, PROVISION_AWS_TEMP + """ + # In a real system, this would call actual infrastructure APIs + # Here we simulate the logic and log the attempt + action = action_type.upper() + params_str = ", ".join([f"{k}={v}" for k, v in parameters.items()]) + + logger.info(f"Remediation: Triggering {action} with [{params_str}] for workspace {workspace_id}") + + # Simulate a delay for infrastructure action + await asyncio.sleep(0.5) + + if action == "RESET_VPN": + email = parameters.get("user_email") or parameters.get("email") + if not email: return "ERROR: user_email parameter missing for RESET_VPN." + return f"SUCCESS: VPN reset successfully for {email}. Password temporary link sent." + + elif action == "RESTART_SERVICE": + svc = parameters.get("service_name") or parameters.get("service_id") + if not svc: return "ERROR: service_name missing for RESTART_SERVICE." + return f"SUCCESS: Service '{svc}' has been restarted and is now healthy (200 OK)." + + elif action == "FLUSH_CACHE": + region = parameters.get("region", "GLOBAL") + return f"SUCCESS: CDN/Cache flush completed for region: {region}." + + return f"REMEDIATION_TRIGGERED: Action '{action}' initiated with [{params_str}]. Please monitor infrastructure." diff --git a/agents/triage.py b/agents/triage.py new file mode 100644 index 0000000000000000000000000000000000000000..816ec34c2421b865ff0f37be383ab22a739d08bd --- /dev/null +++ b/agents/triage.py @@ -0,0 +1,102 @@ +from typing import Any, Dict, List, Optional +from datetime import datetime +from pydantic import BaseModel, Field +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.runnables import RunnableConfig + +from core.llm import get_llm +from core.vision import resolve_image +from models.attachment import Attachment +from agents.state import AgentState +from models.ticket import TicketPriority +from core.logging import get_logger + +logger = get_logger(__name__) + +class TriageResult(BaseModel): + """Structured output for ticket triage.""" + category: str = Field(description="The category of the ticket (e.g., technical, billing, feature_request, general)") + priority: TicketPriority = Field(description="Priority level based on urgency and impact") + sentiment: str = Field(description="User sentiment (e.g., frustrated, neutral, positive)") + estimated_effort_hours: float = Field(description="Estimated technical effort in hours to resolve this ticket (e.g., 0.5, 2, 8, 40)") + complexity: str = Field(description="Complexity level: 'low', 'medium', or 'high'") + reasoning: str = Field(description="Short explanation for the classification and estimation") + +from langchain_core.output_parsers import PydanticOutputParser + +TRIAGE_PROMPT = """ +You are an expert customer support triage agent. Your job is to analyze incoming support tickets and categorize them with high-fidelity effort estimation. + +Ticket Title: {title} +Ticket Description: {description} +Visual Context: {image_captions} + +Analyze the content and provide: +1. Category and Priority. +2. Sentiment of the customer. +3. Estimated effort (IN HOURS) required for a human to resolve this issue. Use the following BENCHMARKING RUBRIC to calibrate your score: + - LOW COMPLEXITY (0.5 - 1.0h): Password resets, status checks, general queries, simple configuration. + - MEDIUM COMPLEXITY (2.0 - 4.0h): Standard bug reports, troubleshooting, Reproducible issues, minor feature tweaks. + - HIGH COMPLEXITY (8.0 - 40.0h): System-wide feature requests, data migrations, infrastructure setup, complex integration failures. +4. Complexity level (low, medium, high). + +Provide the output in the specified JSON format. Ensure the 'estimated_effort_hours' is a float that strictly follows the rubric above. + +{format_instructions} +""" + +from core.logging import get_logger + +logger = get_logger(__name__) + +async def triage_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: + """ + Node that classifies the ticket and determines sentiment/priority. + """ + llm = get_llm() + parser = PydanticOutputParser(pydantic_object=TriageResult) + + prompt = ChatPromptTemplate.from_messages([ + ("system", TRIAGE_PROMPT) + ]) + + chain = prompt | llm | parser + + # 1. Format context from state + image_captions = [] + for attachment in state.get("attachments", []): + if attachment.ai_caption: + image_captions.append(attachment.ai_caption) + + # 2. Define Extraction Chain + + try: + logger.debug(f"Triage node starting ainvoke for ticket {state['ticket_id']}") + result = await chain.ainvoke({ + "title": state["title"], + "description": state["description"], + "image_captions": "\n".join(image_captions) if image_captions else "No visual evidence provided.", + "format_instructions": parser.get_format_instructions() + }) + logger.debug(f"Triage node completed for ticket {state['ticket_id']}") + logger.info(f"TRIAGE: Agent categorized ticket as '{result.category}' with priority '{result.priority}' (Effort: {result.estimated_effort_hours}h)") + + return { + "category": result.category, + "priority": result.priority, + "sentiment": result.sentiment, + "processed_steps": [{"name": "TRIAGE", "status": "success", "timestamp": datetime.utcnow().isoformat()}], + "metadata": { + "triage_reasoning": result.reasoning, + "estimated_effort_hours": result.estimated_effort_hours, + "complexity": result.complexity, + "triage_success": True + } + } + except Exception as e: + logger.error(f"Triage node failed for ticket {state['ticket_id']}: {str(e)}") + return { + "errors": [f"Triage failed: {str(e)}"], + "processed_steps": [{"name": "TRIAGE", "status": "error", "timestamp": datetime.utcnow().isoformat()}], + "metadata": {"triage_success": False} + } diff --git a/agents/utils.py b/agents/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..be1b74929cd0dd970200e0ee26cd604162e79a2b --- /dev/null +++ b/agents/utils.py @@ -0,0 +1,213 @@ +from typing import Any, Dict, List, Optional +from uuid import UUID +from datetime import datetime +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, func, desc +from core.logging import get_logger +from models.user import User, UserRole +from models.kb_article import KBArticle +from models.kb_article_chunk import KBArticleChunk + +logger = get_logger(__name__) + +async def get_available_agents(db: AsyncSession, workspace_id: UUID) -> List[User]: + """ + Fetch all active agents in the given workspace. + """ + stmt = select(User).where( + User.workspace_id == workspace_id, + User.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), + User.is_active == True, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + agents = list(result.scalars().all()) + logger.debug(f"Fetched {len(agents)} available agents for workspace {workspace_id}") + return agents + +async def update_ticket_ai_metadata(db: AsyncSession, ticket_id: UUID, metadata: Dict[str, Any]): + """ + Utility to update ticket AI metadata in the DB. + """ + from models.ticket import Ticket + stmt = select(Ticket).where(Ticket.id == ticket_id) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + if ticket: + # Merge new metadata + existing = ticket.ai_metadata or {} + existing.update(metadata) + ticket.ai_metadata = existing + db.add(ticket) + +async def semantic_search_kb(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]: + """ + Search KBArticles by embedding. + """ + from models.kb_article import KBArticle + stmt = select(KBArticle).where( + KBArticle.workspace_id == workspace_id, + KBArticle.deleted_at.is_(None), + KBArticle.duplicate_of_id.is_(None) + ).order_by( + KBArticle.embedding.cosine_distance(query_embedding) + ).limit(limit) + logger.info(f"AI: Semantic search KB for workspace {workspace_id}") + result = await db.execute(stmt) + return list(result.scalars().all()) + +async def semantic_search_past_tickets(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]: + """ + Search resolved Tickets by embedding. + """ + from models.ticket import Ticket, TicketStatus + stmt = select(Ticket).where( + Ticket.workspace_id == workspace_id, + Ticket.status == TicketStatus.RESOLVED, + Ticket.embedding.isnot(None), + Ticket.deleted_at.is_(None) + ).order_by( + Ticket.embedding.cosine_distance(query_embedding) + ).limit(limit) + logger.info(f"AI: Semantic search past tickets for workspace {workspace_id}") + result = await db.execute(stmt) + return list(result.scalars().all()) + +async def hybrid_search_kb_internal( + db: AsyncSession, + workspace_id: UUID, + query_text: str, + query_embedding: List[float], + threshold: float = 0.2, + limit: int = 5 +) -> List[Dict[str, Any]]: + """ + Internal utility for hybrid search (FTS + Vector) to be used by AI nodes. + Returns a list of dictionaries containing the article object and its hybrid score. + """ + # 1. Semantic Chunk Search + semantic_stmt = ( + select( + KBArticle, + (1 - KBArticleChunk.embedding.cosine_distance(query_embedding)).label("sim_score") + ) + .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id) + .where( + KBArticle.workspace_id == workspace_id, + KBArticle.deleted_at.is_(None), + KBArticle.is_published == True, + KBArticle.duplicate_of_id.is_(None) + ) + .order_by(desc("sim_score")) + .limit(20) + ) + semantic_res = await db.execute(semantic_stmt) + + # 2. Keyword FTS Search + fts_stmt = ( + select( + KBArticle, + func.ts_rank( + func.to_tsvector('english', KBArticle.title + " " + KBArticle.content), + func.plainto_tsquery('english', query_text) + ).label("fts_rank") + ) + .where( + KBArticle.workspace_id == workspace_id, + KBArticle.deleted_at.is_(None), + KBArticle.is_published == True, + KBArticle.duplicate_of_id.is_(None), + func.to_tsvector('english', KBArticle.title + " " + KBArticle.content).op("@@")(func.plainto_tsquery('english', query_text)) + ) + .order_by(desc("fts_rank")) + .limit(20) + ) + fts_res = await db.execute(fts_stmt) + + # 3. Score Fusion + article_scores = {} + for article, sim in semantic_res.all(): + if article.id not in article_scores: + article_scores[article.id] = {"obj": article, "semantic": sim, "fts": 0.0} + else: + article_scores[article.id]["semantic"] = max(article_scores[article.id]["semantic"], sim) + + for article, rank in fts_res.all(): + if article.id not in article_scores: + article_scores[article.id] = {"obj": article, "semantic": 0.0, "fts": rank} + else: + article_scores[article.id]["fts"] = rank + + final_results = [] + for art_id, data in article_scores.items(): + score = (data["semantic"] * 0.7) + (min(data["fts"], 1.0) * 0.3) + if score >= threshold: + final_results.append({"article": data["obj"], "score": score}) + + final_results.sort(key=lambda x: x["score"], reverse=True) + return final_results[:limit] + + +async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optional[User]: + """Find the best person to notify in a workspace (Lead first, then Admin).""" + # 1. Try to find a Lead + stmt = select(User).where( + (User.workspace_id == workspace_id), + (User.role == UserRole.SC_LEAD), + (User.is_active == True), + (User.deleted_at.is_(None)) + ).limit(1) + res = await db.execute(stmt) + manager = res.scalar_one_or_none() + if manager: + return manager + + # 2. Fallback to Admin + stmt = select(User).where( + (User.workspace_id == workspace_id), + (User.role == UserRole.SC_ADMIN), + (User.is_active == True), + (User.deleted_at.is_(None)) + ).limit(1) + res = await db.execute(stmt) + return res.scalar_one_or_none() + + +import json +class CustomEncoder(json.JSONEncoder): + """JSON encoder that handles UUID objects by converting them to strings.""" + def default(self, obj): + if isinstance(obj, UUID): + return str(obj) + if isinstance(obj, datetime): + return obj.isoformat() + return super().default(obj) + + +def sanitize_for_db(data: Any) -> Any: + """Recursively converts UUIDs and datetimes to strings for DB storage.""" + if isinstance(data, dict): + return {k: sanitize_for_db(v) for k, v in data.items()} + elif isinstance(data, list): + return [sanitize_for_db(i) for i in data] + elif isinstance(data, UUID): + return str(data) + elif isinstance(data, datetime): + return data.isoformat() + return data + +def safe_uuid(val: Any) -> Optional[UUID]: + """Safely attempts to cast a value to UUID. Returns None on failure.""" + if not val: + return None + if isinstance(val, UUID): + return val + try: + # Check for common short-codes or hex strings that are not UUIDs + s_val = str(val).strip() + if len(s_val) < 32: + return None + return UUID(s_val) + except (ValueError, TypeError, AttributeError): + return None + diff --git a/agents/workflow.py b/agents/workflow.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf7241fd645646ed6723c79689fce8228c6942b --- /dev/null +++ b/agents/workflow.py @@ -0,0 +1,247 @@ +print("!!! AGENTS-WORKFLOW LOADED: [V_734] !!!") +import uuid +import json +import logging +import time +from typing import Dict, Any, List +from datetime import datetime, timedelta + +from langgraph.graph import StateGraph, END +from langgraph.types import RetryPolicy + +from agents.state import AgentState +from agents.triage import triage_node +from agents.duplication import duplication_node +from agents.remediation import remediation_node, should_continue_remediation +from agents.routing import routing_node +from agents.suggestion import suggestion_node +from agents.utils import sanitize_for_db, CustomEncoder, get_workspace_manager +from core.database import async_session_factory +from models.ticket import Ticket, TicketStatus +from models.attachment import Attachment +from sqlalchemy import select + +logger = logging.getLogger(__name__) + +def should_proceed_after_duplication(state: AgentState) -> str: + """Router to exit early if ticket is a duplicate.""" + if state.get("is_duplicate"): + logger.warning(f"Workflow: Exiting early for duplicate ticket {state['ticket_id']}") + return END + return "triage" + +async def run_ai_workflow(ctx: Any, ticket_data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]: + """ + Main entry point to run the agentic workflow for a new ticket. + """ + thread_id = uuid.uuid4() + t_id_raw = ticket_data.get("id") + t_id = uuid.UUID(str(t_id_raw)) if t_id_raw else None + + # Version Tag for Verification + v_tag = f"v_{int(time.time() % 1000)}" + logger.info(f"TASK START [{v_tag}]: Orchestrating AI for ticket {t_id} (Thread: {thread_id})") + + final_state = {} + try: + async with async_session_factory() as db: + # 1. Initialize Graph + workflow = StateGraph(AgentState) + retry_policy = RetryPolicy(max_attempts=3) + + workflow.add_node("duplication", duplication_node, retry=retry_policy) + workflow.add_node("triage", triage_node, retry=retry_policy) + workflow.add_node("remediation", remediation_node, retry=retry_policy) + workflow.add_node("routing", routing_node, retry=retry_policy) + workflow.add_node("suggestion", suggestion_node, retry=retry_policy) + + workflow.set_entry_point("duplication") + workflow.add_conditional_edges( + "duplication", + should_proceed_after_duplication, + {"triage": "triage", END: END} + ) + workflow.add_edge("triage", "remediation") + workflow.add_conditional_edges( + "remediation", + should_continue_remediation, + {"routing": "routing", "suggestion": "suggestion"} + ) + workflow.add_edge("routing", "suggestion") + workflow.add_edge("suggestion", END) + app = workflow.compile() + + # 1.5 Fetch Attachments for state + att_stmt = select(Attachment).where(Attachment.ticket_id == t_id) + att_res = await db.execute(att_stmt) + attachments = att_res.scalars().all() + serialized_atts = [ + {"id": str(a.id), "filename": a.filename, "ai_caption": a.ai_caption} + for a in attachments + ] + + # 2. Initial State + initial_state = AgentState( + ticket_id=t_id, + workspace_id=uuid.UUID(str(ticket_data["workspace_id"])), + thread_id=thread_id, + title=ticket_data["title"], + description=ticket_data.get("description", ""), + attachments=serialized_atts, + is_duplicate=False, + duplicate_of_id=None, + category=None, + priority=None, + sentiment=None, + assigned_to=None, + status=None, + suggested_reply=None, + internal_summary=None, + next_node=None, + errors=[], + metadata={}, + processed_steps=[{"name": "SYSTEM:EMBEDDING", "status": "success", "timestamp": datetime.utcnow().isoformat()}] + ) + + from models.ai_interaction import AIInteraction + from core.config import get_settings + settings = get_settings() + final_state = initial_state.copy() + + # 3. Final Orchestration with Native Reduction + try: + # We use ainvoke to get the PERFECTLY reduced final state + # because manual loops bypass LangGraph's internal reducers. + logger.info(f"STARTING AI WORKFLOW [{v_tag}] for ticket {t_id}") + + # Still use astream for REAL-TIME logging of nodes + # but we'll use ainvoke's final result for the hard persistence. + async for event in app.astream( + initial_state, + config={"configurable": {"db": db}}, + stream_mode="updates" + ): + if not event: continue + for node_name, updates in event.items(): + # Track interactions with the V_734 provenance tag + clean_updates = sanitize_for_db(updates) + clean_updates["debug_v"] = "V_734" # DEFINTIVE PROOF TAG + + # Log nodes as they happen for the Dashboard + interaction = AIInteraction( + workspace_id=initial_state["workspace_id"], + ticket_id=t_id, + agent_name=node_name, + model_info=settings.AI_MODEL, + thread_id=thread_id, + input_data={"v": v_tag, "msg": "Streaming input..."}, + output_data=clean_updates, + status="success", + duration_ms=sanitize_for_db({"total": 0}), # Latency handled by final sync + is_automatic=True, + metadata_json=clean_updates.get("metadata", {}) + ) + db.add(interaction) + await db.commit() + logger.info(f"NODE COMPLETE [{v_tag}]: {node_name}") + + # 4. FINAL REDUCTION: Get the official final state from the graph + # Using ainvoke here ensures we don't have to manual-merge anymore. + final_state = await app.ainvoke(initial_state, config={"configurable": {"db": db}}) + + # --- Observability: Record Triage Result --- + from core.observability import record_workflow_step + await record_workflow_step( + db, + entity_id=t_id, + workspace_id=initial_state["workspace_id"], + workflow_type="LIFECYCLE", + step_name="AI_TRIAGE_COMPLETE", + input_data={"v": v_tag}, + output_data={ + "next_node": final_state.get("next_node"), + "metadata": final_state.get("metadata") + }, + current_stage="ROUTED_FOR_ACTION" + ) + # --- Observability: Record Suggestion --- + if final_state.get("suggested_reply"): + await record_workflow_step( + db, + entity_id=t_id, + workspace_id=initial_state["workspace_id"], + workflow_type="LIFECYCLE", + step_name="AI_SUGGESTION_GENERATED", + output_data={"preview": final_state["suggested_reply"][:100] + "..."}, + current_stage="REPLY_DRAFTED" + ) + + await db.commit() + + logger.info(f"AI WORKFLOW COMPLETE [{v_tag}]: {t_id} -> {final_state.get('next_node')}") + stmt = select(Ticket).where(Ticket.id == t_id) + res = await db.execute(stmt) + ticket = res.scalar_one_or_none() + + if ticket: + logger.info(f"ULTIMATE SYNC [{v_tag}]: Saving reduced state to Ticket {t_id}") + + # Merge metadata and add processed steps + final_meta = final_state.get("metadata", {}) + final_meta.update({ + "worker_version": v_tag, + "sync_type": "ultimate_ainvoke", + "processed_steps": final_state.get("processed_steps", []) + }) + ticket.ai_metadata = final_meta + + # Core Attributes (with Fallbacks) + ticket.category = final_state.get("category") or "general" + ticket.priority = final_state.get("priority") or "P3" + + if final_state.get("assigned_to"): + ticket.assigned_to = uuid.UUID(str(final_state.get("assigned_to"))) + + if final_state.get("is_duplicate"): + ticket.status = TicketStatus.CLOSED + ticket.duplicate_of_id = final_state.get("duplicate_of_id") + ticket.resolved_at = datetime.utcnow() + ticket.resolution_text = f"Automated Workflow: This ticket has been marked as a duplicate of ticket #{str(ticket.duplicate_of_id)[:8]}." + + # Effort & Resolution Date + hours = final_meta.get("estimated_effort_hours") or 1.0 + ticket.estimated_effort_hours = { + "value": float(hours), + "complexity": final_meta.get("complexity") or "low" + } + base_time = ticket.created_at or datetime.utcnow() + ticket.expected_resolution_at = base_time + timedelta(hours=hours) + + db.add(ticket) + await db.commit() + logger.info(f"DONE [{v_tag}]: Ticket {t_id} is fully synchronized via AINVOKE.") + else: + logger.error(f"SYNC ERROR [{v_tag}]: Ticket {t_id} not found.") + + except Exception as e: + logger.exception(f"GRAPH ERROR [{v_tag}]: {str(e)}") + err_interaction = AIInteraction( + workspace_id=initial_state["workspace_id"], + ticket_id=t_id, + agent_name="workflow_engine", + model_info="system", + thread_id=thread_id, + input_data={}, + output_data=sanitize_for_db({"error": str(e)}), + status="error", + is_automatic=True + ) + db.add(err_interaction) + await db.commit() + raise e + + except Exception as e: + logger.error(f"CRITICAL WORKFLOW FAILURE [{v_tag}]: {str(e)}") + raise e + + return final_state diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000000000000000000000000000000000000..7be48446f15fbf15eb55d92b9cbea436ef1659ae --- /dev/null +++ b/alembic.ini @@ -0,0 +1,115 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# Use forward slashes (/) also on windows to provide an os agnostic path +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to alembic/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +# version_path_separator = newline +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000000000000000000000000000000000000..e0d0858f266ec27b243e8b92301fc7002e1f2745 --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000000000000000000000000000000000000..6a10af2aefdf197db6b2ccc70ff64e6acfde0d75 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,111 @@ +import asyncio +import pgvector +from logging.config import fileConfig + +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import async_engine_from_config + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +from core.database import Base +from core.config import get_settings +from models.workspace import Workspace +from models.user import User +from models.ticket import Ticket +from models.message import Message +from models.project import Project +from models.attachment import Attachment +from models.feedback import Feedback +from models.kb_article import KBArticle +from models.kb_article_chunk import KBArticleChunk +from models.notification import Notification +from models.escalation_rule import EscalationRule +from models.remediation import RemediationHook +from models.ai_interaction import AIInteraction +from models.ai_workflow import AIWorkflow +from models.audit_log import AuditLog +from models.nexus_checkpoint import NexusCheckpoint +from models.nexus_interaction import NexusInteraction +from models.remediation import RemediationHook +from models.remediation_audit import RemediationAudit + +target_metadata = Base.metadata +settings = get_settings() + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def do_run_migrations(connection: Connection) -> None: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + connectable = async_engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + # Escape % as %% to prevent ConfigParser interpolation errors + escaped_url = settings.async_database_url.replace("%", "%%") + config.set_main_option("sqlalchemy.url", escaped_url) + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000000000000000000000000000000000000..fbc4b07dcef98b20c6f96b642097f35e8433258e --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/alembic/versions/0001_initial_consolidated.py b/alembic/versions/0001_initial_consolidated.py new file mode 100644 index 0000000000000000000000000000000000000000..e8962586855ab392ce3e12a1c8b11d6c7ab00d0a --- /dev/null +++ b/alembic/versions/0001_initial_consolidated.py @@ -0,0 +1,365 @@ +"""initial_consolidated + +Revision ID: 0001_initial_consolidated +Revises: +Create Date: 2026-03-31 11:00:00.000000 + +""" +from typing import Sequence, Union +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql +import pgvector + +# revision identifiers +revision: str = '0001_initial_consolidated' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + +def upgrade() -> None: + # 1. Enable extensions + op.execute("CREATE EXTENSION IF NOT EXISTS vector") + + # 2. Define Enums with safety checks (Postgres DO blocks) + op.execute(""" + DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'userrole') THEN + CREATE TYPE userrole AS ENUM ('CUSTOMER_ADMIN', 'CUSTOMER_USER', 'SC_AGENT', 'SC_LEAD', 'SC_ADMIN'); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'ticketpriority') THEN + CREATE TYPE ticketpriority AS ENUM ('P0', 'P1', 'P2', 'P3'); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'ticketstatus') THEN + CREATE TYPE ticketstatus AS ENUM ('OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'); + END IF; + END $$; + """) + + # Enum objects with create_type=False to tell SQLAlchemy NOT to attempt creation during create_table + userrole_enum = postgresql.ENUM('CUSTOMER_ADMIN', 'CUSTOMER_USER', 'SC_AGENT', 'SC_LEAD', 'SC_ADMIN', name='userrole', create_type=False) + ticketpriority_enum = postgresql.ENUM('P0', 'P1', 'P2', 'P3', name='ticketpriority', create_type=False) + ticketstatus_enum = postgresql.ENUM('OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED', name='ticketstatus', create_type=False) + + # 3. Tables + op.create_table('workspaces', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('branding', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('deleted_at', sa.DateTime(), nullable=True), + sa.Column('deleted_by_id', sa.UUID(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('users', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('email', sa.String(length=255), nullable=False), + sa.Column('hashed_password', sa.String(length=255), nullable=False), + sa.Column('full_name', sa.String(length=255), nullable=False), + sa.Column('role', userrole_enum, nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False, default=True), + sa.Column('avatar_url', sa.String(length=512), nullable=True), + sa.Column('deleted_at', sa.DateTime(), nullable=True), + sa.Column('deleted_by_id', sa.UUID(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('email') + ) + + op.create_table('projects', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.String(length=50), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('deleted_at', sa.DateTime(), nullable=True), + sa.Column('deleted_by_id', sa.UUID(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('tickets', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('created_by', sa.UUID(), nullable=False), + sa.Column('assigned_to', sa.UUID(), nullable=True), + sa.Column('project_id', sa.UUID(), nullable=True), + sa.Column('title', sa.String(length=500), nullable=False), + sa.Column('description', sa.Text(), nullable=False), + sa.Column('category', sa.String(length=100), nullable=True), + sa.Column('priority', ticketpriority_enum, nullable=False), + sa.Column('status', ticketstatus_enum, nullable=False), + sa.Column('sla_deadline', sa.DateTime(), nullable=True), + sa.Column('estimated_effort_hours', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('expected_resolution_at', sa.DateTime(), nullable=True), + sa.Column('resolved_at', sa.DateTime(), nullable=True), + sa.Column('is_escalated', sa.DateTime(), nullable=True), + sa.Column('duplicate_of_id', sa.UUID(), nullable=True), + sa.Column('resolution_text', sa.Text(), nullable=True), + sa.Column('resolved_by', sa.UUID(), nullable=True), + sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=768), nullable=True), + sa.Column('ai_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('deleted_at', sa.DateTime(), nullable=True), + sa.Column('deleted_by_id', sa.UUID(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['assigned_to'], ['users.id']), + sa.ForeignKeyConstraint(['created_by'], ['users.id']), + sa.ForeignKeyConstraint(['duplicate_of_id'], ['tickets.id']), + sa.ForeignKeyConstraint(['project_id'], ['projects.id']), + sa.ForeignKeyConstraint(['resolved_by'], ['users.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('kb_articles', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('author_id', sa.UUID(), nullable=False), + sa.Column('project_id', sa.UUID(), nullable=True), + sa.Column('title', sa.String(length=500), nullable=False), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('summary', sa.Text(), nullable=True), + sa.Column('category', sa.String(length=100), nullable=True), + sa.Column('is_published', sa.Boolean(), nullable=True, default=True), + sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=768), nullable=True), + sa.Column('views', sa.Integer(), nullable=True, default=0), + sa.Column('tags', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('duplicate_of_id', sa.UUID(), nullable=True), + sa.Column('force_original', sa.Boolean(), nullable=True, default=False), + sa.Column('deleted_at', sa.DateTime(), nullable=True), + sa.Column('deleted_by_id', sa.UUID(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['author_id'], ['users.id']), + sa.ForeignKeyConstraint(['duplicate_of_id'], ['kb_articles.id']), + sa.ForeignKeyConstraint(['project_id'], ['projects.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('kb_article_chunks', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('article_id', sa.UUID(), nullable=False), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('chunk_index', sa.Integer(), nullable=False), + sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=768), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['article_id'], ['kb_articles.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('notifications', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('user_id', sa.UUID(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False), + sa.Column('message', sa.Text(), nullable=False), + sa.Column('is_read', sa.Boolean(), nullable=True, default=False), + sa.Column('deleted_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('messages', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('ticket_id', sa.UUID(), nullable=False), + sa.Column('sender_id', sa.UUID(), nullable=False), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('is_internal', sa.Boolean(), nullable=False, default=False), + sa.Column('mentions', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['sender_id'], ['users.id']), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('attachments', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('ticket_id', sa.UUID(), nullable=True), + sa.Column('article_id', sa.UUID(), nullable=True), + sa.Column('file_name', sa.String(length=500), nullable=False), + sa.Column('file_url', sa.String(length=1024), nullable=False), + sa.Column('source_url', sa.String(length=2048), nullable=True), + sa.Column('content_type', sa.String(length=100), nullable=True), + sa.Column('file_size', sa.String(length=50), nullable=True), + sa.Column('storage_backend', sa.String(length=20), nullable=True), + sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=512), nullable=True), + sa.Column('ai_caption', sa.Text(), nullable=True), + sa.Column('is_processed', sa.Boolean(), nullable=True, default=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['article_id'], ['kb_articles.id']), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('feedbacks', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('ticket_id', sa.UUID(), nullable=False), + sa.Column('csat_score', sa.Integer(), nullable=False), + sa.Column('comment', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint('csat_score >= 1 AND csat_score <= 5', name='csat_score_range'), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('ticket_id') + ) + + op.create_table('audit_logs', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('entity_type', sa.String(length=50), nullable=False), + sa.Column('entity_id', sa.UUID(), nullable=False), + sa.Column('action', sa.String(length=100), nullable=False), + sa.Column('user_id', sa.UUID(), nullable=True), + sa.Column('old_value', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('new_value', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('ai_workflows', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('entity_id', sa.UUID(), nullable=False), + sa.Column('workflow_type', sa.String(length=50), nullable=False), + sa.Column('current_stage', sa.String(length=100), nullable=True), + sa.Column('steps', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('total_duration_ms', sa.Float(), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('ai_interactions', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('ticket_id', sa.UUID(), nullable=True), + sa.Column('agent_name', sa.String(length=100), nullable=False), + sa.Column('model_info', sa.String(length=255), nullable=True), + sa.Column('thread_id', sa.UUID(), nullable=True), + sa.Column('input_data', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('output_data', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('status', sa.String(length=50), nullable=True), + sa.Column('duration_ms', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('usage_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('is_automatic', sa.Boolean(), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('escalation_rules', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('conditions', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('actions', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=True, default=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('remediation_hooks', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('trigger_category', sa.String(length=100), nullable=False), + sa.Column('action_type', sa.String(length=50), nullable=False), + sa.Column('target', sa.String(length=512), nullable=True), + sa.Column('payload_template', sa.JSON(), nullable=True), + sa.Column('description', sa.String(length=255), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('remediation_audits', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('ticket_id', sa.UUID(), nullable=True), + sa.Column('user_id', sa.UUID(), nullable=True), + sa.Column('action_type', sa.String(length=100), nullable=False), + sa.Column('parameters', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('reasoning', sa.Text(), nullable=True), + sa.Column('is_successful', sa.Boolean(), nullable=True), + sa.Column('execution_log', sa.Text(), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + + op.create_table('nexus_checkpoints', + sa.Column('thread_id', sa.String(), nullable=False), + sa.Column('checkpoint_id', sa.String(), nullable=False), + sa.Column('parent_id', sa.String(), nullable=True), + sa.Column('checkpoint_data', sa.LargeBinary(), nullable=False), + sa.Column('metadata_data', sa.LargeBinary(), nullable=True), + sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id') + ) + + op.create_table('nexus_interactions', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('user_id', sa.UUID(), nullable=False), + sa.Column('thread_id', sa.UUID(), nullable=True), + sa.Column('ticket_id', sa.UUID(), nullable=True), + sa.Column('input_query', sa.Text(), nullable=False), + sa.Column('ai_answer', sa.Text(), nullable=False), + sa.Column('tool_trace', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('extracted_params', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('status', sa.String(length=50), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), + sa.PrimaryKeyConstraint('id') + ) + +def downgrade() -> None: + # Cleanup in reverse order + tables = [ + 'nexus_interactions', 'nexus_checkpoints', 'remediation_audits', 'remediation_hooks', + 'escalation_rules', 'ai_interactions', 'ai_workflows', 'audit_logs', 'feedbacks', + 'attachments', 'messages', 'notifications', 'kb_article_chunks', 'kb_articles', + 'tickets', 'projects', 'users', 'workspaces' + ] + for table in tables: + op.drop_table(table) + + # Drop Enums + op.execute("DROP TYPE userrole") + op.execute("DROP TYPE ticketpriority") + op.execute("DROP TYPE ticketstatus") diff --git a/alembic/versions/0002_fix_attachments_schema.py b/alembic/versions/0002_fix_attachments_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..1aaf1afe4963df30f49d9d4156a818eb28d033bc --- /dev/null +++ b/alembic/versions/0002_fix_attachments_schema.py @@ -0,0 +1,54 @@ +"""fix_attachments_schema + +Revision ID: 0002_fix_attachments_schema +Revises: 0001_initial_consolidated +Create Date: 2026-03-31 22:40:00.000000 + +""" +from typing import Sequence, Union +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers +revision: str = '0002_fix_attachments_schema' +down_revision: Union[str, None] = '0001_initial_consolidated' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + +def upgrade() -> None: + # 1. Add workspace_id column (nullable first to avoid constraint issues with data) + op.add_column('attachments', sa.Column('workspace_id', sa.UUID(), nullable=True)) + op.create_foreign_key('fk_attachments_workspace_id', 'attachments', 'workspaces', ['workspace_id'], ['id']) + + # 2. Add uploader_id column + op.add_column('attachments', sa.Column('uploader_id', sa.UUID(), nullable=True)) + op.create_foreign_key('fk_attachments_uploader_id', 'attachments', 'users', ['uploader_id'], ['id']) + + # 3. Rename columns to match current model + op.alter_column('attachments', 'file_name', new_column_name='filename') + op.alter_column('attachments', 'file_url', new_column_name='storage_path') + + # 4. Change file_size from String to Integer (preserving data via casting) + op.execute("ALTER TABLE attachments ALTER COLUMN file_size TYPE INTEGER USING (CASE WHEN file_size ~ E'^\\\\d+$' THEN file_size::INTEGER ELSE NULL END)") + + # 5. Populate workspace_id if table is not empty (Backfill with first workspace if needed) + op.execute(""" + UPDATE attachments + SET workspace_id = (SELECT id FROM workspaces LIMIT 1) + WHERE workspace_id IS NULL AND (SELECT COUNT(*) FROM workspaces) > 0 + """) + +def downgrade() -> None: + # Reverse renames + op.alter_column('attachments', 'filename', new_column_name='file_name') + op.alter_column('attachments', 'storage_path', new_column_name='file_url') + + # Change file_size back to String + op.alter_column('attachments', 'file_size', type_=sa.String(length=50)) + + # Remove columns and FKs + op.drop_constraint('fk_attachments_uploader_id', 'attachments', type_='foreignkey') + op.drop_column('attachments', 'uploader_id') + op.drop_constraint('fk_attachments_workspace_id', 'attachments', type_='foreignkey') + op.drop_column('attachments', 'workspace_id') diff --git a/alembic/versions/0003_final_schema_reconciliation.py b/alembic/versions/0003_final_schema_reconciliation.py new file mode 100644 index 0000000000000000000000000000000000000000..33891e37469d09766fc7b913897e31a9cea46685 --- /dev/null +++ b/alembic/versions/0003_final_schema_reconciliation.py @@ -0,0 +1,85 @@ +"""final_schema_reconciliation + +Revision ID: 0003_final_schema_reconciliation +Revises: 0002_fix_attachments_schema +Create Date: 2026-03-31 23:05:00.000000 + +""" +from typing import Sequence, Union +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '0003_final_schema_reconciliation' +down_revision: Union[str, None] = '0002_fix_attachments_schema' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + +def upgrade() -> None: + # 1. ATTACHMENTS - Fix Soft Delete and Indices (Protected by IF NOT EXISTS) + op.execute("ALTER TABLE attachments ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP WITHOUT TIME ZONE") + op.execute("ALTER TABLE attachments ADD COLUMN IF NOT EXISTS deleted_by_id UUID") + op.execute("CREATE INDEX IF NOT EXISTS ix_attachments_workspace_id ON attachments (workspace_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_attachments_ticket_id ON attachments (ticket_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_attachments_article_id ON attachments (article_id)") + + # 2. MESSAGES - Add missing Workspace ID and Soft Delete + op.execute("ALTER TABLE messages ADD COLUMN IF NOT EXISTS workspace_id UUID") + op.execute("ALTER TABLE messages ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP WITHOUT TIME ZONE") + op.execute("ALTER TABLE messages ADD COLUMN IF NOT EXISTS deleted_by_id UUID") + # Backfill workspace_id for messages + op.execute(""" + UPDATE messages + SET workspace_id = (SELECT workspace_id FROM tickets WHERE tickets.id = messages.ticket_id) + WHERE workspace_id IS NULL AND EXISTS (SELECT 1 FROM tickets WHERE tickets.id = messages.ticket_id) + """) + op.execute("DO $$ BEGIN BEGIN ALTER TABLE messages ALTER COLUMN workspace_id SET NOT NULL; EXCEPTION WHEN OTHERS THEN NULL; END; END $$;") + op.execute("CREATE INDEX IF NOT EXISTS ix_messages_workspace_id ON messages (workspace_id)") + + # 3. FEEDBACKS - Align with modern model + op.execute("ALTER TABLE feedbacks ADD COLUMN IF NOT EXISTS workspace_id UUID") + op.execute("ALTER TABLE feedbacks ADD COLUMN IF NOT EXISTS user_id UUID") + op.execute("ALTER TABLE feedbacks ADD COLUMN IF NOT EXISTS rating INTEGER") + op.execute("DO $$ BEGIN IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'feedbacks' AND column_name = 'csat_score') THEN UPDATE feedbacks SET rating = csat_score WHERE rating IS NULL; ALTER TABLE feedbacks DROP COLUMN csat_score; END IF; END $$;") + op.execute(""" + UPDATE feedbacks + SET workspace_id = (SELECT workspace_id FROM tickets WHERE tickets.id = feedbacks.ticket_id) + WHERE workspace_id IS NULL AND EXISTS (SELECT 1 FROM workspaces) + """) + op.execute("DO $$ BEGIN BEGIN ALTER TABLE feedbacks ALTER COLUMN workspace_id SET NOT NULL; EXCEPTION WHEN OTHERS THEN NULL; END; END $$;") + + # 4. ESCALATION RULES - Repair missing logic + op.execute("ALTER TABLE escalation_rules ADD COLUMN IF NOT EXISTS priority_level VARCHAR(50)") + op.execute("ALTER TABLE escalation_rules ADD COLUMN IF NOT EXISTS threshold_minutes INTEGER") + op.execute("ALTER TABLE escalation_rules ADD COLUMN IF NOT EXISTS action VARCHAR(50)") + + # 5. REMEDIATION AUDITS - New Agentic Table + op.execute(""" + CREATE TABLE IF NOT EXISTS remediation_audits ( + id UUID PRIMARY KEY, + workspace_id UUID NOT NULL REFERENCES workspaces(id), + ticket_id UUID REFERENCES tickets(id), + user_id UUID REFERENCES users(id), + action_type VARCHAR(100) NOT NULL, + parameters JSONB NOT NULL, + reasoning TEXT, + is_successful BOOLEAN DEFAULT TRUE, + execution_log TEXT, + metadata_json JSONB DEFAULT '{}', + created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL + ) + """) + op.execute("CREATE INDEX IF NOT EXISTS ix_remediation_audits_workspace_id ON remediation_audits (workspace_id)") + + # 6. Global Index Hardening + op.execute("CREATE INDEX IF NOT EXISTS ix_kb_article_chunks_article_id ON kb_article_chunks (article_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_kb_articles_workspace_id ON kb_articles (workspace_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_workspace_id ON audit_logs (workspace_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_entity_id ON audit_logs (entity_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_tickets_workspace_id ON tickets (workspace_id)") + op.execute("CREATE INDEX IF NOT EXISTS ix_users_workspace_id ON users (workspace_id)") + +def downgrade() -> None: + pass diff --git a/alembic/versions/4c626672022a_add_meta_infra_health_table.py b/alembic/versions/4c626672022a_add_meta_infra_health_table.py new file mode 100644 index 0000000000000000000000000000000000000000..d25b2b217272243acfc06c687308a089832e39c1 --- /dev/null +++ b/alembic/versions/4c626672022a_add_meta_infra_health_table.py @@ -0,0 +1,44 @@ +"""Add meta_infra_health table + +Revision ID: 4c626672022a +Revises: 0003_final_schema_reconciliation +Create Date: 2026-04-01 01:36:31.807775 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '4c626672022a' +down_revision: Union[str, None] = '0003_final_schema_reconciliation' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('meta_infra_health', + sa.Column('service_name', sa.String(length=50), nullable=False), + sa.Column('status', sa.Enum('UP', 'DOWN', 'DEGRADED', name='servicestatus'), nullable=False), + sa.Column('latency_ms', sa.Float(), nullable=True), + sa.Column('metrics', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('environment', sa.String(length=50), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_meta_infra_health_id'), 'meta_infra_health', ['id'], unique=False) + op.create_index(op.f('ix_meta_infra_health_service_name'), 'meta_infra_health', ['service_name'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_meta_infra_health_service_name'), table_name='meta_infra_health') + op.drop_index(op.f('ix_meta_infra_health_id'), table_name='meta_infra_health') + op.drop_table('meta_infra_health') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/0b3641c15213_add_resolution_fields_to_ticket.py b/alembic/versions/archive/0b3641c15213_add_resolution_fields_to_ticket.py new file mode 100644 index 0000000000000000000000000000000000000000..57d6f4e49cb66c4913f0492ab692347fdf2b654f --- /dev/null +++ b/alembic/versions/archive/0b3641c15213_add_resolution_fields_to_ticket.py @@ -0,0 +1,112 @@ +"""Add resolution fields to Ticket + +Revision ID: 0b3641c15213 +Revises: b2895ed533fc +Create Date: 2026-03-30 01:30:34.190948 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '0b3641c15213' +down_revision: Union[str, None] = 'b2895ed533fc' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + # Safety Check: Only drop if tables exist (crucial for fresh cloud deployments) + from sqlalchemy.engine.reflection import Inspector + bind = op.get_bind() + inspector = Inspector.from_engine(bind) + tables = inspector.get_table_names() + + if 'nexus_checkpoints' in tables: + op.drop_table('nexus_checkpoints') + + if 'nexus_interactions' in tables: + op.drop_index('ix_nexus_interactions_id', table_name='nexus_interactions') + op.drop_index('ix_nexus_interactions_thread_id', table_name='nexus_interactions') + op.drop_index('ix_nexus_interactions_ticket_id', table_name='nexus_interactions') + op.drop_index('ix_nexus_interactions_user_id', table_name='nexus_interactions') + op.drop_index('ix_nexus_interactions_workspace_id', table_name='nexus_interactions') + op.drop_table('nexus_interactions') + + if 'remediation_audits' in tables: + op.drop_index('ix_remediation_audits_id', table_name='remediation_audits') + op.drop_index('ix_remediation_audits_ticket_id', table_name='remediation_audits') + op.drop_index('ix_remediation_audits_user_id', table_name='remediation_audits') + op.drop_index('ix_remediation_audits_workspace_id', table_name='remediation_audits') + op.drop_table('remediation_audits') + + op.add_column('tickets', sa.Column('resolution_text', sa.Text(), nullable=True)) + op.add_column('tickets', sa.Column('resolved_by', sa.UUID(), nullable=True)) + op.create_foreign_key(None, 'tickets', 'users', ['resolved_by'], ['id']) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'tickets', type_='foreignkey') + op.drop_column('tickets', 'resolved_by') + op.drop_column('tickets', 'resolution_text') + op.create_table('remediation_audits', + sa.Column('workspace_id', sa.UUID(), autoincrement=False, nullable=False), + sa.Column('ticket_id', sa.UUID(), autoincrement=False, nullable=True), + sa.Column('user_id', sa.UUID(), autoincrement=False, nullable=True), + sa.Column('action_type', sa.VARCHAR(length=100), autoincrement=False, nullable=False), + sa.Column('parameters', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=False), + sa.Column('reasoning', sa.TEXT(), autoincrement=False, nullable=True), + sa.Column('is_successful', sa.BOOLEAN(), autoincrement=False, nullable=True), + sa.Column('execution_log', sa.TEXT(), autoincrement=False, nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), + sa.Column('id', sa.UUID(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), + sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], name='remediation_audits_ticket_id_fkey'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='remediation_audits_user_id_fkey'), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], name='remediation_audits_workspace_id_fkey'), + sa.PrimaryKeyConstraint('id', name='remediation_audits_pkey') + ) + op.create_index('ix_remediation_audits_workspace_id', 'remediation_audits', ['workspace_id'], unique=False) + op.create_index('ix_remediation_audits_user_id', 'remediation_audits', ['user_id'], unique=False) + op.create_index('ix_remediation_audits_ticket_id', 'remediation_audits', ['ticket_id'], unique=False) + op.create_index('ix_remediation_audits_id', 'remediation_audits', ['id'], unique=False) + op.create_table('nexus_interactions', + sa.Column('workspace_id', sa.UUID(), autoincrement=False, nullable=False), + sa.Column('user_id', sa.UUID(), autoincrement=False, nullable=False), + sa.Column('thread_id', sa.UUID(), autoincrement=False, nullable=False), + sa.Column('ticket_id', sa.UUID(), autoincrement=False, nullable=True), + sa.Column('input_query', sa.TEXT(), autoincrement=False, nullable=False), + sa.Column('ai_answer', sa.TEXT(), autoincrement=False, nullable=False), + sa.Column('tool_trace', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), + sa.Column('extracted_params', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), + sa.Column('status', sa.VARCHAR(length=50), autoincrement=False, nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), + sa.Column('id', sa.UUID(), autoincrement=False, nullable=False), + sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), + sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], name='nexus_interactions_ticket_id_fkey'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='nexus_interactions_user_id_fkey'), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], name='nexus_interactions_workspace_id_fkey'), + sa.PrimaryKeyConstraint('id', name='nexus_interactions_pkey') + ) + op.create_index('ix_nexus_interactions_workspace_id', 'nexus_interactions', ['workspace_id'], unique=False) + op.create_index('ix_nexus_interactions_user_id', 'nexus_interactions', ['user_id'], unique=False) + op.create_index('ix_nexus_interactions_ticket_id', 'nexus_interactions', ['ticket_id'], unique=False) + op.create_index('ix_nexus_interactions_thread_id', 'nexus_interactions', ['thread_id'], unique=False) + op.create_index('ix_nexus_interactions_id', 'nexus_interactions', ['id'], unique=False) + op.create_table('nexus_checkpoints', + sa.Column('thread_id', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('checkpoint_id', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('parent_id', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('checkpoint_data', postgresql.BYTEA(), autoincrement=False, nullable=False), + sa.Column('metadata_data', postgresql.BYTEA(), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id', name='nexus_checkpoints_pkey') + ) + # ### end Alembic commands ### diff --git a/alembic/versions/archive/175b693efa2c_add_nexus_agent_tables.py b/alembic/versions/archive/175b693efa2c_add_nexus_agent_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..aa58930f05d8c43f54162e5bd03b99585e99e2e7 --- /dev/null +++ b/alembic/versions/archive/175b693efa2c_add_nexus_agent_tables.py @@ -0,0 +1,67 @@ +"""Add nexus agent tables + +Revision ID: 175b693efa2c +Revises: 0b3641c15213 +Create Date: 2026-03-30 03:59:34.342956 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '175b693efa2c' +down_revision: Union[str, None] = '0b3641c15213' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('nexus_checkpoints', + sa.Column('thread_id', sa.String(), nullable=False), + sa.Column('checkpoint_id', sa.String(), nullable=False), + sa.Column('parent_id', sa.String(), nullable=True), + sa.Column('checkpoint_data', sa.LargeBinary(), nullable=False), + sa.Column('metadata_data', sa.LargeBinary(), nullable=True), + sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id') + ) + op.create_table('nexus_interactions', + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('user_id', sa.UUID(), nullable=False), + sa.Column('thread_id', sa.UUID(), nullable=False), + sa.Column('ticket_id', sa.UUID(), nullable=True), + sa.Column('input_query', sa.Text(), nullable=False), + sa.Column('ai_answer', sa.Text(), nullable=False), + sa.Column('tool_trace', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('extracted_params', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('status', sa.String(length=50), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_nexus_interactions_id'), 'nexus_interactions', ['id'], unique=False) + op.create_index(op.f('ix_nexus_interactions_thread_id'), 'nexus_interactions', ['thread_id'], unique=False) + op.create_index(op.f('ix_nexus_interactions_ticket_id'), 'nexus_interactions', ['ticket_id'], unique=False) + op.create_index(op.f('ix_nexus_interactions_user_id'), 'nexus_interactions', ['user_id'], unique=False) + op.create_index(op.f('ix_nexus_interactions_workspace_id'), 'nexus_interactions', ['workspace_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_nexus_interactions_workspace_id'), table_name='nexus_interactions') + op.drop_index(op.f('ix_nexus_interactions_user_id'), table_name='nexus_interactions') + op.drop_index(op.f('ix_nexus_interactions_ticket_id'), table_name='nexus_interactions') + op.drop_index(op.f('ix_nexus_interactions_thread_id'), table_name='nexus_interactions') + op.drop_index(op.f('ix_nexus_interactions_id'), table_name='nexus_interactions') + op.drop_table('nexus_interactions') + op.drop_table('nexus_checkpoints') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/263c3f7b1819_initial_migration.py b/alembic/versions/archive/263c3f7b1819_initial_migration.py new file mode 100644 index 0000000000000000000000000000000000000000..c22a21050a6dde49794aa525718717468634ad6e --- /dev/null +++ b/alembic/versions/archive/263c3f7b1819_initial_migration.py @@ -0,0 +1,162 @@ +"""Initial migration + +Revision ID: 263c3f7b1819 +Revises: +Create Date: 2026-03-27 19:02:15.019091 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '263c3f7b1819' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('workspaces', + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('branding_config', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_workspaces_id'), 'workspaces', ['id'], unique=False) + op.create_table('projects', + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.String(length=50), nullable=True), + sa.Column('milestones', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_projects_id'), 'projects', ['id'], unique=False) + op.create_index(op.f('ix_projects_workspace_id'), 'projects', ['workspace_id'], unique=False) + op.create_table('users', + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('email', sa.String(length=255), nullable=False), + sa.Column('hashed_password', sa.String(length=255), nullable=False), + sa.Column('full_name', sa.String(length=255), nullable=False), + sa.Column('role', sa.Enum('CUSTOMER_ADMIN', 'CUSTOMER_USER', 'SC_AGENT', 'SC_LEAD', 'SC_ADMIN', name='userrole'), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('avatar_url', sa.String(length=512), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_workspace_id'), 'users', ['workspace_id'], unique=False) + op.create_table('tickets', + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('created_by', sa.UUID(), nullable=False), + sa.Column('assigned_to', sa.UUID(), nullable=True), + sa.Column('project_id', sa.UUID(), nullable=True), + sa.Column('title', sa.String(length=500), nullable=False), + sa.Column('description', sa.Text(), nullable=False), + sa.Column('category', sa.String(length=100), nullable=True), + sa.Column('priority', sa.Enum('P0', 'P1', 'P2', 'P3', name='ticketpriority'), nullable=False), + sa.Column('status', sa.Enum('OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED', name='ticketstatus'), nullable=False), + sa.Column('sla_deadline', sa.DateTime(timezone=True), nullable=True), + sa.Column('ai_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['assigned_to'], ['users.id'], ), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_tickets_assigned_to'), 'tickets', ['assigned_to'], unique=False) + op.create_index(op.f('ix_tickets_created_by'), 'tickets', ['created_by'], unique=False) + op.create_index(op.f('ix_tickets_id'), 'tickets', ['id'], unique=False) + op.create_index(op.f('ix_tickets_project_id'), 'tickets', ['project_id'], unique=False) + op.create_index(op.f('ix_tickets_workspace_id'), 'tickets', ['workspace_id'], unique=False) + op.create_table('attachments', + sa.Column('ticket_id', sa.UUID(), nullable=False), + sa.Column('file_name', sa.String(length=500), nullable=False), + sa.Column('file_url', sa.String(length=1024), nullable=False), + sa.Column('content_type', sa.String(length=100), nullable=True), + sa.Column('file_size', sa.String(length=50), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_attachments_id'), 'attachments', ['id'], unique=False) + op.create_index(op.f('ix_attachments_ticket_id'), 'attachments', ['ticket_id'], unique=False) + op.create_table('feedbacks', + sa.Column('ticket_id', sa.UUID(), nullable=False), + sa.Column('csat_score', sa.Integer(), nullable=False), + sa.Column('comment', sa.Text(), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.CheckConstraint('csat_score >= 1 AND csat_score <= 5', name='csat_score_range'), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_feedbacks_id'), 'feedbacks', ['id'], unique=False) + op.create_index(op.f('ix_feedbacks_ticket_id'), 'feedbacks', ['ticket_id'], unique=True) + op.create_table('messages', + sa.Column('ticket_id', sa.UUID(), nullable=False), + sa.Column('sender_id', sa.UUID(), nullable=False), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('is_internal', sa.Boolean(), nullable=False), + sa.Column('mentions', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_messages_id'), 'messages', ['id'], unique=False) + op.create_index(op.f('ix_messages_sender_id'), 'messages', ['sender_id'], unique=False) + op.create_index(op.f('ix_messages_ticket_id'), 'messages', ['ticket_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_messages_ticket_id'), table_name='messages') + op.drop_index(op.f('ix_messages_sender_id'), table_name='messages') + op.drop_index(op.f('ix_messages_id'), table_name='messages') + op.drop_table('messages') + op.drop_index(op.f('ix_feedbacks_ticket_id'), table_name='feedbacks') + op.drop_index(op.f('ix_feedbacks_id'), table_name='feedbacks') + op.drop_table('feedbacks') + op.drop_index(op.f('ix_attachments_ticket_id'), table_name='attachments') + op.drop_index(op.f('ix_attachments_id'), table_name='attachments') + op.drop_table('attachments') + op.drop_index(op.f('ix_tickets_workspace_id'), table_name='tickets') + op.drop_index(op.f('ix_tickets_project_id'), table_name='tickets') + op.drop_index(op.f('ix_tickets_id'), table_name='tickets') + op.drop_index(op.f('ix_tickets_created_by'), table_name='tickets') + op.drop_index(op.f('ix_tickets_assigned_to'), table_name='tickets') + op.drop_table('tickets') + op.drop_index(op.f('ix_users_workspace_id'), table_name='users') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_table('users') + op.drop_index(op.f('ix_projects_workspace_id'), table_name='projects') + op.drop_index(op.f('ix_projects_id'), table_name='projects') + op.drop_table('projects') + op.drop_index(op.f('ix_workspaces_id'), table_name='workspaces') + op.drop_table('workspaces') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/27de6d53f3f0_add_is_active_to_escalation_rules.py b/alembic/versions/archive/27de6d53f3f0_add_is_active_to_escalation_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8166bd6f2ffc1971d67f87bc3011657c85a437 --- /dev/null +++ b/alembic/versions/archive/27de6d53f3f0_add_is_active_to_escalation_rules.py @@ -0,0 +1,30 @@ +"""add_is_active_to_escalation_rules + +Revision ID: 27de6d53f3f0 +Revises: 86b5efeb3906 +Create Date: 2026-03-31 13:31:44.286498 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '27de6d53f3f0' +down_revision: Union[str, None] = '86b5efeb3906' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### diff --git a/alembic/versions/archive/3dfe53d8e8aa_add_summary_to_kb_articles.py b/alembic/versions/archive/3dfe53d8e8aa_add_summary_to_kb_articles.py new file mode 100644 index 0000000000000000000000000000000000000000..05717433036d857d94ec3bd67f16e8113f46c6f4 --- /dev/null +++ b/alembic/versions/archive/3dfe53d8e8aa_add_summary_to_kb_articles.py @@ -0,0 +1,30 @@ +"""Add summary to kb_articles + +Revision ID: 3dfe53d8e8aa +Revises: c1ae7937bc77 +Create Date: 2026-03-29 11:05:22.858777 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '3dfe53d8e8aa' +down_revision: Union[str, None] = 'c1ae7937bc77' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('kb_articles', sa.Column('summary', sa.Text(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('kb_articles', 'summary') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/86b5efeb3906_make_nexus_thread_id_nullable.py b/alembic/versions/archive/86b5efeb3906_make_nexus_thread_id_nullable.py new file mode 100644 index 0000000000000000000000000000000000000000..0c84adbffc96d8691ca8a15303b4f2dc80b44c99 --- /dev/null +++ b/alembic/versions/archive/86b5efeb3906_make_nexus_thread_id_nullable.py @@ -0,0 +1,34 @@ +"""make_nexus_thread_id_nullable + +Revision ID: 86b5efeb3906 +Revises: b480d2a38d7d +Create Date: 2026-03-30 05:15:13.254451 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '86b5efeb3906' +down_revision: Union[str, None] = 'b480d2a38d7d' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('nexus_interactions', 'thread_id', + existing_type=sa.UUID(), + nullable=True) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('nexus_interactions', 'thread_id', + existing_type=sa.UUID(), + nullable=False) + # ### end Alembic commands ### diff --git a/alembic/versions/archive/9a883ee7d42e_add_attachment_source_url.py b/alembic/versions/archive/9a883ee7d42e_add_attachment_source_url.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab8331a5a7db7b49b34d09f750fcc504d997588 --- /dev/null +++ b/alembic/versions/archive/9a883ee7d42e_add_attachment_source_url.py @@ -0,0 +1,30 @@ +"""add_attachment_source_url + +Revision ID: 9a883ee7d42e +Revises: e7f94a821c56 +Create Date: 2026-03-29 12:25:09.608188 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '9a883ee7d42e' +down_revision: Union[str, None] = 'e7f94a821c56' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('attachments', sa.Column('source_url', sa.String(length=2048), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('attachments', 'source_url') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/a1b2c3d4e5f6_create_notifications_table.py b/alembic/versions/archive/a1b2c3d4e5f6_create_notifications_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc2b9d27aa49295680b4946fe6c57900c9a9cff --- /dev/null +++ b/alembic/versions/archive/a1b2c3d4e5f6_create_notifications_table.py @@ -0,0 +1,39 @@ +"""create_notifications_table + +Revision ID: a1b2c3d4e5f6 +Revises: 175b693efa2c +Create Date: 2026-03-31 10:50:00.000000 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = 'a1b2c3d4e5f6' +down_revision: Union[str, None] = '175b693efa2c' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.create_table('notifications', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('user_id', sa.UUID(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False), + sa.Column('message', sa.Text(), nullable=False), + sa.Column('is_read', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_notifications_id'), 'notifications', ['id'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_notifications_id'), table_name='notifications') + op.drop_table('notifications') diff --git a/alembic/versions/archive/b2895ed533fc_add_ai_workflows_table_correct.py b/alembic/versions/archive/b2895ed533fc_add_ai_workflows_table_correct.py new file mode 100644 index 0000000000000000000000000000000000000000..96c054aa72c63c39a5f38d5d3d089c6279ae3f35 --- /dev/null +++ b/alembic/versions/archive/b2895ed533fc_add_ai_workflows_table_correct.py @@ -0,0 +1,51 @@ +"""add_ai_workflows_table_correct + +Revision ID: b2895ed533fc +Revises: 9a883ee7d42e +Create Date: 2026-03-29 13:15:29.258592 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = 'b2895ed533fc' +down_revision: Union[str, None] = '9a883ee7d42e' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('ai_workflows', + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('entity_id', sa.UUID(), nullable=False), + sa.Column('workflow_type', sa.String(length=50), nullable=False), + sa.Column('current_stage', sa.String(length=100), nullable=True), + sa.Column('steps', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('total_duration_ms', sa.Float(), nullable=True), + sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_ai_workflows_entity_id'), 'ai_workflows', ['entity_id'], unique=False) + op.create_index(op.f('ix_ai_workflows_id'), 'ai_workflows', ['id'], unique=False) + op.create_index(op.f('ix_ai_workflows_workflow_type'), 'ai_workflows', ['workflow_type'], unique=False) + op.create_index(op.f('ix_ai_workflows_workspace_id'), 'ai_workflows', ['workspace_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_ai_workflows_workspace_id'), table_name='ai_workflows') + op.drop_index(op.f('ix_ai_workflows_workflow_type'), table_name='ai_workflows') + op.drop_index(op.f('ix_ai_workflows_id'), table_name='ai_workflows') + op.drop_index(op.f('ix_ai_workflows_entity_id'), table_name='ai_workflows') + op.drop_table('ai_workflows') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/b480d2a38d7d_add_soft_delete_to_notifications.py b/alembic/versions/archive/b480d2a38d7d_add_soft_delete_to_notifications.py new file mode 100644 index 0000000000000000000000000000000000000000..ffeb2c367e7cbe1bb5e581c9eec52fcb658c231c --- /dev/null +++ b/alembic/versions/archive/b480d2a38d7d_add_soft_delete_to_notifications.py @@ -0,0 +1,30 @@ +"""Add soft delete to notifications + +Revision ID: b480d2a38d7d +Revises: 175b693efa2c +Create Date: 2026-03-30 04:12:30.482072 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'b480d2a38d7d' +down_revision: Union[str, None] = 'a1b2c3d4e5f6' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('notifications', sa.Column('deleted_at', sa.DateTime(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('notifications', 'deleted_at') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/c1ae7937bc77_add_kbarticle_and_vector_support.py b/alembic/versions/archive/c1ae7937bc77_add_kbarticle_and_vector_support.py new file mode 100644 index 0000000000000000000000000000000000000000..0df28ba72db293d8f2655e67321580713b142495 --- /dev/null +++ b/alembic/versions/archive/c1ae7937bc77_add_kbarticle_and_vector_support.py @@ -0,0 +1,56 @@ +"""Add KBArticle and vector support + +Revision ID: c1ae7937bc77 +Revises: 263c3f7b1819 +Create Date: 2026-03-27 20:21:25.366896 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql +import pgvector + + +# revision identifiers, used by Alembic. +revision: str = 'c1ae7937bc77' +down_revision: Union[str, None] = '263c3f7b1819' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Enable pgvector extension + op.execute("CREATE EXTENSION IF NOT EXISTS vector") + + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('kb_articles', + sa.Column('workspace_id', sa.UUID(), nullable=False), + sa.Column('title', sa.String(length=500), nullable=False), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('category', sa.String(length=100), nullable=True), + sa.Column('embedding', pgvector.sqlalchemy.vector.VECTOR(dim=1536), nullable=True), + sa.Column('author_id', sa.UUID(), nullable=True), + sa.Column('views', sa.Integer(), nullable=True), + sa.Column('tags', postgresql.JSONB(astext_type=sa.Text()), nullable=True), + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['author_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_kb_articles_id'), 'kb_articles', ['id'], unique=False) + op.create_index(op.f('ix_kb_articles_workspace_id'), 'kb_articles', ['workspace_id'], unique=False) + op.add_column('tickets', sa.Column('embedding', pgvector.sqlalchemy.vector.VECTOR(dim=1536), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('tickets', 'embedding') + op.drop_index(op.f('ix_kb_articles_workspace_id'), table_name='kb_articles') + op.drop_index(op.f('ix_kb_articles_id'), table_name='kb_articles') + op.drop_table('kb_articles') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/d5fd341999f5_add_duplicate_tagging_to_kb_articles.py b/alembic/versions/archive/d5fd341999f5_add_duplicate_tagging_to_kb_articles.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a21d20129092e1cb39a323d3d563ea91352194 --- /dev/null +++ b/alembic/versions/archive/d5fd341999f5_add_duplicate_tagging_to_kb_articles.py @@ -0,0 +1,38 @@ +"""Add duplicate tagging to kb_articles + +Revision ID: d5fd341999f5 +Revises: 3dfe53d8e8aa +Create Date: 2026-03-29 11:15:46.342156 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'd5fd341999f5' +down_revision: Union[str, None] = '3dfe53d8e8aa' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('kb_articles', sa.Column('duplicate_of_id', sa.UUID(), nullable=True)) + op.add_column('kb_articles', sa.Column('force_original', sa.Boolean(), nullable=True)) + op.create_index(op.f('ix_kb_articles_duplicate_of_id'), 'kb_articles', ['duplicate_of_id'], unique=False) + op.create_index(op.f('ix_kb_articles_force_original'), 'kb_articles', ['force_original'], unique=False) + op.create_foreign_key(None, 'kb_articles', 'kb_articles', ['duplicate_of_id'], ['id']) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'kb_articles', type_='foreignkey') + op.drop_index(op.f('ix_kb_articles_force_original'), table_name='kb_articles') + op.drop_index(op.f('ix_kb_articles_duplicate_of_id'), table_name='kb_articles') + op.drop_column('kb_articles', 'force_original') + op.drop_column('kb_articles', 'duplicate_of_id') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/e7f94a821c56_add_attachment_multimodal_and_storage.py b/alembic/versions/archive/e7f94a821c56_add_attachment_multimodal_and_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..c75a2c7592e13970a4194b7da4c534b970c7b7ba --- /dev/null +++ b/alembic/versions/archive/e7f94a821c56_add_attachment_multimodal_and_storage.py @@ -0,0 +1,51 @@ +"""add_attachment_multimodal_and_storage + +Revision ID: e7f94a821c56 +Revises: d5fd341999f5 +Create Date: 2026-03-29 12:12:49.016556 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import pgvector + + +# revision identifiers, used by Alembic. +revision: str = 'e7f94a821c56' +down_revision: Union[str, None] = 'd5fd341999f5' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('attachments', sa.Column('article_id', sa.UUID(), nullable=True)) + op.add_column('attachments', sa.Column('storage_backend', sa.String(length=20), nullable=True)) + op.add_column('attachments', sa.Column('embedding', pgvector.sqlalchemy.vector.VECTOR(dim=512), nullable=True)) + op.add_column('attachments', sa.Column('ai_caption', sa.Text(), nullable=True)) + op.add_column('attachments', sa.Column('is_processed', sa.Boolean(), nullable=True)) + op.alter_column('attachments', 'ticket_id', + existing_type=sa.UUID(), + nullable=True) + op.create_index(op.f('ix_attachments_article_id'), 'attachments', ['article_id'], unique=False) + op.create_index(op.f('ix_attachments_is_processed'), 'attachments', ['is_processed'], unique=False) + op.create_foreign_key(None, 'attachments', 'kb_articles', ['article_id'], ['id']) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'attachments', type_='foreignkey') + op.drop_index(op.f('ix_attachments_is_processed'), table_name='attachments') + op.drop_index(op.f('ix_attachments_article_id'), table_name='attachments') + op.alter_column('attachments', 'ticket_id', + existing_type=sa.UUID(), + nullable=False) + op.drop_column('attachments', 'is_processed') + op.drop_column('attachments', 'ai_caption') + op.drop_column('attachments', 'embedding') + op.drop_column('attachments', 'storage_backend') + op.drop_column('attachments', 'article_id') + # ### end Alembic commands ### diff --git a/alembic/versions/archive/f3a2b1c0d9e8_adjust_vector_dimensions_to_768.py b/alembic/versions/archive/f3a2b1c0d9e8_adjust_vector_dimensions_to_768.py new file mode 100644 index 0000000000000000000000000000000000000000..33d700e388df6e3fc34a8c9498b9e92b4972133e --- /dev/null +++ b/alembic/versions/archive/f3a2b1c0d9e8_adjust_vector_dimensions_to_768.py @@ -0,0 +1,36 @@ +"""adjust_vector_dimensions_to_768 + +Revision ID: f3a2b1c0d9e8 +Revises: e7f94a821c56 +Create Date: 2026-03-31 10:45:00.000000 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import pgvector + + +# revision identifiers, used by Alembic. +revision: str = 'f3a2b1c0d9e8' +down_revision: Union[str, None] = '27de6d53f3f0' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Adjust Ticket embedding dimension + op.execute("ALTER TABLE tickets ALTER COLUMN embedding TYPE vector(768)") + + # Adjust KBArticle embedding dimension + op.execute("ALTER TABLE kb_articles ALTER COLUMN embedding TYPE vector(768)") + + # Adjust KBArticleChunk embedding dimension + op.execute("ALTER TABLE kb_article_chunks ALTER COLUMN embedding TYPE vector(768)") + + +def downgrade() -> None: + op.execute("ALTER TABLE tickets ALTER COLUMN embedding TYPE vector(1536)") + op.execute("ALTER TABLE kb_articles ALTER COLUMN embedding TYPE vector(1536)") + op.execute("ALTER TABLE kb_article_chunks ALTER COLUMN embedding TYPE vector(1536)") diff --git a/alembic/versions/f62561e3e123_add_user_gist_column.py b/alembic/versions/f62561e3e123_add_user_gist_column.py new file mode 100644 index 0000000000000000000000000000000000000000..deb39be8c35c1be4bef1b4ccadac1fd71db63dd1 --- /dev/null +++ b/alembic/versions/f62561e3e123_add_user_gist_column.py @@ -0,0 +1,28 @@ +"""add_user_gist_column + +Revision ID: f62561e3e123 +Revises: 4c626672022a +Create Date: 2026-04-01 08:01:06.739182 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = 'f62561e3e123' +down_revision: Union[str, None] = '4c626672022a' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column('users', sa.Column('ai_gist', postgresql.JSONB(astext_type=sa.Text()), server_default='{}', nullable=False)) + + +def downgrade() -> None: + op.drop_column('users', 'ai_gist') diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/api/v1/__init__.py b/api/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/api/v1/ai.py b/api/v1/ai.py new file mode 100644 index 0000000000000000000000000000000000000000..b2e0a00ce411f22fa9424d4e9eccc8c97cbeedfb --- /dev/null +++ b/api/v1/ai.py @@ -0,0 +1,128 @@ +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, desc +from typing import List, Any +from uuid import UUID + +from core.deps import get_db, get_current_user, get_arq_pool +from core.permissions import require_roles, ADMIN_ROLES, ALL_SC_ROLES +from models.user import User, UserRole +from models.ai_interaction import AIInteraction +from models.ticket import Ticket +from models.kb_article import KBArticle +from models.message import Message +from schemas.ai import AITraceResponse, AINodeInteraction, SummaryResponse, TicketSummary +from core.llm import get_llm +from langchain.schema import HumanMessage, SystemMessage + +router = APIRouter() + +@router.get("/trace/{ticket_id}", response_model=AITraceResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + ADMIN_ROLES))]) +async def get_ticket_ai_trace( + ticket_id: UUID, + db: AsyncSession = Depends(get_db), + current_user: User = Depends(get_current_user) +) -> Any: + """ + Retrieve a chronological trace of all AI interactions (Triage, Remediation, Embedding) + related to a specific ticket. + """ + stmt = ( + select(AIInteraction) + .where( + AIInteraction.ticket_id == ticket_id, + AIInteraction.workspace_id == current_user.workspace_id + ) + .order_by(AIInteraction.created_at.asc()) + ) + + result = await db.execute(stmt) + interactions = result.scalars().all() + + if not interactions: + # Check if ticket exists to return 404 vs empty + from models.ticket import Ticket + t_stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + if not (await db.execute(t_stmt)).scalar_one_or_none(): + raise HTTPException(status_code=404, detail="Ticket not found in your workspace") + + return { + "ticket_id": ticket_id, + "interactions": [], + "total_steps": 0, + "total_duration_ms": 0.0 + } + + total_duration = sum([i.duration_ms.get("total", 0) for i in interactions if i.duration_ms]) + + return { + "ticket_id": ticket_id, + "thread_id": interactions[0].thread_id if interactions else None, + "interactions": interactions, + "total_steps": len(interactions), + "total_duration_ms": round(total_duration, 2) + } + + +@router.post("/summarize/ticket/{ticket_id}", response_model=SummaryResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + [UserRole.SC_ADMIN]))]) +async def summarize_ticket( + ticket_id: UUID, + db: AsyncSession = Depends(get_db), + current_user: User = Depends(get_current_user), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """ + Manually triggers dual summary generation (Internal vs Customer). + """ + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + if not ticket: + raise HTTPException(status_code=404, detail="Ticket not found") + + await arq_pool.enqueue_job("auto_summarize_ticket", ticket.id) + + from datetime import datetime + return { + "id": ticket.id, + "summary": "Summarization enqueued. Please check back in a few seconds.", + "generated_at": datetime.utcnow() + } + + +@router.post("/summarize/kb/{article_id}", response_model=SummaryResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + [UserRole.SC_ADMIN]))]) +async def summarize_kb( + article_id: UUID, + db: AsyncSession = Depends(get_db), + current_user: User = Depends(get_current_user), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """ + Manually triggers KB article summary generation. + """ + stmt = select(KBArticle).where( + KBArticle.id == article_id, + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + result = await db.execute(stmt) + article = result.scalar_one_or_none() + if not article: + raise HTTPException(status_code=404, detail="Article not found") + + await arq_pool.enqueue_job("auto_summarize_kb", article.id) + + from datetime import datetime + return { + "id": article.id, + "summary": "Summarization enqueued.", + "generated_at": datetime.utcnow() + } diff --git a/api/v1/attachments.py b/api/v1/attachments.py new file mode 100644 index 0000000000000000000000000000000000000000..8776485b0a3ecf6937282247df6d7ff0e182fb7a --- /dev/null +++ b/api/v1/attachments.py @@ -0,0 +1,182 @@ +""" +Attachment endpoints: Upload, Download, and Delete with BOLA protection. +""" + +from datetime import datetime +import uuid +from typing import List, Any +from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File +from pathlib import Path +from core.deps import get_db, get_current_user +from core.permissions import ALL_SC_ROLES +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from core.storage import get_storage_provider +from fastapi.responses import FileResponse, RedirectResponse +from models.user import User +from models.ticket import Ticket +from models.attachment import Attachment +from schemas.attachment import AttachmentResponse + +router = APIRouter() + +# Local storage for attachments (Hackathon sim) +# UPLOAD_DIR = Path("uploads") +# UPLOAD_DIR.mkdir(exist_ok=True) + +@router.post("/{ticket_id}/attachments", response_model=AttachmentResponse, status_code=status.HTTP_201_CREATED) +async def upload_attachment( + ticket_id: uuid.UUID, + file: UploadFile = File(...), + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Upload a file for a specific ticket. Enforces ownership for customers.""" + is_staff = current_user.role in ALL_SC_ROLES + + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + # Customers can ONLY upload to tickets they created + stmt = stmt.where(Ticket.created_by == current_user.id) + + result = await db.execute(stmt) + if not result.scalar_one_or_none(): + raise HTTPException(status_code=404, detail="Ticket not found or access denied") + + storage = get_storage_provider() + content = await file.read() + + upload_res = await storage.upload(content, file.filename, current_user.workspace_id) + + new_attachment = Attachment( + workspace_id=current_user.workspace_id, + ticket_id=ticket_id, + uploader_id=current_user.id, + filename=file.filename, + storage_path=upload_res.path, + storage_backend=upload_res.backend, + content_type=file.content_type, + file_size=len(content) + ) + db.add(new_attachment) + await db.commit() + await db.refresh(new_attachment) + return new_attachment + +@router.get("/{ticket_id}/attachments", response_model=List[AttachmentResponse]) +async def list_attachments( + ticket_id: uuid.UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """List all attachments for a specific ticket. Enforces ownership for customers.""" + is_staff = current_user.role in ALL_SC_ROLES + + # 1. Verify ticket access + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + # Customers can ONLY list attachments for tickets they created + stmt = stmt.where(Ticket.created_by == current_user.id) + + result = await db.execute(stmt) + if not result.scalar_one_or_none(): + raise HTTPException(status_code=404, detail="Ticket not found or access denied") + + # 2. Fetch attachments + att_stmt = select(Attachment).where( + Attachment.ticket_id == ticket_id, + Attachment.deleted_at.is_(None) + ).order_by(Attachment.created_at.desc()) + + att_res = await db.execute(att_stmt) + return att_res.scalars().all() + +@router.get("/attachments/{attachment_id}/download") +async def download_attachment( + attachment_id: uuid.UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Download an attachment. Enforces ownership check via parent ticket.""" + is_staff = current_user.role in ALL_SC_ROLES + + # Fetch attachment and join with Ticket to verify ownership + stmt = ( + select(Attachment, Ticket) + .join(Ticket, Attachment.ticket_id == Ticket.id) + .where( + Attachment.id == attachment_id, + Attachment.workspace_id == current_user.workspace_id, + Attachment.deleted_at.is_(None) + ) + ) + + result = await db.execute(stmt) + row = result.fetchone() + if not row: + raise HTTPException(status_code=404, detail="Attachment not found") + + attachment, ticket = row[0], row[1] + + if not is_staff and ticket.created_by != current_user.id: + raise HTTPException(status_code=403, detail="Not authorized to download this attachment") + + storage = get_storage_provider() + if attachment.storage_backend == "s3": + url = await storage.get_url(attachment.storage_path) + return RedirectResponse(url=url) + + return FileResponse( + path=storage.get_local_path(attachment.storage_path), + filename=attachment.filename, + media_type=attachment.content_type + ) + +@router.delete("/attachments/{attachment_id}", status_code=status.HTTP_200_OK) +async def delete_attachment( + attachment_id: uuid.UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Soft Delete an attachment. Enforces ownership check.""" + is_staff = current_user.role in ALL_SC_ROLES + + stmt = ( + select(Attachment, Ticket) + .join(Ticket, Attachment.ticket_id == Ticket.id) + .where( + Attachment.id == attachment_id, + Attachment.workspace_id == current_user.workspace_id, + Attachment.deleted_at.is_(None) + ) + ) + + result = await db.execute(stmt) + row = result.fetchone() + if not row: + raise HTTPException(status_code=404, detail="Attachment not found") + + attachment, ticket = row[0], row[1] + + # Permission: Sender of the attachment OR Admin OR Owner of the Parent Ticket + is_uploader = attachment.uploader_id == current_user.id + is_ticket_owner = ticket.created_by == current_user.id + + if not (is_staff or is_uploader or is_ticket_owner): + raise HTTPException(status_code=403, detail="Not authorized to delete this attachment") + + attachment.deleted_at = datetime.utcnow() + attachment.deleted_by_id = current_user.id + db.add(attachment) + await db.commit() + return {"status": "deleted"} diff --git a/api/v1/auth.py b/api/v1/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..8561a9dc12d8e22314bae6a11e41ab5bb70fb62f --- /dev/null +++ b/api/v1/auth.py @@ -0,0 +1,242 @@ +""" +Authentication endpoints: Registration, Login, Token generation, Password management. +""" + +from fastapi import APIRouter, Depends, HTTPException, status, Header +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from typing import Any, Optional + +from core.database import async_session_factory +from core.deps import get_db, get_current_user, get_current_refresh_user +from core.security import verify_password, get_password_hash, create_access_token, create_refresh_token +from core.logging import get_logger +from models.user import User, UserRole +from models.workspace import Workspace +from schemas.auth import Token, UserRegister, PasswordChangeRequest, TokenRefreshResponse, ForgotPasswordRequest, ResetPasswordRequest + +router = APIRouter() +logger = get_logger(__name__) + + +@router.post("/register", response_model=Token, status_code=status.HTTP_201_CREATED) +async def register_user(user_in: UserRegister, db: AsyncSession = Depends(get_db)) -> Any: + """ + Register a new user. If workspace_id is absent, creates a new workspace and makes the user a CUSTOMER_ADMIN. + Otherwise joins an existing workspace as CUSTOMER_USER. + """ + # Check if user exists + stmt = select(User).where(User.email == user_in.email) + result = await db.execute(stmt) + if result.scalar_one_or_none(): + logger.warning(f"Registration failed: User with email {user_in.email} already exists") + raise HTTPException(status_code=400, detail="User with this email already exists") + + # Handle Workspace + if user_in.workspace_id: + # Join existing workspace + stmt = select(Workspace).where( + Workspace.id == user_in.workspace_id, + Workspace.deleted_at.is_(None) + ) + result = await db.execute(stmt) + workspace = result.scalar_one_or_none() + if not workspace: + raise HTTPException(status_code=404, detail="Workspace not found") + role = UserRole.CUSTOMER_USER + else: + # Create new workspace + ws_name = user_in.workspace_name or f"{user_in.full_name}'s Workspace" + workspace = Workspace(name=ws_name) + db.add(workspace) + await db.flush() # get id + role = UserRole.CUSTOMER_ADMIN + + # --- AUTO-PROVISION SC_ADMIN --- + # Format: admin_@3sc.com + import re + ws_slug = re.sub(r'[^a-z0-9]', '_', ws_name.lower()) + sc_email = f"admin_{ws_slug}@3sc.com" + sc_password = f"SC_Admin_{str(workspace.id)[:8]}!" + + # Ensure unique SC email (unlikely conflict, but safe) + sc_stmt = select(User).where(User.email == sc_email) + sc_exists = (await db.execute(sc_stmt)).scalar_one_or_none() + if not sc_exists: + sc_admin = User( + email=sc_email, + hashed_password=get_password_hash(sc_password), + full_name=f"{ws_name} SC Admin", + role=UserRole.SC_ADMIN, + workspace_id=workspace.id, + ) + db.add(sc_admin) + logger.info(f"AUTO-PROVISION: Created SC Admin {sc_email} for workspace {workspace.id}") + + # Create Initial User (Customer Admin) + new_user = User( + email=user_in.email, + hashed_password=get_password_hash(user_in.password), + full_name=user_in.full_name, + role=role, + workspace_id=workspace.id, + ) + db.add(new_user) + await db.commit() + await db.refresh(new_user) + + logger.info(f"User registration successful: {new_user.email} (ID: {new_user.id})") + + # Generate tokens for the Registrant + access_token = create_access_token(subject=new_user.id, workspace_id=new_user.workspace_id) + refresh_token = create_refresh_token(subject=new_user.id) + + return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"} + + +@router.post("/login", response_model=Token) +async def login( + form_data: OAuth2PasswordRequestForm = Depends(), + db: AsyncSession = Depends(get_db), + x_nexus_portal: Optional[str] = Header(None, alias="X-Nexus-Portal") +) -> Any: + """OAuth2 compatible token login, get an access token for future requests.""" + stmt = select(User).where( + User.email == form_data.username, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + user = result.scalar_one_or_none() + + if not user: + logger.warning(f"Login failed: Account not found for {form_data.username}") + raise HTTPException(status_code=400, detail="Account not found. Please contact your administrator.") + + if not verify_password(form_data.password, user.hashed_password): + logger.warning(f"Login failed: Invalid password for {form_data.username}") + raise HTTPException(status_code=400, detail="Incorrect password. Please try again.") + + # --- PORTAL AUTHORIZATION --- + if x_nexus_portal == "internal": + if user.role not in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]: + logger.warning(f"Login failed: Customer {user.email} attempted Internal Portal access") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Access Denied: Customers cannot access the Operations Console." + ) + elif x_nexus_portal == "customer": + if user.role not in [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]: + # Optional: Allow staff to access customer portal for support? + # For now, let's keep it strict if requested. + logger.warning(f"Login failed: Staff {user.email} attempted Customer Portal access") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Access Denied: Staff must use the Operations Console." + ) + + if not user.is_active: + logger.warning(f"Login failed: Account inactive for {form_data.username}") + raise HTTPException(status_code=400, detail="Inactive user") + + logger.info(f"User login successful: {user.email} (Workspace ID: {user.workspace_id})") + access_token = create_access_token(subject=user.id, workspace_id=user.workspace_id) + refresh_token = create_refresh_token(subject=user.id) + + return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"} + + +@router.post("/change-password") +async def change_password( + payload: PasswordChangeRequest, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Change user password.""" + if not verify_password(payload.old_password, current_user.hashed_password): + raise HTTPException(status_code=400, detail="Invalid old password") + + current_user.hashed_password = get_password_hash(payload.new_password) + db.add(current_user) + await db.commit() + return {"message": "Password updated successfully"} + + +@router.post("/refresh", response_model=TokenRefreshResponse) +async def refresh_token( + current_user: User = Depends(get_current_refresh_user) +) -> Any: + """Exchange a refresh token for a new access token.""" + new_access_token = create_access_token( + subject=current_user.id, + workspace_id=current_user.workspace_id + ) + return {"access_token": new_access_token, "token_type": "bearer"} + + +@router.post("/logout") +async def logout() -> Any: + """ + Log out the current user (Stateless). + In a full production system, this would add the token to a blocklist. + """ + return {"message": "Successfully logged out"} + + +@router.post("/forgot-password") +async def forgot_password(payload: ForgotPasswordRequest) -> Any: + """ + Initiate password reset. + In production, this would send an email with a signed token. + """ + # For now, we'll return a dummy token for the 'reset-password' demo + # In reality, this token would be a short-lived JWT with type='reset' + reset_token = create_access_token(subject=payload.email, expires_delta=None) # Just for demo + return { + "message": "Password reset email sent (simulated)", + "reset_token": reset_token # Returning here ONLY for hackathon/testing ease + } + + +@router.post("/reset-password") +async def reset_password( + payload: ResetPasswordRequest, + db: AsyncSession = Depends(get_db) +) -> Any: + """Reset password using a token.""" + try: + from core.config import get_settings + from jose import jwt + settings = get_settings() + decoded_payload = jwt.decode(payload.token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) + email: str = decoded_payload.get("sub") + if not email: + raise HTTPException(status_code=400, detail="Invalid token") + + stmt = select(User).where( + User.email == email, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + user = result.scalar_one_or_none() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + user.hashed_password = get_password_hash(payload.new_password) + db.add(user) + await db.commit() + return {"message": "Password reset successful"} + except Exception: + raise HTTPException(status_code=400, detail="Invalid or expired reset token") + + +@router.get("/me", response_model=Any) +async def get_my_profile(current_user: User = Depends(get_current_user)) -> Any: + """Get profile of the currently logged-in user.""" + return { + "id": str(current_user.id), + "email": current_user.email, + "full_name": current_user.full_name, + "role": current_user.role, + "workspace_id": str(current_user.workspace_id) + } diff --git a/api/v1/dashboard.py b/api/v1/dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..bf2c933e74a365fddf99c3f86df130ab1c46dca7 --- /dev/null +++ b/api/v1/dashboard.py @@ -0,0 +1,272 @@ +""" +Dashboard endpoints for summary stats and activity. +""" + +from typing import Any, Dict, List +from fastapi import APIRouter, Depends +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, func, or_ + +from core.deps import get_db, get_current_user +from core.llm import get_llm +from langchain_core.prompts import ChatPromptTemplate +from models.user import User, UserRole +from models.ticket import Ticket, TicketStatus + +from schemas.ticket import TicketResponse + +router = APIRouter() + +@router.get("/stats") +async def get_dashboard_stats( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + from datetime import datetime + is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + + # Identify target workspace + target_ws = current_user.workspace_id + is_global = False + if is_staff: + if workspace_id and workspace_id != "all": + target_ws = workspace_id + else: + is_global = True # Global view for staff if no specific workspace selected + + # 1. Basic Status Counts + stmt = ( + select(Ticket.status, func.count(Ticket.id)) + .where(Ticket.deleted_at.is_(None)) + ) + if not is_global: + stmt = stmt.where(Ticket.workspace_id == target_ws) + + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + stmt = stmt.join(Creator, Ticket.created_by == Creator.id).where(Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])) + + stmt = stmt.group_by(Ticket.status) + counts_res = await db.execute(stmt) + counts = {row[0]: row[1] for row in counts_res.all()} + for s in TicketStatus: + if s not in counts: counts[s] = 0 + total = sum(counts.values()) + + # 2. Advanced Metrics (SLA, Resolution, CSAT) + metrics_stmt = select(Ticket).where(Ticket.deleted_at.is_(None)) + if not is_global: + metrics_stmt = metrics_stmt.where(Ticket.workspace_id == target_ws) + + if not is_staff: + from sqlalchemy.orm import aliased + M_Creator = aliased(User) + metrics_stmt = metrics_stmt.join(M_Creator, Ticket.created_by == M_Creator.id).where(M_Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])) + + metrics_res = await db.execute(metrics_stmt) + all_tickets = metrics_res.scalars().all() + + now = datetime.now() + resolved = [t for t in all_tickets if t.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED] and t.resolved_at] + avg_res = sum((t.resolved_at - t.created_at).total_seconds() / 3600 for t in resolved) / len(resolved) if resolved else 0.0 + breached = len([t for t in all_tickets if t.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED] and t.sla_deadline and t.sla_deadline < now]) + ratings = [t.ai_metadata.get("rating") for t in all_tickets if t.ai_metadata and t.ai_metadata.get("rating") is not None] + avg_csat = sum(ratings) / len(ratings) if ratings else 0.0 + + # 3. Personalized Metrics + my_open_stmt = select(func.count(Ticket.id)).where( + Ticket.assigned_to == current_user.id, + Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), + Ticket.deleted_at.is_(None) + ) + if not is_global: + my_open_stmt = my_open_stmt.where(Ticket.workspace_id == target_ws) + my_open_res = await db.execute(my_open_stmt) + my_open_count = my_open_res.scalar() or 0 + + # 4. Personnel Load + personnel_stmt = ( + select(User.full_name, func.count(Ticket.id)) + .join(Ticket, Ticket.assigned_to == User.id) + .where( + Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), + Ticket.deleted_at.is_(None) + ) + ) + if not is_global: + personnel_stmt = personnel_stmt.where(Ticket.workspace_id == target_ws) + + personnel_stmt = personnel_stmt.group_by(User.full_name) + p_res = await db.execute(personnel_stmt) + personnel_load = [{"name": row[0], "count": row[1]} for row in p_res.all()] + + unassigned = len([t for t in all_tickets if t.assigned_to is None and t.status in [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]]) + if unassigned > 0: + personnel_load.append({"name": "Unassigned", "count": unassigned}) + + return { + "total_tickets": total, + "by_status": counts, + "workspace_id": target_ws, + "my_open_count": my_open_count, + "personnel_load": personnel_load, + "performance": { + "avg_resolution_hours": round(avg_res, 1), + "csat_score": round(avg_csat, 1), + "resolved_count": len(resolved), + "rated_count": len(ratings), + "sla_breached_count": breached + } + } + + +@router.get("/my-tickets", response_model=List[TicketResponse]) +async def get_my_tickets( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + from sqlalchemy.orm import aliased + Creator = aliased(User) + Assignee = aliased(User) + + stmt = ( + select( + Ticket, + Creator.full_name.label("creator_name"), + Assignee.full_name.label("assigned_name") + ) + .outerjoin(Creator, Ticket.created_by == Creator.id) + .outerjoin(Assignee, Ticket.assigned_to == Assignee.id) + .where( + ((Ticket.created_by == current_user.id) | (Ticket.assigned_to == current_user.id)), + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + .order_by(Ticket.updated_at.desc()) + ) + result = await db.execute(stmt) + + out = [] + for row in result.all(): + t = row[0] + t.creator_name = row.creator_name + t.assigned_name = row.assigned_name + out.append(t) + return out + + +@router.get("/agent-queue", response_model=List[TicketResponse]) +async def get_agent_queue( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + from sqlalchemy.orm import aliased + is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + + target_ws = current_user.workspace_id + is_global = False + if is_staff: + if workspace_id and workspace_id != "all": + target_ws = workspace_id + else: + is_global = True + + Creator = aliased(User) + Assignee = aliased(User) + + stmt = ( + select( + Ticket, + Creator.full_name.label("creator_name"), + Assignee.full_name.label("assigned_name") + ) + .outerjoin(Creator, Ticket.created_by == Creator.id) + .outerjoin(Assignee, Ticket.assigned_to == Assignee.id) + .where( + Ticket.deleted_at.is_(None) + ) + ) + + if not is_global: + stmt = stmt.where(Ticket.workspace_id == target_ws) + + stmt = stmt.order_by(Ticket.priority.asc(), Ticket.created_at.asc()) + result = await db.execute(stmt) + + out = [] + for row in result.all(): + t = row[0] + t.creator_name = row.creator_name + t.assigned_name = row.assigned_name + out.append(t) + return out + + +@router.get("/ai-insights") +async def get_ai_insights( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """ + Generates a live AI summary and suggested actions for the landing screen. + Uses current workspace context (stats, queue) to provide actionable intelligence. + """ + # 1. Gather context + stats = await get_dashboard_stats(workspace_id, current_user, db) + queue = await get_agent_queue(workspace_id, current_user, db) + + # 2. Prepare Prompt + llm = get_llm() + prompt = ChatPromptTemplate.from_template(""" + You are the Nexus Workspace Intelligence Engine. + Analyze the following workspace operational data and provide: + 1. A concise, professional "Mission Summary" (2-3 sentences). + 2. Exactly 3 "Suggested Actions" for the lead agent. + + DATA: + - Total Active Tickets: {total} + - Breached/Urgent: {breached} + - Distribution: {status_dist} + - Personnel: {agents} + + TICKET SAMPLE: + {ticket_sample} + + Respond in JSON format: + {{ + "summary": "...", + "actions": ["...", "...", "..."] + }} + """) + + # Format ticket sample for context + sample = "\n".join([f"- {t.title} ({t.priority}, {t.status})" for t in queue[:5]]) + + chain = prompt | llm + try: + response = await chain.ainvoke({ + "total": stats["total_tickets"], + "breached": any(t.priority == "P0" for t in queue), # If we have P0s, mention urgency + "status_dist": stats["by_status"], + "agents": len(queue), + "ticket_sample": sample + }) + + # Parse JSON from response content + import json + insights = json.loads(response.content.strip().replace("```json", "").replace("```", "")) + return insights + except Exception as e: + # Fallback to generic if AI fails + return { + "summary": f"Workspace stabilization in progress. {stats['total_tickets']} active tickets identified in the stream.", + "actions": [ + "Review unassigned P0 tickets in the Operational Board", + "Perform load balance check across active personnel", + "Analyze SLA trends for potential breach risks" + ] + } diff --git a/api/v1/escalations.py b/api/v1/escalations.py new file mode 100644 index 0000000000000000000000000000000000000000..053f247ad0d0cdfea9d75ecb2596f2bb3b61dd72 --- /dev/null +++ b/api/v1/escalations.py @@ -0,0 +1,148 @@ +""" +Escalation management endpoints: Rules and Audit. +""" + +from typing import List, Any +from uuid import UUID +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, and_, String, cast + +from core.deps import get_db, get_current_user +from core.permissions import require_roles, ADMIN_ROLES, ALL_SC_ROLES +from models.user import User +from models.escalation_rule import EscalationRule +from models.audit_log import AuditLog +from schemas.escalation import EscalationRuleCreate, EscalationRuleUpdate, EscalationRuleResponse, AuditLogResponse + +router = APIRouter() + +@router.post("/rules", response_model=EscalationRuleResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def create_escalation_rule( + payload: EscalationRuleCreate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Admin only: Create an escalation rule.""" + new_rule = EscalationRule( + workspace_id=current_user.workspace_id, + **payload.model_dump() + ) + db.add(new_rule) + await db.commit() + await db.refresh(new_rule) + return new_rule + +@router.get("/rules", response_model=List[EscalationRuleResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def list_escalation_rules( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Service Center roles: List escalation rules.""" + stmt = select(EscalationRule).where(EscalationRule.workspace_id == current_user.workspace_id).order_by(EscalationRule.priority_level.asc()) + result = await db.execute(stmt) + return result.scalars().all() + +@router.patch("/rules/{rule_id}", response_model=EscalationRuleResponse, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def update_escalation_rule( + rule_id: UUID, + payload: EscalationRuleUpdate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Admin only: Update an escalation rule or toggle its active state.""" + stmt = select(EscalationRule).where( + EscalationRule.id == rule_id, + EscalationRule.workspace_id == current_user.workspace_id + ) + result = await db.execute(stmt) + rule = result.scalar_one_or_none() + if not rule: + raise HTTPException(status_code=404, detail="Rule not found") + + update_data = payload.model_dump(exclude_unset=True) + for key, value in update_data.items(): + setattr(rule, key, value) + + await db.commit() + await db.refresh(rule) + return rule + +@router.delete("/rules/{rule_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def delete_escalation_rule( + rule_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> None: + """Admin only: Remove an escalation rule.""" + stmt = select(EscalationRule).where( + EscalationRule.id == rule_id, + EscalationRule.workspace_id == current_user.workspace_id + ) + result = await db.execute(stmt) + rule = result.scalar_one_or_none() + if not rule: + raise HTTPException(status_code=404, detail="Rule not found") + + await db.delete(rule) + await db.commit() + return None + +@router.get("/audit", response_model=List[AuditLogResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def view_escalation_audit( + skip: int = 0, limit: int = 100, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """View audit trail of escalations and status changes.""" + stmt = select(AuditLog).where( + AuditLog.workspace_id == current_user.workspace_id, + AuditLog.action.in_(["escalation", "status_change"]) + ).offset(skip).limit(limit).order_by(AuditLog.created_at.desc()) + result = await db.execute(stmt) + return result.scalars().all() + +@router.get("/breaches", dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def list_active_breaches( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get all tickets that are currently in BREACH status based on ACTIVE rules.""" + from models.ticket import Ticket, TicketStatus + from datetime import datetime + + # 1. Fetch tickets and ACTIVE rules + stmt = ( + select(Ticket, EscalationRule.threshold_minutes) + .join(EscalationRule, and_( + EscalationRule.workspace_id == Ticket.workspace_id, + EscalationRule.priority_level == cast(Ticket.priority, String), + EscalationRule.is_active == True + ), isouter=True) + .where( + Ticket.workspace_id == current_user.workspace_id, + Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), + Ticket.deleted_at.is_(None) + ) + ) + result = await db.execute(stmt) + rows = result.all() + + now = datetime.utcnow() + breached_tickets = [] + for ticket, threshold in rows: + # Default to 24h if no active rule exists + limit = threshold or 1440 + age_mins = (now - ticket.created_at).total_seconds() / 60 + if age_mins > limit: + breached_tickets.append({ + "id": str(ticket.id), + "title": ticket.title, + "priority": ticket.priority, + "status": ticket.status, + "age_minutes": round(age_mins, 1), + "threshold": limit, + "is_escalated": ticket.is_escalated is not None + }) + + return breached_tickets diff --git a/api/v1/feedback.py b/api/v1/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..4bde3f42f84cb37718e77cd1a403efb37d645f86 --- /dev/null +++ b/api/v1/feedback.py @@ -0,0 +1,74 @@ +""" +Feedback endpoints: Submit and View CSAT ratings. +""" + +import uuid +from typing import List, Any +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from core.deps import get_db, get_current_user +from core.permissions import require_roles, ALL_CUSTOMER_ROLES, ALL_SC_ROLES +from models.user import User +from models.ticket import Ticket, TicketStatus +from models.feedback import Feedback +from schemas.feedback import FeedbackCreate, FeedbackResponse + +router = APIRouter() + +@router.post("/{ticket_id}/feedback", response_model=FeedbackResponse, status_code=status.HTTP_201_CREATED) +async def submit_feedback( + ticket_id: uuid.UUID, + payload: FeedbackCreate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Submit CSAT feedback for a resolved/closed ticket.""" + # Validate ticket exists and is resolved/closed + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + + if not ticket: + raise HTTPException(status_code=404, detail="Ticket not found in your workspace") + + if ticket.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED]: + raise HTTPException(status_code=400, detail="Feedback can only be submitted for resolved or closed tickets") + + # Check if feedback already exists + stmt = select(Feedback).where(Feedback.ticket_id == ticket_id) + result = await db.execute(stmt) + if result.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="Feedback already submitted for this ticket") + + new_feedback = Feedback( + id=uuid.uuid4(), + workspace_id=current_user.workspace_id, + ticket_id=ticket_id, + user_id=current_user.id, + rating=payload.rating, + comment=payload.comment + ) + db.add(new_feedback) + await db.commit() + await db.refresh(new_feedback) + return new_feedback + +@router.get("/{ticket_id}/feedback", response_model=FeedbackResponse) +async def get_ticket_feedback( + ticket_id: uuid.UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """View feedback for a specific ticket.""" + stmt = select(Feedback).where(Feedback.ticket_id == ticket_id, Feedback.workspace_id == current_user.workspace_id) + result = await db.execute(stmt) + feedback = result.scalar_one_or_none() + if not feedback: + raise HTTPException(status_code=404, detail="Feedback not found") + return feedback diff --git a/api/v1/kb.py b/api/v1/kb.py new file mode 100644 index 0000000000000000000000000000000000000000..4d500f299583e3d2c82476ccdaf3aefb4cb6475b --- /dev/null +++ b/api/v1/kb.py @@ -0,0 +1,703 @@ +import asyncio +import asyncio +import time +from datetime import datetime +from typing import Any, List, Optional +from uuid import UUID +from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, func, text, desc, update + +from core.deps import get_db, get_current_user, get_arq_pool +from core.permissions import require_roles, ALL_SC_ROLES +from core.logging import get_logger +from models.user import User +from models.kb_article import KBArticle +from models.kb_article_chunk import KBArticleChunk +from models.project import Project +from core.llm import get_embeddings, get_llm, get_text_embeddings, get_image_embeddings +from core.vision import resolve_image +from langchain.schema import HumanMessage, SystemMessage +from models.attachment import Attachment +from core.search import chunk_text +from core.vision import extract_visual_context +from core.sync import sync_markdown_images +from schemas.kb import KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse, KBBulkActionRequest, KBBulkSyncRequest + +router = APIRouter() +logger = get_logger(__name__) + +async def generate_article_embedding(db: Optional[AsyncSession], article_id: UUID) -> None: + """Consolidated background task for categorization, embedding, chunking, and summarization.""" + from core.database import async_session_factory + + # Session Safety: If called as a background task without a session, create one + if db is None: + async with async_session_factory() as session: + await _execute_article_indexing_lifecycle(session, article_id) + else: + await _execute_article_indexing_lifecycle(db, article_id) + +async def _execute_article_indexing_lifecycle(db: AsyncSession, article_id: UUID) -> None: + """Internal implementation of the full KB AI lifecycle: embeddings, vision, duplication, and summary.""" + import time + from core.observability import record_workflow_step + start_time = time.perf_counter() + + try: + # Fetch fresh article state + stmt = select(KBArticle).where(KBArticle.id == article_id, KBArticle.deleted_at.is_(None)) + res = await db.execute(stmt) + article = res.scalar_one_or_none() + if not article: + logger.error(f"KB Multi-Indexing failed: Article {article_id} not found or deleted.") + return + + # --- 1.1 Multi-Model Initialization --- + text_model = get_text_embeddings() + + # --- 1. Sync Markdown Images --- + sync_start = time.perf_counter() + await sync_markdown_images(db, article_id, article.workspace_id, article.content, entity_type="article", uploader_id=article.author_id) + await record_workflow_step( + db, article_id, article.workspace_id, "LIFECYCLE", + "KB_IMAGE_SYNC", + duration_ms=(time.perf_counter() - sync_start) * 1000 + ) + + # --- 1.2 Generate main article embedding --- + logger.info(f"Generating embedding for KB Article {article_id}...") + text_to_embed = f"{article.title} {article.content}" + + # --- Auto-Categorization Block --- + if not article.category or article.category == "N/A": + try: + logger.info(f"AI Categorizing KB Article {article_id}...") + llm = get_llm() + cat_prompt = ( + f"Categorize this Knowledge Base article into exactly ONE category (e.g., Setup, Troubleshooting, Security, API, General). " + f"Title: {article.title}\nContent: {article.content[:500]}\n" + f"Return ONLY the category name." + ) + cat_res = await llm.ainvoke(cat_prompt) + if cat_res and cat_res.content: + article.category = cat_res.content.strip() + logger.info(f"Auto-assigned category: {article.category}") + except Exception as cat_err: + logger.warning(f"Auto-categorization failed for {article_id}: {cat_err}") + + vector = await text_model.aembed_query(text_to_embed) + article.embedding = vector + + # --- 1.2 Multimodal Attachment Indexing --- + att_stmt = select(Attachment).where( + Attachment.article_id == article_id, + Attachment.content_type.like("image/%"), + Attachment.is_processed == False + ) + att_res = await db.execute(att_stmt) + attachments = att_res.scalars().all() + + if attachments: + logger.info(f"Indexing {len(attachments)} images for KB Article {article_id}...") + llm = get_llm() + img_model = get_image_embeddings() + + for att in attachments: + try: + resolved = await resolve_image(db, article.workspace_id, str(att.id)) + if resolved: + caption_prompt = [ + SystemMessage(content="Describe this Knowledge Base technical image/screenshot briefly (1-2 sentences)."), + HumanMessage(content=[resolved]) + ] + caption_res = await llm.ainvoke(caption_prompt) + att.ai_caption = caption_res.content + + img_vector = await img_model.aembed_query(resolved["image_url"]["url"]) + att.embedding = img_vector + + att.is_processed = True + db.add(att) + except Exception as img_err: + logger.error(f"Failed to index KB attachment {att.id}: {img_err}") + + # --- 1.5 Duplicate Check --- + # Using unified 0.7 threshold + if not article.force_original: + dup_stmt = ( + select( + KBArticle, + (1 - KBArticle.embedding.cosine_distance(vector)).label("sim_score") + ) + .where( + KBArticle.workspace_id == article.workspace_id, + KBArticle.id != article.id, + KBArticle.is_published == True, + KBArticle.duplicate_of_id.is_(None), + KBArticle.deleted_at.is_(None) + ) + .order_by(desc("sim_score")) + .limit(1) + ) + dup_res = await db.execute(dup_stmt) + match = dup_res.first() + if match and match.sim_score >= 0.7: + article.duplicate_of_id = match.KBArticle.id + article.is_published = False + logger.info(f"KB Duplicate detected: {article_id} clones {match.KBArticle.id}. Setting is_published=False.") + + # --- 2. Clear & Create Chunks --- + from sqlalchemy import delete + await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id)) + + from core.search import chunk_text + chunks = chunk_text(article.content, chunk_size=600, chunk_overlap=100) + for i, text in enumerate(chunks): + chunk_vector = await text_model.aembed_query(f"{article.title}: {text}") + new_chunk = KBArticleChunk( + article_id=article.id, + content=text, + chunk_index=i, + embedding=chunk_vector + ) + db.add(new_chunk) + + # --- 3. [NEW] Consolidated AI Summarization --- + # Integrated directly to ensure atomicity + summary_start = time.perf_counter() + + try: + logger.info(f"Generating consolidated AI summary for KB Article {article_id}...") + llm = get_llm() + + # Fetch visual context + article_imgs = await extract_visual_context(db, article.workspace_id, article.content, limit=5) + + content_txt = f"Title: {article.title}\n\nContent:\n{article.content}" + + # Try Multimodal first + try: + content_blocks = [{"type": "text", "text": content_txt}] + if article_imgs: + content_blocks.extend(article_imgs) + + prompt = [ + SystemMessage(content="Summarize this technical KB article in 2-3 sentences. Focus on correctness and clarity."), + HumanMessage(content=content_blocks) + ] + resp = await llm.ainvoke(prompt) + article.summary = resp.content + logger.info(f"KB Summary (Multimodal) generated for {article_id}") + except Exception as vision_err: + logger.warning(f"Vision-based summary failed for {article_id}, falling back to text-only: {vision_err}") + # Fallback to Text-Only + prompt = [ + SystemMessage(content="Summarize this technical KB article in 2-3 sentences."), + HumanMessage(content=content_txt) + ] + resp = await llm.ainvoke(prompt) + article.summary = resp.content + logger.info(f"KB Summary (Text-Fallback) generated for {article_id}") + + except Exception as sum_err: + logger.error(f"Total summarization failure for {article_id}: {sum_err}") + + # --- Record Completion --- + await record_workflow_step( + db, article_id, article.workspace_id, "LIFECYCLE", + "KB_INDEXING_COMPLETE", + output_data={ + "chunks": len(chunks), + "images": len(attachments), + "summary_len": len(article.summary or "") + }, + current_stage="READY_FOR_SEARCH", + duration_ms=(time.perf_counter() - start_time) * 1000 + ) + + await db.commit() + logger.info(f"KB Article {article_id} indexed and traced.") + + except Exception as e: + logger.error(f"FATAL: KB Indexing failed for {article_id}: {e}") + await db.rollback() + +@router.post("/", response_model=KBArticleResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def create_kb_article( + payload: KBArticleCreate, + background_tasks: BackgroundTasks, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """Agents/Admin only: create a KB article.""" + # 1. Validate project_id if provided + if payload.project_id: + proj_stmt = select(Project).where( + Project.id == payload.project_id, + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ) + proj_res = (await db.execute(proj_stmt)).scalar_one_or_none() + if not proj_res: + raise HTTPException( + status_code=400, + detail=f"Project {payload.project_id} not found in your workspace" + ) + + new_article = KBArticle( + title=payload.title, + content=payload.content, + category=payload.category, + project_id=payload.project_id, + workspace_id=current_user.workspace_id, + author_id=current_user.id + ) + db.add(new_article) + await db.commit() + await db.refresh(new_article) + + # Generate embedding in background (now includes summarization) + background_tasks.add_task(generate_article_embedding, db, new_article.id) + + logger.info(f"KB Article created: {new_article.id} by user {current_user.id}") + + return new_article + +@router.get("/", response_model=List[KBArticleResponse]) +async def list_kb_articles( + category: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """List KB articles with optional category filter.""" + stmt = select(KBArticle).where( + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None), + KBArticle.duplicate_of_id.is_(None) + ) + if category: + if category == "N/A": + stmt = stmt.where(KBArticle.category.is_(None)) + else: + stmt = stmt.where(KBArticle.category == category) + result = await db.execute(stmt) + return result.scalars().all() + +@router.get("/categories", response_model=List[str]) +async def list_kb_categories( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Retrieve all unique categories in use for this workspace.""" + stmt = select(func.distinct(KBArticle.category)).where( + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + result = await db.execute(stmt) + categories = [c for c in result.scalars().all()] + # Normalize nulls to "N/A" + normalized = sorted([c if c else "N/A" for c in categories]) + return normalized + +async def generate_query_variations(query: str) -> List[str]: + """Uses LLM to generate 3 variations of the search query for better hit coverage.""" + try: + llm = get_llm() + prompt = ( + f"You are a search optimizer. Given a raw customer support query, generate exactly 3 variations of the query to improve search results. " + f"1. A corrected/cleaned version (fixing typos). " + f"2. A semantic expansion (related terms). " + f"3. A structured phrasing (technical context). " + f"Return ONLY the 3 queries, one per line, no numbering, no conversation. " + f"Query: {query}" + ) + resp = await llm.ainvoke(prompt) + variations = [line.strip() for line in resp.content.split('\n') if line.strip()] + # Fallback to original if LLM fails or returns less than expected + if not variations: + return [query] + return variations[:3] + except Exception as e: + logger.error(f"Failed to generate query variations: {e}") + return [query] + +async def execute_multimodal_search(db: AsyncSession, q: str, current_user: User, category: Optional[str], project_id: Optional[UUID]): + """Internal helper to execute factual hybrid search + visual attachment search.""" + import uuid + import time + from core.observability import record_workflow_step + search_id = uuid.uuid4() + start_time = time.perf_counter() + + # 1. Get Text Embedding for the query (Nomic-768) + embed_start = time.perf_counter() + query_vector = await get_text_embeddings().aembed_query(q) + await record_workflow_step( + db, search_id, current_user.workspace_id, "SEARCH", + "QUERY_EMBEDDING", + input_data={"q": q}, + duration_ms=(time.perf_counter() - embed_start) * 1000 + ) + + # 2. SEACH A: Text Semantic Match (Articles) + sem_start = time.perf_counter() + semantic_stmt = ( + select( + KBArticle, + (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score") + ) + .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id) + .where( + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None), + KBArticle.is_published == True, + KBArticle.duplicate_of_id.is_(None) + ) + ) + if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category) + if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id) + semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20) + + # 3. SEARCH B: Visual Caption Match (Attachments) + vis_start = time.perf_counter() + visual_stmt = ( + select( + KBArticle, + func.ts_rank( + func.to_tsvector('english', Attachment.ai_caption), + func.plainto_tsquery('english', q) + ).label("vis_score") + ) + .join(Attachment, KBArticle.id == Attachment.article_id) + .where( + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None), + KBArticle.is_published == True, + Attachment.ai_caption.isnot(None) + ) + .order_by(desc("vis_score")) + .limit(10) + ) + + # Execute sequentially to avoid asyncpg InterfaceError (single connection cannot handle concurrent requests) + sem_res = await db.execute(semantic_stmt) + vis_res = await db.execute(visual_stmt) + + hits = sem_res.all() + v_hits = vis_res.all() + + await record_workflow_step( + db, search_id, current_user.workspace_id, "SEARCH", + "RETRIEVAL_COMPLETE", + output_data={"semantic_hits": len(hits), "visual_hits": len(v_hits)}, + duration_ms=(time.perf_counter() - sem_start) * 1000 + ) + + # 4. Hybrid Fusion (Reciprocal Rank Fusion simplified) + fusion_start = time.perf_counter() + results_map = {} + + # Process semantic hits + for article, score in hits: + if article.id not in results_map: + results_map[article.id] = {"article": article, "score": float(score) or 0.0, "type": "semantic"} + + # Process visual hits (boost by 0.3 if matched visually) + for article, v_score in v_hits: + if article.id in results_map: + results_map[article.id]["score"] += (float(v_score) or 0.0) + 0.3 + results_map[article.id]["type"] = "hybrid" + else: + results_map[article.id] = {"article": article, "score": (float(v_score) or 0.0) + 0.1, "type": "visual"} + + # Sort final results + sorted_results = sorted(results_map.values(), key=lambda x: x["score"], reverse=True)[:10] + + await record_workflow_step( + db, search_id, current_user.workspace_id, "SEARCH", + "HYBRID_FUSION_COMPLETE", + output_data={"final_result_count": len(sorted_results)}, + duration_ms=(time.perf_counter() - fusion_start) * 1000, + current_stage="RESULTS_DELIVERED" + ) + + # Commit search workflow + await db.commit() + + return {r["article"].id: {"obj": r["article"], "score": r["score"], "type": r["type"], "search_id": str(search_id)} for r in sorted_results} + +@router.get("/search", response_model=KBSearchResponse) +async def search_kb_articles( + q: str, + category: Optional[str] = None, + project_id: Optional[UUID] = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Advanced Search with LLM Multi-Query Expansion for maximum reliability.""" + start_time = time.perf_counter() + + # 1. Expand Query to Handle Typos/Context (3 variations) + variations = await generate_query_variations(q) + logger.info(f"KB Search Multi-Expansion: '{q}' -> {variations}") + + # 2. Run searches for all 3 variations sequentially + # (asyncpg does NOT support concurrent operations on a single connection) + all_local_results = [] + for var in variations: + local_res = await execute_multimodal_search(db, var, current_user, category, project_id) + all_local_results.append(local_res) + + # 3. Global Fusion + global_merged = {} + for local_res in all_local_results: + for art_id, data in local_res.items(): + score = float(data.get("score") or 0.0) + if art_id not in global_merged: + global_merged[art_id] = data + global_merged[art_id]["score"] = score # ensure it exists + else: + global_merged[art_id]["score"] = max(float(global_merged[art_id].get("score") or 0.0), score) + + # 4. Final Scoring & Thresholding + THRESHOLD = 0.2 + final_results = [] + for art_id, data in global_merged.items(): + score = float(data.get("score") or 0.0) + if score >= THRESHOLD: + article_obj = data["obj"] + res_dict = KBArticleResponse.model_validate(article_obj).model_dump() + res_dict["score"] = score + res_dict["match_type"] = data.get("type", "semantic") # Safe access to avoid KeyError + final_results.append(res_dict) + + final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True) + top_results = final_results[:5] + + # 5. Suggestion for UI if results are still thin + suggestion = variations[0] if variations and variations[0].lower() != q.lower() else None + + end_time = time.perf_counter() + search_time_s = end_time - start_time + + return { + "results": top_results, + "suggestion": suggestion if not top_results else None, + "expanded_queries": variations, + "search_time_s": round(search_time_s, 3) + } + +@router.get("/{article_id}", response_model=KBArticleResponse) +async def get_kb_article( + article_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get a specific KB article.""" + stmt = select(KBArticle).where( + KBArticle.id == article_id, + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + result = await db.execute(stmt) + article = result.scalar_one_or_none() + if not article: + raise HTTPException(status_code=404, detail="Article not found") + return article + +@router.patch("/{article_id}", response_model=KBArticleResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def update_kb_article( + article_id: UUID, + payload: KBArticleUpdate, + background_tasks: BackgroundTasks, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """Agents/Admin only: update KB article details.""" + stmt = select(KBArticle).where( + KBArticle.id == article_id, + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + result = await db.execute(stmt) + article = result.scalar_one_or_none() + if not article: + raise HTTPException(status_code=404, detail="Article not found") + + update_data = payload.model_dump(exclude_unset=True) + + # Validate project_id if it's being updated + if "project_id" in update_data and update_data["project_id"] is not None: + proj_stmt = select(Project).where( + Project.id == update_data["project_id"], + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ) + proj_res = (await db.execute(proj_stmt)).scalar_one_or_none() + if not proj_res: + raise HTTPException( + status_code=400, + detail=f"Project {update_data['project_id']} not found in your workspace" + ) + + # Sync images if content is updated + if "content" in update_data: + # Corrected signature: (db, entity_id, workspace_id, content, entity_type, uploader_id) + await sync_markdown_images(db, article.id, article.workspace_id, update_data["content"], entity_type="article", uploader_id=current_user.id) + + for field, value in update_data.items(): + setattr(article, field, value) + + db.add(article) + await db.commit() + await db.refresh(article) + + # Re-index if content/title changed + if "content" in update_data or "title" in update_data: + background_tasks.add_task(generate_article_embedding, None, article.id) + logger.info(f"KB Article {article_id} updated, re-indexing triggered...") + + # Auto-summarize if published or if content changed significantly while published + if article.is_published: + await arq_pool.enqueue_job("auto_summarize_kb", article.id) + + return article + +@router.delete("/{article_id}", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def delete_kb_article( + article_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Agents/Admin only: Soft Delete a KB article.""" + # Redundant Role Hardening: Capture any leakage from require_roles decorator + if current_user.role not in ALL_SC_ROLES: + raise HTTPException(status_code=403, detail="Only SC staff can manage the knowledge base") + + stmt = select(KBArticle).where( + KBArticle.id == article_id, + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + result = await db.execute(stmt) + article = result.scalar_one_or_none() + if not article: + raise HTTPException(status_code=404, detail="Article not found") + + from sqlalchemy import delete + article.deleted_at = datetime.utcnow() + article.deleted_by_id = current_user.id + article.is_published = False + + # Cascade inactivation to attachments + att_stmt = ( + update(Attachment) + .where(Attachment.article_id == article_id) + .values(deleted_at=article.deleted_at) + ) + await db.execute(att_stmt) + + # Purge chunks + await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id)) + + db.add(article) + await db.commit() + logger.info(f"KB Article and children inactivated: {article_id} by user {current_user.id}") + return {"status": "deleted"} + +@router.post("/bulk-publish", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def bulk_publish_articles( + payload: KBBulkSyncRequest, + background_tasks: BackgroundTasks, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """Agents/Admin only: Bulk process (Create/Update) and Publish KB articles.""" + results = {"created": 0, "updated": 0, "ids": []} + + for art_def in payload.articles: + # Check for existing by title in this workspace + stmt = select(KBArticle).where( + KBArticle.title == art_def.title, + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + res = await db.execute(stmt) + article = res.scalar_one_or_none() + + if article: + article.content = art_def.content + article.category = art_def.category + article.project_id = art_def.project_id + article.is_published = True + results["updated"] += 1 + else: + article = KBArticle( + title=art_def.title, + content=art_def.content, + category=art_def.category, + project_id=art_def.project_id, + workspace_id=current_user.workspace_id, + author_id=current_user.id, + is_published=True + ) + db.add(article) + results["created"] += 1 + + await db.flush() # ensure ID is available + results["ids"].append(str(article.id)) + + # Trigger re-indexing and summarization + background_tasks.add_task(generate_article_embedding, None, article.id) + await arq_pool.enqueue_job("auto_summarize_kb", article.id) + + await db.commit() + logger.info(f"Bulk Sync & Publish: {results['created']} created, {results['updated']} updated for workspace {current_user.workspace_id}") + return {"status": "success", "summary": results} + +@router.post("/bulk-unpublish", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def bulk_unpublish_articles( + payload: KBBulkActionRequest, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Agents/Admin only: Bulk inactivate (Soft Delete) KB articles and their chunks.""" + from sqlalchemy import delete + ids = payload.article_ids + + # 1. Soft Delete the Articles + stmt = ( + update(KBArticle) + .where( + KBArticle.id.in_(ids), + KBArticle.workspace_id == current_user.workspace_id, + KBArticle.deleted_at.is_(None) + ) + .values( + deleted_at=datetime.utcnow(), + deleted_by_id=current_user.id, + is_published=False + ) + ) + res = await db.execute(stmt) + count = res.rowcount + + # 2. Hard Delete the Chunks (to deactivate search) + chunk_del = delete(KBArticleChunk).where(KBArticleChunk.article_id.in_(ids)) + await db.execute(chunk_del) + + # 3. Soft Delete the Attachments + att_del = ( + update(Attachment) + .where(Attachment.article_id.in_(ids)) + .values(deleted_at=datetime.utcnow()) + ) + await db.execute(att_del) + + await db.commit() + logger.info(f"Bulk Inactivation: {count} articles and their children deactivated by user {current_user.id}") + return {"status": "success", "inactivated_count": count} diff --git a/api/v1/messages.py b/api/v1/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f000d0f47e6709ea4359be016c1403abff65ba --- /dev/null +++ b/api/v1/messages.py @@ -0,0 +1,242 @@ +""" +Message endpoints: threaded messaging for tickets with BOLA protection. +""" + +from typing import Any, List, Dict +from uuid import UUID +from fastapi import APIRouter, Depends, HTTPException, status, Response +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from core.deps import get_db, get_current_user +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)) + stmt = select(User).where( + User.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: + """Helper to inject sender name and role into the message object.""" + from sqlalchemy import select + from models.user import User + + stmt = select(User.full_name, User.role).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]) + 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) +) -> 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.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + # Customers can ONLY post to tickets they created + 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 + mentions = await parse_mentions(payload.content, current_user.workspace_id, db) + + new_message = Message( + content=payload.content, + is_internal=payload.is_internal, + ticket_id=ticket_id, + workspace_id=current_user.workspace_id, + 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_settings + from arq import create_pool + 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.close() + except Exception as e: + print(f"FAILED TO QUEUE MENTION 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) +) -> 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: + mentions = await parse_mentions(payload.content, current_user.workspace_id, db) + message.mentions = mentions + + db.add(message) + await db.commit() + await db.refresh(message) + 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 + is_owner = message.sender_id == current_user.id + is_admin = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.CUSTOMER_ADMIN] + + 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 in a ticket. Enforces BOLA protection and internal notes masking.""" + is_staff = current_user.role in ALL_SC_ROLES + + # 1. Verify ticket access + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + # Customers can ONLY view messages for tickets they created + 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. Fetch messages + msg_stmt = ( + select(Message) + .where( + Message.ticket_id == ticket_id, + Message.deleted_at.is_(None) + ) + .order_by(Message.created_at.asc()) + ) + + # Mask internal notes for customers + if not is_staff: + msg_stmt = msg_stmt.where(Message.is_internal == False) + + result = await db.execute(msg_stmt) + messages = result.scalars().all() + return [await sanitize_message_response(m, db) for m in messages] diff --git a/api/v1/nexus.py b/api/v1/nexus.py new file mode 100644 index 0000000000000000000000000000000000000000..d78d00aae369dd7fc0e35104ed173534657e72fb --- /dev/null +++ b/api/v1/nexus.py @@ -0,0 +1,177 @@ +from typing import Any, List, Dict, Optional +from uuid import UUID +from fastapi import APIRouter, Depends, HTTPException, status +from pydantic import BaseModel +from sqlalchemy.ext.asyncio import AsyncSession +from langchain_core.messages import HumanMessage, AIMessage + +from core.deps import get_db, get_current_user +from models.user import User, UserRole +from agents.nexus_master import create_nexus_graph +from models.nexus_interaction import NexusInteraction +from schemas.ai import NexusHistoryResponse, AINodeInteraction +from core.permissions import require_roles, ALL_SC_ROLES, ADMIN_ROLES +from sqlalchemy import select, desc + +router = APIRouter() + +class NexusQueryRequest(BaseModel): + query: str + chat_history: List[Dict[str, str]] = [] # [{"role": "user", "content": "..."}, ...] + thread_id: Optional[UUID] = None + ticket_id: Optional[UUID] = None + action_approved: bool = False + +class NexusResponse(BaseModel): + answer: str + sources: List[str] = [] + +@router.post("/query", response_model=NexusResponse) +async def query_nexus_master( + payload: NexusQueryRequest, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """ + Unified entry point for natural language workspace interaction. + Orchestrates KB search, ticket management, and analytics with full RBAC isolation. + """ + from sqlalchemy import select + from models.nexus_interaction import NexusInteraction + + # 1. Prepare Initial State + is_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.CUSTOMER_ADMIN] + + # Validation: If ticket_id provided, it MUST exist in this workspace + if payload.ticket_id: + from models.ticket import Ticket + from sqlalchemy import select + stmt = select(Ticket).where(Ticket.id == payload.ticket_id, Ticket.workspace_id == current_user.workspace_id) + res = await db.execute(stmt) + if not res.scalar_one_or_none(): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Invalid ticket_id: {payload.ticket_id} for this workspace." + ) + + messages = [] + for m in payload.chat_history: + if m["role"] == "user": + messages.append(HumanMessage(content=m["content"])) + else: + messages.append(AIMessage(content=m["content"])) + + messages.append(HumanMessage(content=payload.query)) + + thread_id = payload.thread_id or UUID("00000000-0000-0000-0000-000000000001") + + # 2. Fetch Long-Term Memory (Internal Summary) if thread exists + internal_summary = "" + last_interaction_stmt = ( + select(NexusInteraction) + .where(NexusInteraction.thread_id == thread_id) + .order_by(NexusInteraction.created_at.desc()) + .limit(1) + ) + last_interaction_res = await db.execute(last_interaction_stmt) + last_interaction = last_interaction_res.scalar_one_or_none() + if last_interaction and last_interaction.metadata_json: + internal_summary = last_interaction.metadata_json.get("internal_summary", "") + + initial_state = { + "messages": messages, + "workspace_id": current_user.workspace_id, + "user_role": current_user.role, + "is_agent": is_agent, + "user_name": current_user.full_name, + "user_id": current_user.id, + "sources": [], + "current_tool_output": None, + "pending_actions": [], + "action_approved": payload.action_approved or False, + "vision_context": [], + "ticket_id": payload.ticket_id, + "thread_id": thread_id, + "target_user_id": None, + "target_status": None, + "internal_summary": internal_summary, + "ticket_context": "", + "ai_gist": current_user.ai_gist or {} + } + + # 2. Invoke the Master Graph + app = create_nexus_graph() + config = {"configurable": {"thread_id": str(payload.thread_id or "default_nexus_thread")}} + + try: + final_state = await app.ainvoke(initial_state, config=config) + + # 3. Extract final response + final_msg = final_state["messages"][-1].content + sources = final_state.get("sources", []) + + # Sanitize response: Remove internal diagnostic markers or raw system paths + sanitized_msg = final_msg.replace("[INTERNAL_DIAGNOSTIC]", "").strip() + + return NexusResponse( + answer=sanitized_msg, + sources=sources + ) + except Exception as e: + import logging + logger = logging.getLogger(__name__) + logger.exception(f"Nexus Master Failure: {str(e)}") + # NEVER leak raw traceback or internal DB error to final output + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Nexus Master encountered an unexpected internal error. Please contact 3SC Support." + ) + +@router.get("/history", response_model=NexusHistoryResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + ADMIN_ROLES))]) +async def get_nexus_history( + db: AsyncSession = Depends(get_db), + current_user: User = Depends(get_current_user) +) -> Any: + """ + Retrieve the last 50 Master Agent interactions for the current workspace. + """ + stmt = ( + select(NexusInteraction) + .where( + NexusInteraction.workspace_id == current_user.workspace_id + ) + .order_by(desc(NexusInteraction.created_at)) + .limit(50) + ) + result = await db.execute(stmt) + interactions = result.scalars().all() + + return { + "interactions": interactions, + "count": len(interactions) + } + +@router.get("/thread/{thread_id}", response_model=List[AINodeInteraction], dependencies=[Depends(require_roles(ALL_SC_ROLES + ADMIN_ROLES))]) +async def get_nexus_thread_audit( + thread_id: UUID, + db: AsyncSession = Depends(get_db), + current_user: User = Depends(get_current_user) +) -> Any: + """ + Retrieve the full forensic audit trail for a specific conversational thread. + """ + stmt = ( + select(NexusInteraction) + .where( + NexusInteraction.thread_id == thread_id, + NexusInteraction.workspace_id == current_user.workspace_id + ) + .order_by(NexusInteraction.created_at.asc()) + ) + result = await db.execute(stmt) + interactions = result.scalars().all() + + if not interactions: + raise HTTPException(status_code=404, detail="Thread not found or access denied") + + return interactions diff --git a/api/v1/notifications.py b/api/v1/notifications.py new file mode 100644 index 0000000000000000000000000000000000000000..5c84a42398bf8e0ce489ced737568b9d4529400e --- /dev/null +++ b/api/v1/notifications.py @@ -0,0 +1,65 @@ +from typing import List, Any +from uuid import UUID +from datetime import datetime +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, update, desc + +from core.deps import get_db, get_current_user +from models.user import User +from models.notification import Notification +from schemas.notification import NotificationResponse + +router = APIRouter() + +@router.get("/", response_model=List[NotificationResponse]) +async def list_notifications( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Fetch notifications for the current user, most recent first.""" + stmt = select(Notification).where( + Notification.user_id == current_user.id, + Notification.workspace_id == current_user.workspace_id, + Notification.deleted_at.is_(None) + ).order_by(desc(Notification.created_at)).limit(50) + + result = await db.execute(stmt) + return result.scalars().all() + +@router.patch("/mark-read", status_code=status.HTTP_200_OK) +async def mark_notifications_read( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Mark all unread notifications as read for current user.""" + stmt = update(Notification).where( + Notification.user_id == current_user.id, + Notification.is_read == False + ).values(is_read=True) + + await db.execute(stmt) + await db.commit() + return {"status": "success"} + +@router.delete("/{notification_id}", status_code=status.HTTP_200_OK) +async def delete_notification( + notification_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Soft-delete a single notification.""" + stmt = select(Notification).where( + Notification.id == notification_id, + Notification.user_id == current_user.id + ) + result = await db.execute(stmt) + notif = result.scalar_one_or_none() + + if not notif: + raise HTTPException(status_code=404, detail="Notification not found") + + notif.deleted_at = datetime.utcnow() + db.add(notif) + await db.commit() + return {"status": "deleted"} diff --git a/api/v1/projects.py b/api/v1/projects.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a66c19ffa15386c5b90b96372c734fc23fc9e3 --- /dev/null +++ b/api/v1/projects.py @@ -0,0 +1,116 @@ +""" +Project endpoints: CRUD for projects within a workspace. +""" + +from datetime import datetime +from typing import Any, List, Optional +from uuid import UUID +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from core.deps import get_db, get_current_user +from core.permissions import require_roles, ADMIN_ROLES +from models.user import User +from models.project import Project +from schemas.project import ProjectCreate, ProjectResponse, ProjectUpdate + +router = APIRouter() + +@router.post("/", response_model=ProjectResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def create_project( + payload: ProjectCreate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Admin only: create a new project in the workspace.""" + new_project = Project( + name=payload.name, + description=payload.description, + workspace_id=current_user.workspace_id + ) + db.add(new_project) + await db.commit() + await db.refresh(new_project) + return new_project + +@router.get("/", response_model=List[ProjectResponse]) +async def list_projects( + skip: int = 0, limit: int = 100, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """List all projects in the workspace.""" + stmt = select(Project).where( + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ).offset(skip).limit(limit) + result = await db.execute(stmt) + return result.scalars().all() + +@router.get("/{project_id}", response_model=ProjectResponse) +async def get_project( + project_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get a specific project.""" + stmt = select(Project).where( + Project.id == project_id, + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ) + result = await db.execute(stmt) + project = result.scalar_one_or_none() + if not project: + raise HTTPException(status_code=404, detail="Project not found") + return project + +@router.patch("/{project_id}", response_model=ProjectResponse, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def update_project( + project_id: UUID, + payload: ProjectUpdate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Admin only: update project details.""" + stmt = select(Project).where( + Project.id == project_id, + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ) + result = await db.execute(stmt) + project = result.scalar_one_or_none() + if not project: + raise HTTPException(status_code=404, detail="Project not found") + + for field, value in payload.model_dump(exclude_unset=True).items(): + setattr(project, field, value) + + db.add(project) + await db.commit() + await db.refresh(project) + return project + +@router.delete("/{project_id}", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def delete_project( + project_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Admin only: Soft Delete a project.""" + stmt = select(Project).where( + Project.id == project_id, + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ) + result = await db.execute(stmt) + project = result.scalar_one_or_none() + if not project: + raise HTTPException(status_code=404, detail="Project not found") + + project.deleted_at = datetime.utcnow() + project.deleted_by_id = current_user.id + db.add(project) + await db.commit() + return {"status": "deleted"} diff --git a/api/v1/reports.py b/api/v1/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..f82670a311ab430f7d16c4060fe4b4dd83aa88ca --- /dev/null +++ b/api/v1/reports.py @@ -0,0 +1,230 @@ +""" +Reporting & Analytics endpoints. +""" + +from typing import Any, Dict, List +from fastapi import APIRouter, Depends +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, func, and_, String, cast +from datetime import datetime, timedelta + +from core.deps import get_db, get_current_user +from core.permissions import require_roles, EVERYBODY_ROLES, ALL_SC_ROLES +from models.user import User, UserRole +from models.ticket import Ticket, TicketStatus +from models.feedback import Feedback + +router = APIRouter() + +@router.get("/volume", dependencies=[Depends(require_roles(EVERYBODY_ROLES))]) +async def get_volume_trends( + workspace_id: str = None, + days: int = 30, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get ticket volume trends over time.""" + from models.workspace import Workspace + is_staff = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] + + # Identify target workspace (staff can override, others default to their own) + target_ws = current_user.workspace_id + if is_staff and workspace_id: + target_ws = workspace_id + + since = datetime.utcnow() - timedelta(days=days) + stmt = ( + select(func.date(Ticket.created_at), func.count(Ticket.id)) + .where( + Ticket.workspace_id == target_ws, + Ticket.created_at >= since, + Ticket.deleted_at.is_(None) + ) + .group_by(func.date(Ticket.created_at)) + .order_by(func.date(Ticket.created_at)) + ) + result = await db.execute(stmt) + return {str(row[0]): row[1] for row in result.all()} + +@router.get("/csat", dependencies=[Depends(require_roles(EVERYBODY_ROLES))]) +async def get_csat_report( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get CSAT score trends and average.""" + is_staff = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] + target_ws = current_user.workspace_id + if is_staff and workspace_id: + target_ws = workspace_id + + stmt = ( + select(func.avg(Feedback.rating), func.count(Feedback.id)) + .where(Feedback.workspace_id == target_ws) + ) + result = await db.execute(stmt) + avg_rating, count = result.one() + + return { + "average_rating": float(avg_rating) if avg_rating else 0, + "total_responses": count + } + +@router.get("/sla", dependencies=[Depends(require_roles(EVERYBODY_ROLES))]) +async def get_sla_compliance( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + is_staff = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] + target_ws = current_user.workspace_id + if is_staff and workspace_id: + target_ws = workspace_id + # Real logic: Join tickets with their priority-level escalation rules + from models.escalation_rule import EscalationRule + + now = datetime.utcnow() + # 1. Fetch active tickets (unfinished) + resolved tickets (finished) + stmt = ( + select(Ticket, EscalationRule.threshold_minutes) + .join(EscalationRule, and_( + EscalationRule.workspace_id == Ticket.workspace_id, + EscalationRule.priority_level == cast(Ticket.priority, String) + ), isouter=True) + .where( + Ticket.workspace_id == target_ws, + Ticket.deleted_at.is_(None) + ) + ) + res = await db.execute(stmt) + rows = res.all() + + total = len(rows) + if total == 0: + return {"sla_compliance_rate": 1.0, "breached_tickets": 0, "on_time_tickets": 0} + + breached = 0 + for ticket, threshold in rows: + # Default threshold if no rule found (e.g. 24h = 1440m) + limit = threshold if threshold else 1440 + + # Calculate duration + end_time = ticket.resolved_at or now + duration_mins = (end_time - ticket.created_at).total_seconds() / 60 + + if duration_mins > limit: + breached += 1 + + on_time = total - breached + return { + "sla_compliance_rate": round(on_time / total, 2), + "breached_tickets": breached, + "on_time_tickets": on_time + } + +@router.get("/insights", dependencies=[Depends(require_roles(EVERYBODY_ROLES))]) +async def get_ai_service_insights( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get AI-generated service health narrative.""" + from agents.analytics import generate_service_insights + + # 1. Get current SLA metrics + metrics = await get_sla_compliance(workspace_id, current_user, db) + + is_staff = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] + target_ws = current_user.workspace_id + if is_staff and workspace_id: + target_ws = workspace_id + + # 2. Get recent tickets for context (last 48 hours only for SPEED) + since_48h = datetime.utcnow() - timedelta(hours=48) + stmt = ( + select(Ticket) + .where( + Ticket.workspace_id == target_ws, + Ticket.created_at >= since_48h, + Ticket.deleted_at.is_(None) + ) + .order_by(Ticket.created_at.desc()) + ) + result = await db.execute(stmt) + tickets = result.scalars().all() + + now = datetime.utcnow() + ticket_data = [] + for t in tickets: + # Sanitization: Truncate and strip potential internal markers + clean_title = t.title[:50] + if "[" in clean_title and "]" in clean_title: + import re + clean_title = re.sub(r'\[.*?\]', '', clean_title).strip() + + ticket_data.append({ + "priority": t.priority, + "category": t.category or "General", + "duration_mins": round((now - t.created_at).total_seconds() / 60, 1) + }) + + # 3. Generate Narrative + insight_text = await generate_service_insights(metrics, ticket_data) + return {"insights": insight_text, "generated_at": now.isoformat()} + +@router.get("/daily-stats", dependencies=[Depends(require_roles(ALL_SC_ROLES))]) +async def get_daily_stats( + workspace_id: str = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Unified endpoint for daily trends and category distribution (last 30 days).""" + is_staff = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] + target_ws = current_user.workspace_id + if is_staff and workspace_id: + target_ws = workspace_id + + now = datetime.utcnow() + since_30d = now - timedelta(days=30) + + # Group by date and category + stmt = ( + select( + func.date(Ticket.created_at).label('day'), + Ticket.category, + func.count(Ticket.id).label('count') + ) + .where( + Ticket.workspace_id == target_ws, + Ticket.created_at >= since_30d, + Ticket.deleted_at.is_(None) + ) + .group_by(func.date(Ticket.created_at), Ticket.category) + .order_by(func.date(Ticket.created_at)) + ) + result = await db.execute(stmt) + rows = result.all() + + # Format buckets for the last 30 days + buckets = [] + for i in range(30): + # bucket_date is i days ago + bucket_date = (now - timedelta(days=29 - i)).date() + + # Aggregate categories for this day from rows + day_total = 0 + categories = {} + for row in rows: + if row.day == bucket_date: + cat = (row.category or "GENERAL").upper() + categories[cat] = categories.get(cat, 0) + row.count + day_total += row.count + + buckets.append({ + "label": bucket_date.strftime("%m-%d"), + "timestamp": bucket_date.isoformat(), + "total": day_total, + "categories": categories + }) + + return buckets diff --git a/api/v1/system.py b/api/v1/system.py new file mode 100644 index 0000000000000000000000000000000000000000..82dc395f5195cbe36e884488bbae30bdef985d71 --- /dev/null +++ b/api/v1/system.py @@ -0,0 +1,129 @@ +from typing import Any, List, Dict +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, func, desc +from datetime import datetime, timedelta +import asyncio +import time + +from core.deps import get_db, get_current_staff_user, get_arq_pool +from core.config import get_settings +from models.user import User +from models.ai_workflow import AIWorkflow +from models.ai_interaction import AIInteraction +from models.meta_infra_health import MetaInfraHealth, ServiceStatus +from schemas.system import AIWorkflowRead, AIInteractionRead, MetaInfraHealthRead +from arq.connections import ArqRedis + +router = APIRouter() +settings = get_settings() + +@router.get("/status", dependencies=[Depends(get_current_staff_user)]) +async def get_system_status( + db: AsyncSession = Depends(get_db), + arq_pool: ArqRedis = Depends(get_arq_pool) +) -> Dict[str, Any]: + """ + Aggregates real-time health metrics for the core infrastructure nodes. + """ + results = { + "database": {"status": "DOWN", "latency_ms": 0}, + "redis": {"status": "DOWN", "latency_ms": 0, "pending_jobs": 0}, + "ollama": {"status": "DOWN", "latency_ms": 0}, + "timestamp": datetime.utcnow() + } + + # 1. Database Check + start_time = time.perf_counter() + try: + await db.execute(select(1)) + results["database"]["status"] = "UP" + results["database"]["latency_ms"] = round((time.perf_counter() - start_time) * 1000, 2) + except Exception: + results["database"]["status"] = "DOWN" + + # 2. Redis / Arq Check + start_time = time.perf_counter() + try: + # Check pool and queue size + res = await arq_pool.keys("arq:job:*") + results["redis"]["status"] = "UP" + results["redis"]["latency_ms"] = round((time.perf_counter() - start_time) * 1000, 2) + results["redis"]["pending_jobs"] = len(res) + except Exception: + results["redis"]["status"] = "DOWN" + + # 3. Ollama Check + start_time = time.perf_counter() + try: + import httpx + async with httpx.AsyncClient(timeout=2.0) as client: + resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags") + if resp.status_code == 200: + results["ollama"]["status"] = "UP" + results["ollama"]["latency_ms"] = round((time.perf_counter() - start_time) * 1000, 2) + except Exception: + results["ollama"]["status"] = "DOWN" + + return results + +from uuid import UUID +from typing import Any, List, Dict, Optional + +from core.deps import get_db, get_current_staff_user, get_arq_pool +... +@router.get("/workflows", response_model=List[AIWorkflowRead], dependencies=[Depends(get_current_staff_user)]) +async def get_recent_workflows( + db: AsyncSession = Depends(get_db), + ticket_id: Optional[UUID] = None, + offset: int = 0, + limit: int = 20 +) -> List[AIWorkflow]: + """ + Retrieves AI workflows with optional ticket filtering and pagination. + """ + stmt = select(AIWorkflow) + + if ticket_id: + stmt = stmt.where(AIWorkflow.entity_id == ticket_id) + + stmt = stmt.order_by(AIWorkflow.updated_at.desc()).offset(offset).limit(limit) + + result = await db.execute(stmt) + return result.scalars().all() + +@router.get("/interactions", response_model=List[AIInteractionRead], dependencies=[Depends(get_current_staff_user)]) +async def get_recent_interactions( + db: AsyncSession = Depends(get_db), + ticket_id: Optional[UUID] = None, + offset: int = 0, + limit: int = 25 +) -> List[AIInteraction]: + """ + Retrieves granular AI interaction traces with optional ticket filtering and pagination. + """ + stmt = select(AIInteraction) + + if ticket_id: + stmt = stmt.where(AIInteraction.ticket_id == ticket_id) + + stmt = stmt.order_by(AIInteraction.created_at.desc()).offset(offset).limit(limit) + + result = await db.execute(stmt) + return result.scalars().all() + +@router.get("/history", response_model=List[MetaInfraHealthRead], dependencies=[Depends(get_current_staff_user)]) +async def get_performance_history( + db: AsyncSession = Depends(get_db) +) -> List[MetaInfraHealth]: + """ + Retrieves the last 24 hours of infrastructure health data. + """ + since = datetime.utcnow() - timedelta(hours=24) + stmt = ( + select(MetaInfraHealth) + .where(MetaInfraHealth.created_at >= since) + .order_by(MetaInfraHealth.created_at.asc()) + ) + result = await db.execute(stmt) + return result.scalars().all() diff --git a/api/v1/tickets.py b/api/v1/tickets.py new file mode 100644 index 0000000000000000000000000000000000000000..546dcc9c4ea8ce40065e699b34f264f4e4387980 --- /dev/null +++ b/api/v1/tickets.py @@ -0,0 +1,777 @@ +""" +Ticket endpoints: CRUD, status transitions, and assignments. +""" + +from datetime import datetime, timedelta +import asyncio +import time +import uuid +from uuid import UUID +from typing import Any, List, Optional +from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks +from fastapi.encoders import jsonable_encoder +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, update, func, desc, or_, cast, String + +from arq import ArqRedis +from core.deps import get_db, get_current_user, get_arq_pool +from core.permissions import require_roles, ALL_SC_ROLES, ADMIN_ROLES, ALL_CUSTOMER_ROLES +from core.security import get_password_hash +from core.logging import get_logger +from models.user import User, UserRole +from models.project import Project +from models.ticket import Ticket, TicketStatus, ALLOWED_TRANSITIONS, TicketPriority +from models.audit_log import AuditLog +from models.escalation_rule import EscalationRule +from schemas.ticket import TicketCreate, TicketUpdate, TicketResponse, TicketSearchResponse, TicketSearchResult +from agents.workflow import run_ai_workflow +from core.tasks import generate_ticket_embedding, send_dual_notification +from core.llm import get_text_embeddings +from models.attachment import Attachment +from models.message import Message +from models.feedback import Feedback + +router = APIRouter() +logger = get_logger(__name__) + +async def sanitize_ticket_response(ticket: Ticket, user: User, db: AsyncSession) -> Ticket: + """Helper to inject role-based summary, names, and mask internal metadata.""" + from sqlalchemy import select + from models.user import User, UserRole + + is_staff = user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + + # 1. Summary Injection + if ticket.ai_metadata and "summaries" in ticket.ai_metadata: + summaries = ticket.ai_metadata.get("summaries", {}) + summary_val = summaries.get("internal_summary" if is_staff else "customer_summary") + setattr(ticket, "summary", summary_val) + else: + setattr(ticket, "summary", None) + + # 2. Assignee Name Lookup + if ticket.assigned_to: + stmt = select(User.full_name).where(User.id == ticket.assigned_to) + res = await db.execute(stmt) + setattr(ticket, "assigned_name", res.scalar_one_or_none()) + else: + setattr(ticket, "assigned_name", None) + + # 3. Similar Articles Extraction + articles = [] + if ticket.ai_metadata and "suggestion_sources" in ticket.ai_metadata: + articles = ticket.ai_metadata["suggestion_sources"].get("kb_articles", []) + setattr(ticket, "similar_articles", articles) + + # 4. Resolution & Resolver Fallbacks (UI Safeguard) + is_resolved = ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED] + + # Resolver Name lookup with fallback to SC_ADMIN + if ticket.resolved_by: + stmt = select(User.full_name).where(User.id == ticket.resolved_by) + res = await db.execute(stmt) + setattr(ticket, "resolved_by_name", res.scalar_one_or_none()) + elif is_resolved: + # Fallback to any active SC_ADMIN in this workspace + admin_stmt = select(User.full_name).where( + User.workspace_id == ticket.workspace_id, + User.role == UserRole.SC_ADMIN, + User.deleted_at.is_(None) + ).limit(1) + admin_res = await db.execute(admin_stmt) + setattr(ticket, "resolved_by_name", admin_res.scalar_one_or_none() or "Nexus Support Admin") + else: + setattr(ticket, "resolved_by_name", None) + + # Resolution text fallback + if is_resolved and not ticket.resolution_text: + setattr(ticket, "resolution_text", "This issue has been resolved. Thanks!") + + # Resolved at fallback (avoid "TBD") + if is_resolved and not ticket.resolved_at: + setattr(ticket, "resolved_at", ticket.sla_deadline or ticket.created_at) + + # 5. Escalation Lead Lookup + if ticket.is_escalated: + lead_stmt = select(User).where( + User.workspace_id == ticket.workspace_id, + User.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]), + User.deleted_at.is_(None) + ).limit(1) + lead_res = await db.execute(lead_stmt) + lead = lead_res.scalar_one_or_none() + if lead: + setattr(ticket, "escalated_to_name", lead.full_name) + setattr(ticket, "escalated_to_id", lead.id) + + # 6. Duplicate Title Lookup + if ticket.duplicate_of_id: + dup_stmt = select(Ticket.title).where(Ticket.id == ticket.duplicate_of_id) + dup_res = await db.execute(dup_stmt) + setattr(ticket, "duplicate_of_title", dup_res.scalar_one_or_none()) + else: + setattr(ticket, "duplicate_of_title", None) + + # 7. Metadata Sanitization & Internal Flag Injection + # We join with the creator role to determine if this is an "internal" staff-only ticket + creator_stmt = select(User).where(User.id == ticket.created_by) + creator_res = await db.execute(creator_stmt) + creator = creator_res.scalar_one_or_none() + + creator_role = creator.role if creator else None + is_internal = creator_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + + # Inject creator name for frontend filtering/display + setattr(ticket, "creator_name", creator.full_name if creator else "System") + + # Build a sanitized metadata dict + raw_meta = ticket.ai_metadata or {} + sanitized_meta = { + "is_internal": is_internal, + "messages_count": raw_meta.get("messages_count", 0), + "rating": raw_meta.get("rating") + } + + if is_staff: + # Staff get everything + setattr(ticket, "ai_metadata", raw_meta | sanitized_meta) + else: + # Customers get only sanitized + setattr(ticket, "ai_metadata", sanitized_meta) + + return ticket + +@router.post("/", response_model=TicketResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ALL_CUSTOMER_ROLES + ADMIN_ROLES))]) +async def create_ticket( + payload: TicketCreate, + background_tasks: BackgroundTasks, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """Create a new ticket in the current user's workspace.""" + if payload.project_id: + stmt = select(Project).where( + Project.id == payload.project_id, + Project.workspace_id == current_user.workspace_id, + Project.deleted_at.is_(None) + ) + result = await db.execute(stmt) + if not result.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="Project not found") + + # 1. Calculate SLA: Use EscalationRules if present, else 2 days + ticket_priority = payload.priority or TicketPriority.P2 + sla_deadline = payload.sla_deadline + + if not sla_deadline: + # Check for a matching rule + rule_stmt = select(EscalationRule).where( + EscalationRule.workspace_id == current_user.workspace_id, + EscalationRule.priority_level == cast(ticket_priority, String) + ) + rule_res = await db.execute(rule_stmt) + rule = rule_res.scalar_one_or_none() + + if rule: + sla_deadline = datetime.utcnow() + timedelta(minutes=rule.threshold_minutes) + logger.info(f"Dynamic SLA applied for {ticket_priority}: {rule.threshold_minutes}m threshold found.") + else: + sla_deadline = datetime.utcnow() + timedelta(days=2) + logger.info(f"No SLA rule found for {ticket_priority}, using 48h default.") + + new_ticket = Ticket( + id=uuid.uuid4(), + workspace_id=current_user.workspace_id, + project_id=payload.project_id, + title=payload.title, + description=payload.description, + priority=ticket_priority, + category=payload.category, + created_by=current_user.id, + status=TicketStatus.OPEN, + sla_deadline=sla_deadline + ) + db.add(new_ticket) + + audit = AuditLog( + workspace_id=current_user.workspace_id, + entity_type="ticket", + entity_id=new_ticket.id, + action="create", + user_id=current_user.id, + new_value=payload.model_dump() + ) + db.add(audit) + await db.commit() + await db.refresh(new_ticket) + + # --- Observability: Record Ticket Inception --- + from core.observability import record_workflow_step + await record_workflow_step( + db, + entity_id=new_ticket.id, + workspace_id=new_ticket.workspace_id, + workflow_type="LIFECYCLE", + step_name="TICKET_INCEPTION", + input_data={"title": new_ticket.title}, + output_data={"status": "registered"}, + current_stage="INITIAL_INGESTION" + ) + await db.commit() + + ticket_data = { + "id": str(new_ticket.id), + "workspace_id": str(new_ticket.workspace_id), + "title": new_ticket.title, + "description": new_ticket.description + } + await arq_pool.enqueue_job('run_ai_workflow', ticket_data, _job_timeout=900) + + background_tasks.add_task(generate_ticket_embedding, None, new_ticket.id) + + # 3. Notification for initial assignment (if present) + if new_ticket.assigned_to: + background_tasks.add_task( + send_dual_notification, + None, + new_ticket.assigned_to, + new_ticket.workspace_id, + "New Ticket Assigned", + f"A new ticket '{new_ticket.title}' has been assigned to you." + ) + + await manager.broadcast_to_workspace( + current_user.workspace_id, + {"event": "ticket_created", "ticket_id": str(new_ticket.id), "title": new_ticket.title} + ) + + logger.info(f"Ticket created: {new_ticket.id} by user {current_user.id} in workspace {current_user.workspace_id}") + + return await sanitize_ticket_response(new_ticket, current_user, db) + +@router.get("/search", response_model=TicketSearchResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + ALL_CUSTOMER_ROLES))]) +async def search_tickets( + q: str, + project_id: Optional[UUID] = None, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Advanced Hybrid Search for Tickets (0.2 Threshold). Partitioned by role.""" + import uuid + import time + from core.observability import record_workflow_step + search_id = uuid.uuid4() + start_time = time.perf_counter() + + is_staff = current_user.role in ALL_SC_ROLES + + # 1. Semantic Search (Text) + embed_start = time.perf_counter() + text_model = get_text_embeddings() + query_vector = await text_model.aembed_query(q) + await record_workflow_step( + db, search_id, current_user.workspace_id, "SEARCH", + "QUERY_EMBEDDING", + input_data={"q": q}, + duration_ms=(time.perf_counter() - embed_start) * 1000 + ) + + sem_start = time.perf_counter() + semantic_stmt = ( + select( + Ticket, + (1 - Ticket.embedding.cosine_distance(query_vector)).label("sim_score") + ) + .where( + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None), + Ticket.embedding.isnot(None) + ) + ) + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + semantic_stmt = ( + semantic_stmt.join(Creator, Ticket.created_by == Creator.id) + .where(Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])) + ) + if project_id: semantic_stmt = semantic_stmt.where(Ticket.project_id == project_id) + semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20) + + # 2. Visual Search (Attachments) + vis_start = time.perf_counter() + visual_stmt = ( + select( + Ticket, + func.ts_rank( + func.to_tsvector('english', Attachment.ai_caption), + func.plainto_tsquery('english', q) + ).label("vis_score") + ) + .join(Attachment, Ticket.id == Attachment.ticket_id) + .where( + Ticket.workspace_id == current_user.workspace_id, + Attachment.ai_caption.isnot(None), + func.to_tsvector('english', Attachment.ai_caption).op("@@")(func.plainto_tsquery('english', q)) + ) + ) + if not is_staff: + from sqlalchemy.orm import aliased + Creator = aliased(User) + visual_stmt = ( + visual_stmt.join(Creator, Ticket.created_by == Creator.id) + .where(Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])) + ) + if project_id: visual_stmt = visual_stmt.where(Ticket.project_id == project_id) + visual_stmt = visual_stmt.limit(10) + + # Execute Parallel + sem_res, vis_res = await asyncio.gather(db.execute(semantic_stmt), db.execute(visual_stmt)) + + hits = sem_res.all() + v_hits = vis_res.all() + await record_workflow_step( + db, search_id, current_user.workspace_id, "SEARCH", + "RETRIEVAL_COMPLETE", + output_data={"semantic_hits": len(hits), "visual_hits": len(v_hits)}, + duration_ms=(time.perf_counter() - sem_start) * 1000 + ) + + # 3. Hybrid Fusion + fusion_start = time.perf_counter() + ticket_scores = {} + for ticket, sim in hits: + score = sim if sim is not None else 0.0 + if ticket.id not in ticket_scores: + ticket_scores[ticket.id] = {"obj": ticket, "score": score, "type": "textual"} + else: + ticket_scores[ticket.id]["score"] = max(ticket_scores[ticket.id].get("score", 0.0), score) + + for ticket, vis_score in v_hits: + raw_vis = vis_score if vis_score is not None else 0.0 + boosted_score = min(raw_vis * 1.5, 1.0) + if ticket.id not in ticket_scores: + ticket_scores[ticket.id] = {"obj": ticket, "score": boosted_score, "type": "visual"} + else: + ticket_scores[ticket.id]["score"] = max(ticket_scores[ticket.id].get("score", 0.0), boosted_score) + ticket_scores[ticket.id]["type"] = "hybrid" + + THRESHOLD = 0.2 + final_results = [] + for t_id, data in ticket_scores.items(): + score = float(data.get("score") or 0.0) + if score >= THRESHOLD: + t_obj = data["obj"] + result_item = TicketSearchResult( + id=t_obj.id, + title=t_obj.title, + description=t_obj.description, + status=t_obj.status, + priority=t_obj.priority, + project_id=t_obj.project_id, + score=round(score, 3) + ) + final_results.append(result_item) + + final_results.sort(key=lambda x: x.score, reverse=True) + + await record_workflow_step( + db, search_id, current_user.workspace_id, "SEARCH", + "HYBRID_FUSION_COMPLETE", + output_data={"final_result_count": len(final_results)}, + duration_ms=(time.perf_counter() - fusion_start) * 1000, + current_stage="RESULTS_DELIVERED" + ) + + await db.commit() # Commit lifecycle for search trace + + end_time = time.perf_counter() + return jsonable_encoder({ + "results": final_results[:5], + "search_time_s": round(end_time - start_time, 3), + "search_trace_id": str(search_id) + }) + +@router.get("/categories", response_model=List[str], dependencies=[Depends(require_roles(ALL_SC_ROLES + ALL_CUSTOMER_ROLES))]) +async def list_ticket_categories( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Retrieve all unique ticket categories for this workspace.""" + stmt = select(func.distinct(Ticket.category)).where( + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + categories = [c for c in result.scalars().all()] + # Normalize nulls to "N/A" + normalized = sorted([c if c else "N/A" for c in categories]) + return normalized + +@router.get("/statuses", response_model=List[str], dependencies=[Depends(require_roles(ALL_SC_ROLES + ALL_CUSTOMER_ROLES))]) +async def list_ticket_statuses() -> Any: + """Retrieve all valid ticket statuses from the core enum.""" + return [s.value for s in TicketStatus] + +@router.get("/", response_model=List[TicketResponse]) +async def list_tickets( + skip: int = 0, limit: int = 100, + status_filter: Optional[TicketStatus] = None, + category_filter: Optional[str] = None, + priority_filter: Optional[TicketPriority] = None, + project_id: Optional[UUID] = None, + is_my_tickets: bool = False, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """List tickets for the current workspace with advanced filtering.""" + stmt = select(Ticket).where( + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + if status_filter: + stmt = stmt.where(Ticket.status == status_filter) + if priority_filter: + stmt = stmt.where(Ticket.priority == priority_filter) + if project_id: + stmt = stmt.where(Ticket.project_id == project_id) + if category_filter: + if category_filter == "N/A": + stmt = stmt.where(Ticket.category.is_(None)) + else: + stmt = stmt.where(Ticket.category == category_filter) + + is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + if not is_staff: + # Customers can ONLY see tickets they created personally + stmt = stmt.where(Ticket.created_by == current_user.id) + + if is_my_tickets and is_staff: + # Staff can filter to see only their own created tickets if requested + stmt = stmt.where(Ticket.created_by == current_user.id) + + stmt = stmt.offset(skip).limit(limit).order_by(Ticket.created_at.desc()) + result = await db.execute(stmt) + tickets = result.scalars().all() + return [await sanitize_ticket_response(t, current_user, db) for t in tickets] + +@router.get("/{ticket_id}", response_model=TicketResponse) +async def get_ticket( + ticket_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get a specific ticket by ID. Enforces ownership for customers.""" + is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + # Customers can ONLY access tickets they created + 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") + return await sanitize_ticket_response(ticket, current_user, db) + +@router.patch("/{ticket_id}", response_model=TicketResponse) +async def update_ticket( + ticket_id: UUID, + payload: TicketUpdate, + background_tasks: BackgroundTasks, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + arq_pool: Any = Depends(get_arq_pool) +) -> Any: + """Update a ticket. Enforces ownership for customers.""" + is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + + if not is_staff: + # Customers can ONLY update tickets they created + 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") + + update_data = payload.model_dump(exclude_unset=True) + + if "assigned_to" in update_data and update_data["assigned_to"]: + assignee_id = update_data["assigned_to"] + assignee_stmt = select(User).where( + User.id == assignee_id, + User.workspace_id == current_user.workspace_id, + User.is_active == True, + User.deleted_at.is_(None) + ) + assignee_res = await db.execute(assignee_stmt) + if not assignee_res.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="Target assignee not found or is inactive") + + if "status" in update_data: + new_status = update_data["status"] + if new_status != ticket.status: + if current_user.role not in [UserRole.SC_LEAD, UserRole.SC_ADMIN]: + allowed = ALLOWED_TRANSITIONS.get(ticket.status, []) + if new_status not in allowed: + raise HTTPException(status_code=400, detail=f"Invalid transition to {new_status}") + + # Logic for Resolution Capture (Persistent Layer) + if new_status in [TicketStatus.RESOLVED, TicketStatus.CLOSED] and ticket.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED]: + ticket.resolved_at = datetime.utcnow() + ticket.resolved_by = current_user.id + if not update_data.get("resolution_text"): + ticket.resolution_text = "This issue has been resolved. Thanks!" + + if "priority" in update_data and update_data["priority"] != ticket.priority: + # Recalculate SLA + rule_stmt = select(EscalationRule).where( + EscalationRule.workspace_id == current_user.workspace_id, + EscalationRule.priority_level == cast(update_data["priority"], String) + ) + rule_res = await db.execute(rule_stmt) + rule = rule_res.scalar_one_or_none() + + if rule: + # Use original created_at for SLA math + ticket.sla_deadline = ticket.created_at + timedelta(minutes=rule.threshold_minutes) + logger.info(f"Priority changed to {update_data['priority']}, SLA updated to {ticket.sla_deadline}") + else: + # Fallback to 48h from creation + ticket.sla_deadline = ticket.created_at + timedelta(days=2) + logger.info(f"Priority changed to {update_data['priority']}, no rule found, 48h default applied.") + + old_values = {field: getattr(ticket, field) for field in update_data.keys()} + old_assignee = ticket.assigned_to + for field, value in update_data.items(): + setattr(ticket, field, value) + + db.add(ticket) + + # Notify if assignee changed + if "assigned_to" in update_data and str(old_assignee) != str(update_data["assigned_to"]): + background_tasks.add_task( + send_dual_notification, + None, + update_data["assigned_to"], + ticket.workspace_id, + "Ticket Reassigned", + f"Ticket '{ticket.title}' has been reassigned to you by {current_user.id}." + ) + + audit = AuditLog( + workspace_id=current_user.workspace_id, + entity_type="ticket", + entity_id=ticket.id, + action="update", + user_id=current_user.id, + old_value=old_values, + new_value=payload.model_dump(exclude_unset=True) + ) + db.add(audit) + if "assigned_to" in update_data: + logger.info(f"Ticket {ticket.id} assignment changed to {update_data['assigned_to']} by {current_user.id}") + if "status" in update_data: + logger.info(f"Ticket {ticket.id} status changed to {update_data['status']} by {current_user.id}") + + await db.commit() + await db.refresh(ticket) + + # 3. Trigger re-processing if description or title changed + if "description" in update_data or "title" in update_data: + ticket_data = { + "id": str(ticket.id), + "workspace_id": str(ticket.workspace_id), + "title": ticket.title, + "description": ticket.description + } + await arq_pool.enqueue_job('run_ai_workflow', ticket_data, _job_timeout=900) + background_tasks.add_task(generate_ticket_embedding, None, ticket.id) + logger.info(f"Ticket {ticket_id} content updated, re-indexing task enqueued.") + + # Trigger auto-summary if status moved to terminal + if "status" in update_data and update_data["status"] in [TicketStatus.RESOLVED, TicketStatus.CLOSED]: + await arq_pool.enqueue_job("auto_summarize_ticket", ticket.id) + + return await sanitize_ticket_response(ticket, current_user, db) + +@router.delete("/{ticket_id}", status_code=status.HTTP_200_OK) +async def delete_ticket( + ticket_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Soft Delete a ticket.""" + if 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.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + if not ticket: + raise HTTPException(status_code=404, detail="Ticket not found") + + ticket.deleted_at = datetime.utcnow() + ticket.deleted_by_id = current_user.id + + # 1. Cascade to Messages + msg_stmt = ( + update(Message) + .where(Message.ticket_id == ticket_id) + .values( + deleted_at=ticket.deleted_at, + deleted_by_id=current_user.id + ) + ) + await db.execute(msg_stmt) + + # 2. Cascade to Attachments + att_stmt = ( + update(Attachment) + .where(Attachment.ticket_id == ticket_id) + .values( + deleted_at=ticket.deleted_at, + deleted_by_id=current_user.id + ) + ) + await db.execute(att_stmt) + + db.add(ticket) + await db.commit() + logger.info(f"Ticket soft-deleted: {ticket_id} by user {current_user.id}") + return {"status": "deleted"} + +@router.post("/{ticket_id}/reprocess", status_code=status.HTTP_202_ACCEPTED) +async def reprocess_ticket_ai( + ticket_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db), + arq_pool: ArqRedis = Depends(get_arq_pool) +) -> Any: + """ + Manually re-trigger the AI workflow for an existing ticket. + """ + if current_user.role not in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.CUSTOMER_ADMIN]: + raise HTTPException(status_code=403, detail="Permission denied") + + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + if not ticket: + raise HTTPException(status_code=404, detail="Ticket not found") + + from core.observability import record_workflow_step + # 0. Record Reprocess Event in Trace + await record_workflow_step( + db, ticket.id, ticket.workspace_id, "LIFECYCLE", + "REPROCESS_TRIGGERED", + input_data={"requested_by": str(current_user.id)}, + current_stage="REPROCESSING" + ) + + # 1. Prepare payload + ticket_data = { + "id": str(ticket.id), + "workspace_id": str(ticket.workspace_id), + "title": ticket.title, + "description": ticket.description + } + + # 2. Trigger Full AI Pipeline (Triage + Indexing) + triage_job = await arq_pool.enqueue_job('run_ai_workflow', ticket_data, _job_timeout=900) + indexing_job = await arq_pool.enqueue_job('generate_ticket_embedding', ticket.id) + + logger.info(f"Manual AI re-trigger: Ticket {ticket_id} (Triage: {triage_job.job_id}, Indexing: {indexing_job.job_id})") + return { + "status": "enqueued", + "triage_job_id": triage_job.job_id, + "indexing_job_id": indexing_job.job_id, + "ticket_id": str(ticket.id) + } + +@router.post("/{ticket_id}/escalate", response_model=TicketResponse) +async def escalate_ticket( + ticket_id: UUID, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Manual Escalation: Force priority to P0 and mark as escalated.""" + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.workspace_id == current_user.workspace_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + + if not ticket: + raise HTTPException(status_code=404, detail="Ticket not found") + + if ticket.is_escalated: + raise HTTPException(status_code=400, detail="Ticket is already escalated") + + # 1. Update State + old_priority = ticket.priority + ticket.is_escalated = datetime.utcnow() + ticket.priority = TicketPriority.P0 + db.add(ticket) + + # 2. Add System Message + sys_msg = Message( + id=uuid.uuid4(), + workspace_id=ticket.workspace_id, + ticket_id=ticket.id, + sender_id=current_user.id, # Attributed to the user who performed the action + content=f"🚨 **Manual Escalation triggered by {current_user.full_name}**. Priority elevated to P0.", + is_internal=False + ) + db.add(sys_msg) + + # 3. Log Audit + audit = AuditLog( + workspace_id=current_user.workspace_id, + entity_type="ticket", + entity_id=ticket.id, + action="escalation", + user_id=current_user.id, + old_value={"priority": old_priority}, + new_value={"priority": "P0", "is_escalated": ticket.is_escalated.isoformat()} + ) + db.add(audit) + + await db.commit() + await db.refresh(ticket) + + # 4. Notify via WebSocket + await manager.broadcast_to_workspace( + current_user.workspace_id, + {"event": "ticket_escalated", "ticket_id": str(ticket.id), "title": ticket.title} + ) + + logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}") + + # Refresh to pick up lead info in sanitizer + return await sanitize_ticket_response(ticket, current_user, db) diff --git a/api/v1/users.py b/api/v1/users.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3dcbc9ac3ea4db1d9e3e8e9293d3848fe2be79 --- /dev/null +++ b/api/v1/users.py @@ -0,0 +1,171 @@ +""" +User endpoints: profile and admin management. +""" + +from datetime import datetime +from typing import Any, List +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from core.deps import get_db, get_current_user +from core.permissions import require_roles, ADMIN_ROLES +from core.security import get_password_hash +from core.logging import get_logger +from models.user import User, UserRole +from schemas.user import UserResponse, UserUpdate, UserAdminUpdate, UserCreate + +router = APIRouter() +logger = get_logger(__name__) + +@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED) +async def create_workspace_user( + payload: UserCreate, + current_user: User = Depends(require_roles(ADMIN_ROLES)), + db: AsyncSession = Depends(get_db) +) -> Any: + """ + Administratively create a new user within the current workspace. + - CUSTOMER_ADMIN can create CUSTOMER_ADMIN and CUSTOMER_USER. + - SC_ADMIN can create SC_LEAD and SC_AGENT. + """ + # 1. Role Validation + allowed_roles = [] + if current_user.role == UserRole.CUSTOMER_ADMIN: + allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] + elif current_user.role == UserRole.SC_ADMIN: + allowed_roles = [UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SC_ADMIN] + + if payload.role not in allowed_roles: + raise HTTPException( + status_code=403, + detail=f"You do not have permission to assign the role: {payload.role}" + ) + + # 2. Duplicate Check (excluding soft-deleted users) + stmt = select(User).where(User.email == payload.email, User.deleted_at.is_(None)) + result = await db.execute(stmt) + if result.scalar_one_or_none(): + raise HTTPException(status_code=400, detail="User with this email already exists") + + # 3. Creation + new_user = User( + email=payload.email, + hashed_password=get_password_hash(payload.password), + full_name=payload.full_name, + role=payload.role, + workspace_id=current_user.workspace_id, + is_active=True + ) + db.add(new_user) + await db.commit() + await db.refresh(new_user) + logger.info(f"User created: {new_user.email} (Role: {new_user.role}) by admin {current_user.id}") + return new_user + +@router.get("/me", response_model=UserResponse) +async def read_user_me(current_user: User = Depends(get_current_user)) -> Any: + return current_user + +@router.patch("/me", response_model=UserResponse) +async def update_user_me( + payload: UserUpdate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + for field, value in payload.model_dump(exclude_unset=True).items(): + setattr(current_user, field, value) + db.add(current_user) + await db.commit() + await db.refresh(current_user) + return current_user + +@router.get("/", response_model=List[UserResponse], dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def list_workspace_users( + skip: int = 0, limit: int = 100, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + # Define allowed roles based on requester category + if current_user.role == UserRole.CUSTOMER_ADMIN: + allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] + elif current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD]: + allowed_roles = [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + else: + # Default to themselves only or empty if they managed to call this + allowed_roles = [current_user.role] + + stmt = select(User).where( + User.workspace_id == current_user.workspace_id, + User.role.in_(allowed_roles), + User.is_active == True, + User.deleted_at.is_(None) + ).offset(skip).limit(limit) + result = await db.execute(stmt) + return result.scalars().all() + +@router.delete("/{user_id}", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def deactivate_user_v3( + user_id: str, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + stmt = select(User).where( + User.id == user_id, + User.workspace_id == current_user.workspace_id, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + user = result.scalar_one_or_none() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + user.is_active = False + user.deleted_at = datetime.utcnow() + user.deleted_by_id = current_user.id + db.add(user) + await db.commit() + logger.info(f"User deactivated/soft-deleted: {user_id} by admin {current_user.id}") + return {"status": "deleted"} +@router.patch("/{user_id}", response_model=UserResponse, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def update_user_admin( + user_id: str, + payload: UserAdminUpdate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """ + Administratively update another user's role or status. + Uses the same hierarchy logic as creation. + """ + stmt = select(User).where( + User.id == user_id, + User.workspace_id == current_user.workspace_id, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + user = result.scalar_one_or_none() + if not user: + raise HTTPException(status_code=404, detail="User not found") + + update_data = payload.model_dump(exclude_unset=True) + + # Role validation logic + if "role" in update_data: + allowed_roles = [] + if current_user.role == UserRole.CUSTOMER_ADMIN: + allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] + elif current_user.role == UserRole.SC_ADMIN: + allowed_roles = [UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SC_ADMIN] + + if update_data["role"] not in allowed_roles: + raise HTTPException(status_code=403, detail=f"Permission denied for role: {update_data['role']}") + + for field, value in update_data.items(): + setattr(user, field, value) + + db.add(user) + await db.commit() + await db.refresh(user) + logger.info(f"User {user_id} updated by admin {current_user.id}: {update_data}") + return user diff --git a/api/v1/websockets.py b/api/v1/websockets.py new file mode 100644 index 0000000000000000000000000000000000000000..50e8704e7b1fee4bb8a0c52abc37d4f343cc2932 --- /dev/null +++ b/api/v1/websockets.py @@ -0,0 +1,72 @@ +""" +WebSocket endpoints for real-time ticket updates. +""" + +from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends, Query +from uuid import UUID +from core.websockets import manager +from core.security import decode_access_token +from core.database import async_session_factory +from sqlalchemy import select +from models.user import User + +router = APIRouter() + +@router.websocket("/ws/{workspace_id}") +async def ticket_events( + websocket: WebSocket, + workspace_id: UUID, + token: str = Query(...) +): + """ + WebSocket endpoint for a specific workspace. + Authenticates via token in query string (since WS headers are limited). + """ + # 1. Authenticate + try: + payload = decode_access_token(token) + user_id = payload.get("sub") + token_workspace_id = payload.get("workspace_id") + + # Verify user belongs to this workspace + if str(token_workspace_id) != str(workspace_id): + await websocket.close(code=1008) # Policy Violation + return + except Exception: + await websocket.close(code=1008) # Policy Violation + return + + await manager.connect(websocket, workspace_id) + try: + # Keep alive - wait for messages (though we mainly broadcast) + while True: + data = await websocket.receive_text() + # Handle client-to-server messages if needed + except WebSocketDisconnect: + manager.disconnect(websocket, workspace_id) + + +@router.websocket("/ws/tickets/{ticket_id}") +async def ticket_thread_events( + websocket: WebSocket, + ticket_id: UUID, + token: str = Query(...) +): + """ + WebSocket endpoint for a specific ticket thread. + Allows real-time message updates within the thread. + """ + try: + payload = decode_access_token(token) + user_id = payload.get("sub") + # In a real app, we'd verify the user has access to this ticket + except Exception: + await websocket.close(code=1008) + return + + await manager.connect_ticket(websocket, ticket_id) + try: + while True: + await websocket.receive_text() + except WebSocketDisconnect: + manager.disconnect_ticket(websocket, ticket_id) diff --git a/api/v1/workspace.py b/api/v1/workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfdc46d65d2c4267e7e33c5074b5c6511159815 --- /dev/null +++ b/api/v1/workspace.py @@ -0,0 +1,94 @@ +from typing import Any, List +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from core.deps import get_db, get_current_user +from core.permissions import require_roles, ADMIN_ROLES +from models.user import User, UserRole +from models.workspace import Workspace +from schemas.workspace import WorkspaceUpdate, WorkspaceResponse + +router = APIRouter() + +@router.get("/list", response_model=List[WorkspaceResponse]) +async def list_available_workspaces( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """List workspaces available to the current user with strict isolation.""" + # 1. Identify the 'Global Hub' (Snowball Management) + management_ws_stmt = select(Workspace).where(Workspace.name.ilike("%SNOWBALL%")) + management_ws_res = await db.execute(management_ws_stmt) + management_ws = management_ws_res.scalar_one_or_none() + + # 2. Check if user is Global Staff + is_internal_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] + is_global_staff = is_internal_staff and management_ws and current_user.workspace_id == management_ws.id + + # 3. Build Base Query + stmt = select(Workspace).where( + Workspace.deleted_at.is_(None), + ~Workspace.name.ilike("SOFTDELETE%") + ) + + # 4. Apply Scoping: Only Global staff see the whole list. Others see ONLY their own. + if not is_global_staff: + stmt = stmt.where(Workspace.id == current_user.workspace_id) + + result = await db.execute(stmt) + return result.scalars().all() + +@router.get("/", response_model=WorkspaceResponse) +async def get_my_workspace( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get current workspace details.""" + print(f"DEBUG WORKSPACE: User={current_user.email}, WS_ID_ATTR={current_user.workspace_id}, TYPE={type(current_user.workspace_id)}") + stmt = select(Workspace).where( + Workspace.id == current_user.workspace_id, + Workspace.deleted_at.is_(None) + ) + result = await db.execute(stmt) + workspace = result.scalar_one_or_none() + if not workspace: + raise HTTPException(status_code=404, detail="Workspace not found") + return workspace + +@router.patch("/", response_model=WorkspaceResponse, dependencies=[Depends(require_roles(ADMIN_ROLES))]) +async def update_workspace( + payload: WorkspaceUpdate, + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Admin only: Update workspace settings/branding.""" + stmt = select(Workspace).where( + Workspace.id == current_user.workspace_id, + Workspace.deleted_at.is_(None) + ) + result = await db.execute(stmt) + workspace = result.scalar_one_or_none() + + workspace.name = payload.name + if payload.branding is not None: + workspace.branding = payload.branding + + db.add(workspace) + await db.commit() + await db.refresh(workspace) + return workspace + +@router.get("/branding") +async def get_workspace_branding( + current_user: User = Depends(get_current_user), + db: AsyncSession = Depends(get_db) +) -> Any: + """Get standalone branding config (logo, colors).""" + stmt = select(Workspace).where( + Workspace.id == current_user.workspace_id, + Workspace.deleted_at.is_(None) + ) + result = await db.execute(stmt) + workspace = result.scalar_one_or_none() + return workspace.branding or {} diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/config.py b/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..18b40d9cd487cae8e05149d5414173d2ae7fde1b --- /dev/null +++ b/core/config.py @@ -0,0 +1,106 @@ +""" +Application configuration loaded from environment variables. +Uses pydantic-settings for type-safe config with .env file support. +""" + +import os +from pydantic_settings import BaseSettings +from pydantic import field_validator +from functools import lru_cache + + +class Settings(BaseSettings): + """Application settings from environment variables.""" + + # App + APP_NAME: str = "Customer Portal" + APP_VERSION: str = "1.0.0" + DEBUG: bool = False + API_V1_STR: str = "/api/v1" + + # Database + DATABASE_URL: str | None = None + DB_USER: str = "postgres" + DB_PASS: str = "postgres" + DB_HOST: str = "localhost" + DB_PORT: int = 5432 + DB_NAME: str = "customer_portal" + + @property + def async_database_url(self) -> str: + """Constructs or ensures the +asyncpg prefix exists for SQLAlchemy.""" + if self.DATABASE_URL: + url = self.DATABASE_URL + if url.startswith("postgresql://"): + return url.replace("postgresql://", "postgresql+asyncpg://", 1) + return url + + # Construct from components if DATABASE_URL is missing + return f"postgresql+asyncpg://{self.DB_USER}:{self.DB_PASS}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}" + + REDIS_URL: str = "redis://localhost:6379" + + # JWT Auth + SECRET_KEY: str = "your-secret-key-change-in-production" + ALGORITHM: str = "HS256" + ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 + REFRESH_TOKEN_EXPIRE_DAYS: int = 7 + + # AI Settings (100% Ollama-Only Transition) + AI_PROVIDER: str = "ollama" + AI_MODEL: str = "kimi-k2.5:cloud" + + # AI Providers (Hybrid Switch) + AI_IMAGE_PROVIDER: str = "local" + AI_TEXT_PROVIDER: str = "ollama" + + # Decoupled Embeddings + AI_TEXT_EMBEDDING_PROVIDER: str = "google" # options: "google", "ollama", "openai" + AI_TEXT_EMBEDDING_MODEL: str = "models/embedding-001" + AI_TEXT_EMBEDDING_DIM: int = 768 + + AI_IMAGE_EMBEDDING_MODEL: str = "clip-ViT-B-32" + AI_IMAGE_EMBEDDING_DIM: int = 512 + + # Vector Safety + AI_FORCE_DIMENSION_COMPATIBILITY: bool = True + + # Deprecated (Keeping for soft migration/compat) + AI_EMBEDDING_MODEL: str = "nomic-embed-text:latest" + AI_EMBEDDING_DIM: int = 768 + + OLLAMA_BASE_URL: str = "http://host.docker.internal:11434" + + @field_validator("OLLAMA_BASE_URL") + @classmethod + def sanitize_ollama_url(cls, v: str) -> str: + """Removes trailing slashes to prevent double-slash API paths.""" + if v and v.endswith("/"): + return v.rstrip("/") + return v + + # Cloud AI Providers + GROQ_API_KEY: str | None = None + OPENAI_API_KEY: str | None = None + ANTHROPIC_API_KEY: str | None = None + GOOGLE_API_KEY: str | None = None + + # LangGraph Settings + LANGCHAIN_TRACING_V2: bool = False + LANGCHAIN_API_KEY: str | None = None + LANGCHAIN_PROJECT: str = "customer-portal" + + # Storage & Logging Settings + STORAGE_BACKEND: str = "local" # options: "local", "s3" + UPLOAD_DIR: str = "uploads" + LOG_DIR: str = "logs" + + class Config: + case_sensitive = True + env_file = ".env" + extra = "ignore" # Add this to prevent future validation errors from extra env vars + + +@lru_cache() +def get_settings() -> Settings: + return Settings() diff --git a/core/database.py b/core/database.py new file mode 100644 index 0000000000000000000000000000000000000000..8447b0504eb888c2301b520f02a273f03c5b6edd --- /dev/null +++ b/core/database.py @@ -0,0 +1,90 @@ +""" +Async SQLAlchemy engine and session factory for PostgreSQL. +""" + +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker +from sqlalchemy.orm import DeclarativeBase +from core.config import get_settings + +settings = get_settings() + +# Definitively fix cloud connectivity by building the URL from validated components +from sqlalchemy.engine import URL + +url = URL.create( + drivername="postgresql+asyncpg", + username=settings.DB_USER, + password=settings.DB_PASS, + host=settings.DB_HOST, + port=settings.DB_PORT, + database=settings.DB_NAME, +) + +connect_args = { + "ssl": "require", + "prepared_statement_cache_size": 0 # CRITICAL for Supavisor Transaction mode +} + +engine = create_async_engine( + url, + echo=settings.DEBUG, + future=True, + pool_size=20, + max_overflow=10, + connect_args=connect_args +) + +async_session_factory = async_sessionmaker( + engine, + class_=AsyncSession, + expire_on_commit=False, +) + + +class Base(DeclarativeBase): + """Base class for all SQLAlchemy models.""" + pass + + +async def get_db(): + """Dependency that yields an async DB session per request.""" + async with async_session_factory() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + finally: + await session.close() + + +import subprocess +from core.logging import get_logger + +logger = get_logger(__name__) + +async def run_migrations(): + """ + Run Alembic migrations automatically on startup. + This replaces the hacky init_db approach. + """ + try: + logger.info("Running database migrations via Alembic...") + # We run this as a subprocess to avoid event loop conflicts + # since alembic's env.py often calls asyncio.run() + subprocess.run( + ["alembic", "upgrade", "head"], + check=True + ) + logger.info("Database migrations completed successfully.") + except Exception as e: + logger.error(f"Unexpected error during migration: {e}") + # In a real app, we might want to exit here to prevent running on old schema + # For hackathon, we'll log it and continue. + # raise e + +async def init_db(): + """DEPRECATED: Use run_migrations instead for proper versioning.""" + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) diff --git a/core/deps.py b/core/deps.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2b5a129756aa4a6f82076eb2687de26dde8974 --- /dev/null +++ b/core/deps.py @@ -0,0 +1,126 @@ +""" +Dependency injection helpers for FastAPI routes. +""" + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from arq import create_pool +from arq.connections import RedisSettings +from typing import Optional + +from core.database import async_session_factory +from core.config import get_settings +from models.user import User + +settings = get_settings() + +# Standard OAuth2 scheme for Swagger UI +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login") + + +async def get_db(): + """Yields a DB session.""" + async with async_session_factory() as session: + yield session + + +async def get_current_user( + db: AsyncSession = Depends(get_db), + token: str = Depends(oauth2_scheme) +) -> User: + """ + Decodes the JWT access token and fetches the current user from the database. + Raises HTTPException if token is invalid or user doesn't exist. + """ + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) + user_id: str = payload.get("sub") + token_type: str = payload.get("type") + if user_id is None or token_type != "access": + raise credentials_exception + except JWTError: + raise credentials_exception + + # Fetch user + stmt = select(User).where( + User.id == user_id, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + user = result.scalar_one_or_none() + if user: + print(f"DEBUG DEPS: Fetched {user.email}, WS_ID={user.workspace_id}") + + if user is None: + raise credentials_exception + if not user.is_active: + raise HTTPException(status_code=400, detail="Inactive user") + + return user + + +async def get_current_staff_user( + current_user: User = Depends(get_current_user) +) -> User: + """ + Enforces that the current user must have a staff/internal role. + """ + from models.user import UserRole + if current_user.role not in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Access Denied: 3SC Internal Staff Only" + ) + return current_user + + +async def get_current_refresh_user( + db: AsyncSession = Depends(get_db), + token: str = Depends(oauth2_scheme) +) -> User: + """ + Decodes the JWT refresh token and fetches the current user. + """ + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate refresh token", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) + user_id: str = payload.get("sub") + token_type: str = payload.get("type") + if user_id is None or token_type != "refresh": + raise credentials_exception + except JWTError: + raise credentials_exception + + stmt = select(User).where( + User.id == user_id, + User.deleted_at.is_(None) + ) + result = await db.execute(stmt) + user = result.scalar_one_or_none() + if not user: + raise credentials_exception + return user + + +async def get_arq_pool(): + """Returns a Redis pool for arq job enqueuing.""" + pool = await create_pool( + RedisSettings.from_dsn(settings.REDIS_URL), + default_queue_name='arq:queue' + ) + try: + yield pool + finally: + await pool.close() diff --git a/core/llm.py b/core/llm.py new file mode 100644 index 0000000000000000000000000000000000000000..23594cb89cd5f82b61369542a9e4b64b2e8c4ef1 --- /dev/null +++ b/core/llm.py @@ -0,0 +1,257 @@ +import asyncio +import warnings +import logging +from core.config import get_settings +from langchain_core.embeddings import Embeddings +from typing import List, Optional, Any + +# Silence maintenance noise from LangChain and Transformers +from langchain_core._api import LangChainDeprecationWarning +warnings.filterwarnings("ignore", category=LangChainDeprecationWarning) +logging.getLogger("transformers").setLevel(logging.ERROR) + +settings = get_settings() + +def get_llm(provider: str = None, model: str = None, **kwargs: Any) -> Any: + """ + Factory function to return a LangChain ChatModel instance. + ENFORCED: Ollama Only. + """ + model = model or settings.AI_MODEL + base_url = settings.OLLAMA_BASE_URL + + logging.info(f"LLM INIT: Provider=Ollama, Model={model}, BaseURL={base_url}") + + try: + from langchain_ollama import ChatOllama + return ChatOllama( + model=model, + base_url=base_url, + timeout=kwargs.pop("timeout", 30), + **kwargs + ) + except ImportError: + from langchain_community.chat_models import ChatOllama + return ChatOllama( + model=model, + base_url=base_url, + timeout=kwargs.pop("timeout", 30), + **kwargs + ) + +def get_embeddings(provider: str = None, model: str = None, **kwargs: Any) -> Any: + """ + DEPRECATED: Use get_text_embeddings() or get_image_embeddings(). + Factory function to return a LangChain Embeddings instance. + """ + return get_text_embeddings(provider=provider, model=model, **kwargs) + +class TruncatedEmbeddings(Embeddings): + """ + Wrapper for LangChain Embeddings that ensures the output vector + matches a specific dimension by truncating or padding. + """ + def __init__(self, inner: Embeddings, dimension: int): + self.inner = inner + self.dimension = dimension + + def _truncate(self, vector: List[float]) -> List[float]: + if len(vector) > self.dimension: + return vector[:self.dimension] + elif len(vector) < self.dimension: + return vector + [0.0] * (self.dimension - len(vector)) + return vector + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + vectors = self.inner.embed_documents(texts) + return [self._truncate(v) for v in vectors] + + def embed_query(self, text: str) -> List[float]: + vector = self.inner.embed_query(text) + return self._truncate(vector) + + async def aembed_query(self, text: str) -> List[float]: + vector = await self.inner.aembed_query(text) + return self._truncate(vector) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + # Check if the inner embedding provider has an async method + if hasattr(self.inner, "aembed_documents"): + vectors = await self.inner.aembed_documents(texts) + else: + vectors = await asyncio.to_thread(self.inner.embed_documents, texts) + return [self._truncate(v) for v in vectors] + + +def get_text_embeddings(provider: str = None, model: str = None, **kwargs: Any) -> Any: + """ + Factory function to return a LangChain Embeddings instance for TEXT. + Supports Ollama (Local), Google (Vertex/GenAI), and OpenAI. + """ + provider = provider or settings.AI_TEXT_EMBEDDING_PROVIDER or settings.AI_PROVIDER + model = model or settings.AI_TEXT_EMBEDDING_MODEL + target_dim = settings.AI_TEXT_EMBEDDING_DIM + + if provider == "ollama": + try: + from langchain_ollama import OllamaEmbeddings + embeddings = OllamaEmbeddings( + model=model or "nomic-embed-text", + base_url=settings.OLLAMA_BASE_URL, + **kwargs + ) + except ImportError: + from langchain_community.embeddings import OllamaEmbeddings + embeddings = OllamaEmbeddings( + model=model or "nomic-embed-text", + base_url=settings.OLLAMA_BASE_URL, + **kwargs + ) + elif provider == "google": + from langchain_google_genai import GoogleGenerativeAIEmbeddings + embeddings = GoogleGenerativeAIEmbeddings( + model=model or "models/embedding-001", + google_api_key=settings.GOOGLE_API_KEY, + **kwargs + ) + elif provider == "openai": + from langchain_openai import OpenAIEmbeddings + embeddings = OpenAIEmbeddings( + model=model or "text-embedding-3-small", + api_key=settings.OPENAI_API_KEY, + **kwargs + ) + else: + raise ValueError(f"Unsupported text embedding provider: {provider}") + + # Apply safety wrapper if force compatibility is enabled + if settings.AI_FORCE_DIMENSION_COMPATIBILITY: + return TruncatedEmbeddings(embeddings, target_dim) + + return embeddings + +class ONNXCLIPEmbeddings(Embeddings): + """ + Ultra-lightweight CLIP implementation using ONNX Runtime. + Replaces torch/sentence-transformers to reduce image size by 10GB+. + """ + def __init__(self, model_name: str = "clip-ViT-B-32"): + self.model_name = model_name + self._session = None + self._tokenizer = None + self._processor = None + + def _lazy_load(self): + if self._session is None: + import onnxruntime as ort + from PIL import Image + import numpy as np + import os + + # Model path resolution (cached in /app/models or similar) + model_path = os.path.join(os.getcwd(), "models", f"{self.model_name}.onnx") + if not os.path.exists(model_path): + # In production, this should be pre-baked into the Docker image + logging.warning(f"ONNX Model not found at {model_path}. Performance will be degraded during first-run download.") + + self._session = ort.InferenceSession(model_path) + # Tokenizer and Processor would ideally be light-weight python equivalents + # For this hackathon, we'll assume a helper library or pre-processed inputs + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + # Implementation logic for ONNX text encoding + return [[0.0] * 512 for _ in texts] # Placeholder for ONNX logic + + def embed_query(self, text: str) -> List[float]: + return self.embed_documents([text])[0] + + def embed_image(self, image_source: Any) -> List[float]: + return [0.0] * 512 # Placeholder for ONNX vision logic + + async def aembed_query(self, text: str) -> List[float]: + if isinstance(text, str) and (text.startswith("http") or text.endswith((".png", ".jpg", ".jpeg", ".webp"))): + return await asyncio.to_thread(self.embed_image, text) + return await asyncio.to_thread(self.embed_query, text) + +class SentenceTransformersCLIPEmbeddings(Embeddings): + """ + LEGACY: Wrapper for sentence-transformers CLIP model. + Requires torch and full transformers stack (10GB+ total). + """ + def __init__(self, model_name: str = "clip-ViT-B-32"): + self.model_name = model_name + self._model = None + + @property + def model(self): + if self._model is None: + from sentence_transformers import SentenceTransformer + self._model = SentenceTransformer(self.model_name) + return self._model + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + return self.model.encode(texts, show_progress_bar=False).tolist() + + def embed_query(self, text: str) -> List[float]: + return self.model.encode(text, show_progress_bar=False).tolist() + + def embed_image(self, image_source: Any) -> List[float]: + from PIL import Image + import requests + from io import BytesIO + import base64 + import re + + img = None + if isinstance(image_source, Image.Image): + img = image_source + elif isinstance(image_source, str): + if image_source.startswith("data:image"): + base64_data = re.sub(r'^data:image/.+;base64,', '', image_source) + img = Image.open(BytesIO(base64.b64decode(base64_data))) + elif image_source.startswith("http"): + response = requests.get(image_source, timeout=10) + img = Image.open(BytesIO(response.content)) + else: + img = Image.open(image_source) + + if not img: + raise ValueError(f"Invalid image source: {image_source}") + + return self.model.encode(img, show_progress_bar=False).tolist() + + async def aembed_query(self, text: str) -> List[float]: + if isinstance(text, str) and (text.startswith("http") or text.endswith((".png", ".jpg", ".jpeg", ".webp"))): + return await asyncio.to_thread(self.embed_image, text) + return await asyncio.to_thread(self.embed_query, text) + +def get_image_embeddings(provider: str = None, model: str = None, **kwargs: Any) -> Any: + """ + Factory function for high-fidelity multimodal embeddings. + Supports Local (ONNX), Google (Vertex), and OpenAI. + """ + provider = provider or settings.AI_IMAGE_PROVIDER or "local" + model = model or settings.AI_IMAGE_EMBEDDING_MODEL + + if provider == "local": + # Check if we should use legacy torch or new ONNX + try: + import onnxruntime + return ONNXCLIPEmbeddings(model_name=model) + except ImportError: + return SentenceTransformersCLIPEmbeddings(model_name=model) + + elif provider == "google": + from langchain_google_vertexai import VertexAIMultimodalEmbeddings + return VertexAIMultimodalEmbeddings( + model_name=model or "multimodalembedding", + project=kwargs.get("project"), + location=kwargs.get("location", "us-central1") + ) + elif provider == "openai": + # Note: OpenAI uses text-embedding-3 for text but CLIP/Vision for multimodal. + # This wrapper would handle the specific OpenAI vision encoding if needed. + from langchain_openai import OpenAIEmbeddings + return OpenAIEmbeddings(model=model or "text-embedding-3-small") + else: + raise ValueError(f"Unsupported image embedding provider: {provider}") diff --git a/core/logging.py b/core/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..7fcb7027473b4cd49fe6fb9cf30d068c3750700d --- /dev/null +++ b/core/logging.py @@ -0,0 +1,57 @@ +import logging +import sys +from pathlib import Path +from logging.handlers import TimedRotatingFileHandler +from core.config import get_settings + +settings = get_settings() + +# Ensure logs directory exists +LOGS_DIR = Path("logs") +LOGS_DIR.mkdir(exist_ok=True) + +# Default log format +LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + +def setup_logging(): + """ + Configure global logging settings for the application. + """ + log_level = logging.DEBUG if settings.DEBUG else logging.INFO + + # Root logger configuration + root_logger = logging.getLogger() + root_logger.setLevel(log_level) + + # Remove existing handlers to avoid duplicates + if root_logger.hasHandlers(): + root_logger.handlers.clear() + + # 1. Console Handler + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(logging.Formatter(LOG_FORMAT)) + root_logger.addHandler(console_handler) + + # 2. File Handler (Timed Rotating - Daily) + file_handler = TimedRotatingFileHandler( + LOGS_DIR / "app.log", + when="midnight", + interval=1, + backupCount=30, # Keep 30 days of logs + encoding="utf-8" + ) + file_handler.setFormatter(logging.Formatter(LOG_FORMAT)) + root_logger.addHandler(file_handler) + + # 3. Suppress noisy third-party libraries if not in DEBUG + if not settings.DEBUG: + logging.getLogger("uvicorn.access").setLevel(logging.WARNING) + logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING) + logging.getLogger("httpx").setLevel(logging.WARNING) + logging.getLogger("langchain_ollama").setLevel(logging.INFO) + +def get_logger(name: str): + """ + Utility to get a logger instance for a specific module. + """ + return logging.getLogger(name) diff --git a/core/observability.py b/core/observability.py new file mode 100644 index 0000000000000000000000000000000000000000..99ffc7eb9a10253f8894a509bedd8323f08af45a --- /dev/null +++ b/core/observability.py @@ -0,0 +1,79 @@ +""" +AI Observability Utils β€” centralized logic for recording AI workflow steps. +""" + +from uuid import UUID +from datetime import datetime +from sqlalchemy import select, update +from sqlalchemy.ext.asyncio import AsyncSession +from models.ai_workflow import AIWorkflow +from core.logging import get_logger + +logger = get_logger(__name__) + +async def record_workflow_step( + db: AsyncSession, + entity_id: UUID, + workspace_id: UUID, + workflow_type: str, + step_name: str, + input_data: any = None, + output_data: any = None, + status: str = "success", + duration_ms: float = 0.0, + current_stage: str = None +): + """ + Records a step in an AI workflow lifecycle. + Finds the existing workflow for this entity_id (ticket_id, article_id, search_id) + or creates a new one. + """ + try: + # 1. Fetch existing workflow + stmt = select(AIWorkflow).where( + AIWorkflow.entity_id == entity_id, + AIWorkflow.workflow_type == workflow_type + ) + res = await db.execute(stmt) + workflow = res.scalar_one_or_none() + + step_entry = { + "timestamp": datetime.utcnow().isoformat(), + "step_name": step_name, + "status": status, + "input": input_data, + "output": output_data, + "duration_ms": round(duration_ms, 2) + } + + if not workflow: + # 2. Create new record + workflow = AIWorkflow( + workspace_id=workspace_id, + entity_id=entity_id, + workflow_type=workflow_type, + current_stage=current_stage or step_name, + steps=[step_entry], + total_duration_ms=duration_ms + ) + db.add(workflow) + else: + # 3. USE ATOMIC UPDATE to prevent lost steps in concurrent background tasks + # This is critical for parallel jobs like Triage and Indexing + stmt = ( + update(AIWorkflow) + .where(AIWorkflow.id == workflow.id) + .values( + steps=AIWorkflow.steps.concat([step_entry]), # Atomic JSONB append + total_duration_ms=AIWorkflow.total_duration_ms + duration_ms, + current_stage=current_stage or AIWorkflow.current_stage + ) + ) + await db.execute(stmt) + + # We flush so the ID is available, caller commits the full transaction + await db.flush() + return workflow + except Exception as e: + logger.error(f"Failed to record AI workflow step for {entity_id}: {e}") + return None diff --git a/core/permissions.py b/core/permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..8093854a84b6b251e736241317f493aa6c18650b --- /dev/null +++ b/core/permissions.py @@ -0,0 +1,29 @@ +""" +Role-based access control (RBAC) decorators and utilities. +""" + +from typing import List +from fastapi import Depends, HTTPException, status +from models.user import User, UserRole +from core.deps import get_current_user + + +def require_roles(allowed_roles: List[UserRole]): + """ + Dependency generator that checks if the current user has one of the allowed roles. + """ + def role_checker(current_user: User = Depends(get_current_user)) -> User: + if current_user.role not in allowed_roles: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="You do not have permission to perform this action", + ) + return current_user + + return role_checker + +# Pre-defined role groups for convenience +ALL_CUSTOMER_ROLES = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] +ALL_SC_ROLES = [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] +ADMIN_ROLES = [UserRole.CUSTOMER_ADMIN, UserRole.SC_ADMIN, UserRole.SC_LEAD] +EVERYBODY_ROLES = ALL_CUSTOMER_ROLES + ALL_SC_ROLES # status 120 diff --git a/core/search.py b/core/search.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6cbaed6c0d6e71db7c4e539825c84c075e4ccf --- /dev/null +++ b/core/search.py @@ -0,0 +1,26 @@ +from typing import List + +def chunk_text(text: str, chunk_size: int = 600, chunk_overlap: int = 100) -> List[str]: + """ + Simple recursive-style character splitter for text chunking. + Ensures chunks have the specified overlap for context preservation. + """ + if not text: + return [] + + chunks = [] + start = 0 + + while start < len(text): + end = start + chunk_size + chunk = text[start:end] + chunks.append(chunk) + + # Move start forward by chunk_size minus overlap + start += (chunk_size - chunk_overlap) + + # Prevent infinite loop if overlap >= size + if chunk_overlap >= chunk_size: + start = end + + return chunks diff --git a/core/security.py b/core/security.py new file mode 100644 index 0000000000000000000000000000000000000000..962037cfa8966351761ad8f1437c69e6e0f7da15 --- /dev/null +++ b/core/security.py @@ -0,0 +1,60 @@ +""" +Security utilities: password hashing and JWT token generation. +""" + +from datetime import datetime, timedelta, timezone +from typing import Any, Union +from jose import jwt +from passlib.context import CryptContext +from core.config import get_settings + +settings = get_settings() + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """Verifies a plain password against a hashed one.""" + try: + return pwd_context.verify(plain_password, hashed_password) + except ValueError: + return False + + +def get_password_hash(password: str) -> str: + """Hashes a password using bcrypt.""" + return pwd_context.hash(password) + + +def create_access_token(subject: Union[str, Any], workspace_id: Union[str, Any] = None, expires_delta: timedelta = None) -> str: + """Creates a short-lived JWT access token.""" + if expires_delta: + expire = datetime.now(timezone.utc) + expires_delta + else: + expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + + to_encode = { + "exp": expire, + "sub": str(subject), + "workspace_id": str(workspace_id) if workspace_id else None, + "type": "access" + } + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + return encoded_jwt + + +def create_refresh_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str: + """Creates a long-lived JWT refresh token.""" + if expires_delta: + expire = datetime.now(timezone.utc) + expires_delta + else: + expire = datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS) + + to_encode = {"exp": expire, "sub": str(subject), "type": "refresh"} + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + return encoded_jwt + + +def decode_access_token(token: str) -> dict: + """Decodes and validates a JWT access token.""" + return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) diff --git a/core/storage.py b/core/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca9f197ae71f4425b008be00a279fe56011629d --- /dev/null +++ b/core/storage.py @@ -0,0 +1,115 @@ +import os +import uuid +import aiofiles +import aioboto3 +from pathlib import Path +from typing import Optional, Any, Union +from core.config import get_settings +from core.logging import get_logger + +settings = get_settings() +logger = get_logger(__name__) + +class StorageResult: + def __init__(self, path: str, backend: str, url: Optional[str] = None): + self.path = path + self.backend = backend + self.url = url + +class LocalStorage: + def __init__(self): + self.base_dir = Path(settings.UPLOAD_DIR) + self.base_dir.mkdir(exist_ok=True) + + async def upload(self, file_content: bytes, filename: str, workspace_id: Any) -> StorageResult: + file_id = uuid.uuid4() + workspace_dir = self.base_dir / str(workspace_id) + workspace_dir.mkdir(exist_ok=True) + + file_path = workspace_dir / f"{file_id}_{filename}" + + async with aiofiles.open(file_path, mode="wb") as f: + await f.write(file_content) + + return StorageResult(path=str(file_path), backend="local") + + async def get_url(self, storage_path: str) -> str: + # For local, we return a mock or actual local download endpoint if we had one + # Currently, the API handles this via FileResponse. + return storage_path + + def get_local_path(self, storage_path: str) -> str: + return storage_path + + async def delete(self, storage_path: str) -> bool: + try: + if os.path.exists(storage_path): + os.remove(storage_path) + return True + except Exception as e: + logger.error(f"Local Storage: Failed to delete {storage_path}: {e}") + return False + +class S3Storage: + def __init__(self): + self.bucket = settings.S3_BUCKET + self.session = aioboto3.Session( + aws_access_key_id=settings.S3_ACCESS_KEY, + aws_secret_access_key=settings.S3_SECRET_KEY, + region_name=settings.S3_REGION + ) + self.local_fallback = LocalStorage() + + async def upload(self, file_content: bytes, filename: str, workspace_id: Any) -> StorageResult: + # Check if S3 is even configured + if not settings.S3_ACCESS_KEY or not settings.S3_SECRET_KEY: + logger.warning("S3 Storage not configured. Falling back to local storage.") + return await self.local_fallback.upload(file_content, filename, workspace_id) + + file_id = uuid.uuid4() + key = f"{workspace_id}/{file_id}_{filename}" + + try: + async with self.session.client("s3", endpoint_url=settings.S3_ENDPOINT_URL or None) as s3: + await s3.put_object(Bucket=self.bucket, Key=key, Body=file_content) + logger.info(f"S3 Storage: Uploaded {key} to bucket {self.bucket}") + return StorageResult(path=key, backend="s3") + except Exception as e: + logger.error(f"S3 Storage Upload failed: {e}. Falling back to local storage.") + return await self.local_fallback.upload(file_content, filename, workspace_id) + + async def get_url(self, storage_path: str, expires_in: int = 3600) -> str: + """Generates a Presigned URL for S3 or returns local path.""" + if "/" not in storage_path and not storage_path.startswith("uploads"): + # Likely an S3 Key + try: + async with self.session.client("s3", endpoint_url=settings.S3_ENDPOINT_URL or None) as s3: + url = await s3.generate_presigned_url( + 'get_object', + Params={'Bucket': self.bucket, 'Key': storage_path}, + ExpiresIn=expires_in + ) + return url + except Exception as e: + logger.error(f"S3 Storage: Failed to generate presigned URL for {storage_path}: {e}") + return storage_path + return storage_path + + def get_local_path(self, storage_path: str) -> str: + return self.local_fallback.get_local_path(storage_path) + + async def delete(self, storage_path: str) -> bool: + if "/" in storage_path and not storage_path.startswith("uploads"): + try: + async with self.session.client("s3", endpoint_url=settings.S3_ENDPOINT_URL or None) as s3: + await s3.delete_object(Bucket=self.bucket, Key=storage_path) + return True + except Exception as e: + logger.error(f"S3 Storage: Failed to delete key {storage_path}: {e}") + return False + return await self.local_fallback.delete(storage_path) + +def get_storage_provider() -> Union[LocalStorage, S3Storage]: + if settings.STORAGE_BACKEND == "s3": + return S3Storage() + return LocalStorage() diff --git a/core/sync.py b/core/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..1407a16cd0e7e79d8ad7ad5e0cb21039d8f7b39b --- /dev/null +++ b/core/sync.py @@ -0,0 +1,122 @@ +import httpx +import re +import os +import mimetypes +from uuid import UUID, uuid4 +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from models.attachment import Attachment +from core.storage import get_storage_provider +from core.logging import get_logger + +logger = get_logger(__name__) + +# Comprehensive pattern for images: Markdown ![alt](url) OR raw URLs ending in extensions +# Matches: +# 1. ![alt text](https://url) +# 2. https://url.jpg, .png, .jpeg, .webp, .gif (even without markdown) +IMAGE_PATTERN = re.compile( + r'(?:!\[.*?\]\((https?://[^\s\)]+)\))|' + r'(https?://[^\s\)]+(?:\.jpg|\.jpeg|\.png|\.webp|\.gif)(?:\?[^\s\)]*)?)', + re.IGNORECASE +) + +async def sync_markdown_images(db: AsyncSession, entity_id: UUID, workspace_id: UUID, content: str, entity_type: str = "ticket", uploader_id: UUID = None): + """ + Parses content for external images (Markdown or raw URLs), downloads them, + and saves them as formal Attachment records. + """ + if not content: + return [] + + # findall returns a list of tuples for multiple capturing groups + matches = IMAGE_PATTERN.findall(content) + # Flatten matches and filter out empty strings + urls = [url for group in matches for url in group if url] + + if not urls: + return [] + + new_attachments = [] + storage = get_storage_provider() + + # Use a real browser user agent to avoid being blocked by Pexels/Unsplash/etc. + headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + } + + async with httpx.AsyncClient(timeout=30.0, follow_redirects=True, headers=headers) as client: + for url in set(urls): # Use set to avoid double-processing same URL in one content block + try: + # 1. Check if already synced for this entity + stmt = select(Attachment).where( + Attachment.workspace_id == workspace_id, + Attachment.source_url == url, + Attachment.deleted_at.is_(None) + ) + # Link to the specific entity type + if entity_type == "ticket": + stmt = stmt.where(Attachment.ticket_id == entity_id) + else: + stmt = stmt.where(Attachment.article_id == entity_id) + + res = await db.execute(stmt) + existing = res.scalar_one_or_none() + # --- Metadata Recovery Update --- + if existing: + # If the attachment exists but is missing its source_url (from a previous failed run), + # we update it now to ensure full traceability. + if not existing.source_url: + existing.source_url = url + db.add(existing) + logger.info(f"Image Sync: Recovered source_url for existing attachment {existing.id}") + continue + + # 2. Download Image + logger.info(f"Image Sync: Downloading external image for {entity_type} {entity_id}: {url}") + resp = await client.get(url) + if resp.status_code != 200: + logger.warning(f"Image Sync: Failed to download {url}, status {resp.status_code}") + continue + + # 3. Determine properties + content_type = resp.headers.get("Content-Type", "image/png") + ext = mimetypes.guess_extension(content_type) or ".png" + filename = f"extracted_{uuid4().hex[:8]}{ext}" + + # 4. Save to Storage (Corrected Signature: bytes, filename, workspace_id) + # Note: storage_path is determined internally by the provider + storage_res = await storage.upload(resp.content, filename, workspace_id) + storage_path = storage_res.path + + # 5. Create Attachment Record + new_att = Attachment( + workspace_id=workspace_id, + filename=filename, + storage_path=storage_path, + storage_backend=storage.__class__.__name__.lower().replace("storage", ""), # "local" or "s3" + content_type=content_type, + file_size=len(resp.content), + source_url=url, + uploader_id=uploader_id, + is_processed=False # Will be picked up by multimodal indexing + ) + + if entity_type == "ticket": + new_att.ticket_id = entity_id + else: + new_att.article_id = entity_id + + db.add(new_att) + new_attachments.append(new_att) + logger.info(f"Image Sync: Successfully synced {url} -> {storage_path}") + + except Exception as e: + logger.error(f"Image Sync: Error processing {url}: {e}") + + if new_attachments: + # We flush so IDs are available for multimodal processing in the same task + await db.flush() + logger.info(f"Image Sync: Successfully created {len(new_attachments)} attachments for {entity_type} {entity_id}") + + return new_attachments diff --git a/core/tasks.py b/core/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..2987e1df8041c0088ea4f2629103013e7389c8d7 --- /dev/null +++ b/core/tasks.py @@ -0,0 +1,616 @@ +""" +Background task definitions for Arq worker. +""" + +import httpx +from uuid import UUID +from datetime import datetime +from sqlalchemy import select, update +from core.database import async_session_factory +from core.logging import get_logger +from core.websockets import manager +from models.ticket import Ticket, TicketStatus, TicketPriority +from models.notification import Notification +from models.audit_log import AuditLog +from models.escalation_rule import EscalationRule +from models.message import Message +from models.kb_article import KBArticle +from core.llm import get_llm, get_text_embeddings, get_image_embeddings +from core.vision import extract_visual_context, resolve_image +from langchain.schema import HumanMessage, SystemMessage +from models.attachment import Attachment +from models.meta_infra_health import MetaInfraHealth, ServiceStatus +import time + +logger = get_logger(__name__) + +async def auto_summarize_ticket(ctx, ticket_id: UUID): + """ + Background task to generate dual summaries (Internal/Customer). + """ + async with async_session_factory() as db: + # 1. Fetch Ticket + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + if not ticket: + return + + # 2. Fetch Messages + msg_stmt = select(Message).where( + Message.ticket_id == ticket_id, + Message.deleted_at.is_(None) + ).order_by(Message.created_at.asc()) + msg_result = await db.execute(msg_stmt) + messages = msg_result.scalars().all() + + # 3. Partition Messages + public_messages = [m for m in messages if not m.is_internal] + + llm = get_llm() + + def format_convo(msg_list): + return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list]) + + # 4. Multimodal Resolution + # Resolve images from description and messages + all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=3) + for m in messages: + if len(all_imgs) >= 10: break + all_imgs.extend(await extract_visual_context(db, ticket.workspace_id, m.content, limit=2)) + + # Customer Summary + cust_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(public_messages)}" + cust_blocks = [{"type": "text", "text": cust_txt}] + # Only include images found in public messages or description + cust_blocks.extend(all_imgs[:5]) # Hard limit for customer + + cust_prompt = [ + SystemMessage(content="You are a support assistant. Summarize for a CUSTOMER. No internal jargon. Max 3 sentences."), + HumanMessage(content=cust_blocks) + ] + + # Internal Summary + intl_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(messages)}" + intl_blocks = [{"type": "text", "text": intl_txt}] + intl_blocks.extend(all_imgs) # Full internal context + + intl_prompt = [ + SystemMessage(content="You are a support lead. Summarize for an INTERNAL AGENT. Include internal notes. Use visual info if screenshots present. Max 4 sentences."), + HumanMessage(content=intl_blocks) + ] + + # Execute + cust_resp = await llm.ainvoke(cust_prompt) + intl_resp = await llm.ainvoke(intl_prompt) + + summary_data = { + "customer_summary": cust_resp.content, + "internal_summary": intl_resp.content + } + + # Persist + meta = dict(ticket.ai_metadata or {}) + meta["summaries"] = summary_data + ticket.ai_metadata = meta + db.add(ticket) + + # --- Observability: Record Summarization --- + from core.observability import record_workflow_step + await record_workflow_step( + db, + entity_id=ticket.id, + workspace_id=ticket.workspace_id, + workflow_type="LIFECYCLE", + step_name="AI_SUMMARIZATION_COMPLETE", + output_data=summary_data, + current_stage="CONTEXT_SUMMARIZED" + ) + + await db.commit() + logger.info(f"Auto-summary generated for ticket {ticket_id}") + +async def auto_summarize_kb(ctx, article_id: UUID): + """ + Background task to generate KB article summary. + """ + async with async_session_factory() as db: + stmt = select(KBArticle).where( + KBArticle.id == article_id, + KBArticle.deleted_at.is_(None) + ) + result = await db.execute(stmt) + article = result.scalar_one_or_none() + if not article: + return + + llm = get_llm() + # Vision extraction + article_imgs = await extract_visual_context(db, article.workspace_id, article.content, limit=5) + + content_txt = f"Title: {article.title}\n\nContent:\n{article.content}" + # Try Multimodal first + try: + content_blocks = [{"type": "text", "text": content_txt}] + if article_imgs: + content_blocks.extend(article_imgs) + + prompt = [ + SystemMessage(content="Summarize this technical KB article in 2-3 sentences. Focus on correctness and clarity."), + HumanMessage(content=content_blocks) + ] + resp = await llm.ainvoke(prompt) + article.summary = resp.content + logger.info(f"Manual KB Summary (Multimodal) generated for {article_id}") + except Exception as vision_err: + logger.warning(f"Manual Vision summary failed for {article_id}, falling back to text: {vision_err}") + # Fallback to Text-Only + prompt = [ + SystemMessage(content="Summarize this technical KB article in 2-3 sentences."), + HumanMessage(content=content_txt) + ] + resp = await llm.ainvoke(prompt) + article.summary = resp.content + logger.info(f"Manual KB Summary (Text-Fallback) generated for {article_id}") + db.add(article) + + # --- Observability: Record KB Summarization --- + from core.observability import record_workflow_step + await record_workflow_step( + db, + entity_id=article.id, + workspace_id=article.workspace_id, + workflow_type="LIFECYCLE", + step_name="KB_SUMMARIZATION_COMPLETE", + output_data={"summary_len": len(resp.content)}, + current_stage="INDEXED_AND_SUMMARIZED" + ) + + await db.commit() + logger.info(f"Auto-summary generated for KB article {article_id}") + +async def send_dual_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str): + """Send notification to both DB and real-time WebSocket.""" + async with async_session_factory() as db: + # 1. DB Persistence + notification = Notification( + workspace_id=workspace_id, + user_id=user_id, + title=title, + message=message + ) + db.add(notification) + await db.commit() + + # 2. WebSocket Real-time + await manager.broadcast_to_workspace(workspace_id, { + "type": "notification", + "id": str(notification.id), + "title": title, + "message": message, + "created_at": datetime.utcnow().isoformat() + }) + logger.info(f"Dual notification sent to user {user_id}") + +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_dual_notification( + ctx, + user_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") + +async def monitor_sla_thresholds(ctx): + """ + Periodic task to check for SLA breaches and apply escalation rules. + Runs every 5 minutes (configured in worker.py). + """ + logger.info("Starting SLA monitoring check...") + async with async_session_factory() as db: + # Fetch all active tickets with priority + stmt = select(Ticket).where( + (Ticket.status != TicketStatus.RESOLVED) & + (Ticket.status != TicketStatus.CLOSED) & + (Ticket.deleted_at.is_(None)) + ) + result = await db.execute(stmt) + tickets = result.scalars().all() + + now = datetime.utcnow() + + for ticket in tickets: + # Skip if already escalated + if ticket.is_escalated: + continue + + # Find matching escalation rules for this workspace and priority + rule_stmt = select(EscalationRule).where( + (EscalationRule.workspace_id == ticket.workspace_id) & + (EscalationRule.priority_level == ticket.priority.value) + ) + rule_result = await db.execute(rule_stmt) + rules = rule_result.scalars().all() + + for rule in rules: + threshold_time = ticket.created_at.replace(tzinfo=None) + age_minutes = (now - threshold_time).total_seconds() / 60 + + if age_minutes >= rule.threshold_minutes: + logger.warning(f"SLA Breach: Ticket {ticket.id} (Age: {age_minutes:.1f}m) exceeds rule {rule.name}") + + if rule.action == "NOTIFY_LEAD": + # Find Lead or Admin using our new helper + from agents.utils import get_workspace_manager + manager_user = await get_workspace_manager(db, ticket.workspace_id) + + if manager_user: + await send_dual_notification( + ctx, + manager_user.id, + ticket.workspace_id, + "SLA Escalation Alert", + f"Ticket '{ticket.title}' of priority {ticket.priority.value} has exceeded its SLA threshold." + ) + # MARK AS ESCALATED to avoid duplicates + ticket.is_escalated = now + db.add(ticket) + + # --- Observability: Record SLA Breach --- + from core.observability import record_workflow_step + await record_workflow_step( + db, ticket.id, ticket.workspace_id, "LIFECYCLE", + "SLA_BREACH_ENFORCED", + output_data={"rule": rule.name, "action": rule.action, "notify_user_id": str(manager_user.id)}, + current_stage="ESCALATED_SLA" + ) + + # --- Audit Log Update --- + audit = AuditLog( + workspace_id=ticket.workspace_id, + entity_type="ticket", + entity_id=ticket.id, + action="SLA_ESCALATION", + user_id=None, # System action + new_value={"rule_name": rule.name, "action_taken": "NOTIFY_LEAD"} + ) + db.add(audit) + + logger.info(f"Ticket {ticket.id} marked as escalated at {now}") + else: + logger.warning(f"SLA Breach: No Lead/Admin found for workspace {ticket.workspace_id} to notify.") + + elif rule.action == "REASSIGN": + # Log escalation, mark ticket + audit = AuditLog( + workspace_id=ticket.workspace_id, + entity_type="ticket", + entity_id=ticket.id, + action="SLA_REASSIGN", + old_value={"assigned_to": str(ticket.assigned_to)}, + new_value={"assigned_to": "ESCALATED_QUEUE"} + ) + db.add(audit) + ticket.is_escalated = now + db.add(ticket) + + await db.commit() + +async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str): + """Execute a specific remediation action safely in the background.""" + from models.remediation import RemediationHook, RemediationActionType + + async with async_session_factory() as db: + ticket_stmt = select(Ticket).where( + Ticket.id == UUID(ticket_id), + Ticket.deleted_at.is_(None) + ) + hook_stmt = select(RemediationHook).where(RemediationHook.id == UUID(hook_id)) + + ticket = (await db.execute(ticket_stmt)).scalar_one_or_none() + hook = (await db.execute(hook_stmt)).scalar_one_or_none() + + if not ticket or not hook: + return + + logger.info(f"Executing remediation hook {hook.trigger_category} for ticket {ticket.id}") + + if hook.action_type == RemediationActionType.WEBHOOK: + async with httpx.AsyncClient() as client: + # Replace placeholders in template + # (Simple replacement for demonstration) + payload = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id)) + try: + resp = await client.post(hook.target, json=payload) + logger.info(f"Webhook {hook.target} responded with {resp.status_code}") + except Exception as e: + logger.error(f"Failed to trigger remediation webhook: {str(e)}") + + # Mark ticket as resolved after remediation if configured + ticket.status = TicketStatus.RESOLVED + db.add(ticket) + await db.commit() + logger.info(f"Remediation successful: Ticket {ticket_id} resolved via hook {hook_id}") + +async def generate_ticket_embedding(ctx, ticket_id: UUID): + """ + Background task to generate vector embeddings for a ticket's content. + Enables semantic search and similarity matching. + """ + import time + from core.llm import get_embeddings + from models.ai_interaction import AIInteraction + from core.config import get_settings + settings = get_settings() + + start_time = time.perf_counter() + + async with async_session_factory() as db: + stmt = select(Ticket).where( + Ticket.id == ticket_id, + Ticket.deleted_at.is_(None) + ) + result = await db.execute(stmt) + ticket = result.scalar_one_or_none() + + if not ticket: + logger.error(f"Generate Ticket Embedding: Ticket {ticket_id} not found.") + return + + # Prepare content: Title + Description + text_to_embed = f"{ticket.title}\n\n{ticket.description}" + start_time = time.perf_counter() + + try: + from core.observability import record_workflow_step + from core.sync import sync_markdown_images + + # --- 0. Sync Markdown Images --- + sync_start = time.perf_counter() + await sync_markdown_images(db, ticket.id, ticket.workspace_id, ticket.description, entity_type="ticket", uploader_id=ticket.created_by) + await record_workflow_step( + db, ticket.id, ticket.workspace_id, "LIFECYCLE", + "IMAGE_SYNC_COMPLETE", + input_data={"content_len": len(ticket.description)}, + duration_ms=(time.perf_counter() - sync_start) * 1000 + ) + + # --- 1. Textual Embedding --- + embed_start = time.perf_counter() + logger.info(f"Generating embedding for ticket {ticket_id}...") + text_model = get_text_embeddings() + vector = await text_model.aembed_query(text_to_embed) + ticket.embedding = vector + db.add(ticket) + await record_workflow_step( + db, ticket.id, ticket.workspace_id, "LIFECYCLE", + "TEXT_EMBEDDING_GEN", + duration_ms=(time.perf_counter() - embed_start) * 1000 + ) + + # --- 1.5 Duplicate Check (Threshold 0.7) + dup_start = time.perf_counter() + from sqlalchemy import desc + dup_stmt = ( + select( + Ticket, + (1 - Ticket.embedding.cosine_distance(vector)).label("sim_score") + ) + .where( + Ticket.workspace_id == ticket.workspace_id, + Ticket.id != ticket.id, + Ticket.deleted_at.is_(None), + Ticket.duplicate_of_id.is_(None), + Ticket.embedding.isnot(None) + ) + .order_by(desc("sim_score")) + .limit(1) + ) + dup_res = await db.execute(dup_stmt) + match = dup_res.first() + + dup_status = "no_match" + if match and match.sim_score >= 0.7: + ticket.duplicate_of_id = match.Ticket.id + ticket.status = TicketStatus.CLOSED + ticket.resolved_at = datetime.utcnow() + ticket.resolution_text = f"Automated Detection: This ticket has been identified as a duplicate of ticket #{str(match.Ticket.id)[:8]} ({match.Ticket.title})." + dup_status = "duplicate_found" + + # Log this as an automated action + audit = AuditLog( + workspace_id=ticket.workspace_id, + entity_type="ticket", + entity_id=ticket.id, + action="AI_AUTO_CLOSE_DUPLICATE", + user_id=None, # System action + old_value={"status": TicketStatus.OPEN}, + new_value={ + "status": TicketStatus.CLOSED, + "duplicate_of": str(match.Ticket.id), + "resolution": ticket.resolution_text + } + ) + db.add(audit) + logger.info(f"Duplicate Ticket detected: {ticket.id} clones {match.Ticket.id} (score: {match.sim_score}). Auto-closed with metadata.") + + await record_workflow_step( + db, ticket.id, ticket.workspace_id, "LIFECYCLE", + "DUPLICATE_DETECTION", + output_data={"status": dup_status, "max_score": float(match.sim_score) if match else 0.0}, + duration_ms=(time.perf_counter() - dup_start) * 1000 + ) + + # --- 2. Multimodal Attachment Indexing --- + # Fetch all image attachments for this ticket that haven't been processed + att_stmt = select(Attachment).where( + Attachment.ticket_id == ticket_id, + Attachment.content_type.like("image/%"), + Attachment.is_processed == False + ) + att_res = await db.execute(att_stmt) + attachments = att_res.scalars().all() + + if attachments: + logger.info(f"Indexing {len(attachments)} images for ticket {ticket_id}...") + llm = get_llm() + img_model = get_image_embeddings() + + for att in attachments: + try: + # A. Generate Text Caption + # We use the existing resolve_image helper to get Base64 + resolved = await resolve_image(db, ticket.workspace_id, str(att.id)) + if resolved: + try: + caption_prompt = [ + SystemMessage(content="Describe this support ticket image/screenshot briefly (1-2 sentences). Focus on technical errors or UI state."), + HumanMessage(content=[resolved]) + ] + caption_res = await llm.ainvoke(caption_prompt) + if caption_res: + att.ai_caption = caption_res.content + except Exception as cap_err: + logger.warning(f"Vision Caption failed for {att.id}: {cap_err}") + + # B. Generate Vision Vector (CLIP) + try: + # Ollama/CLIP might need raw text or special handling. + # For now, we try embedding the caption or a visual identifier. + # To be absolutely safe, we'll embed the caption if available, + # otherwise we try the URL (which resolved["image_url"]["url"] provides). + vision_input = att.ai_caption or resolved["image_url"]["url"] + img_vector = await img_model.aembed_query(vision_input) + att.embedding = img_vector + except Exception as emb_err: + logger.warning(f"Vision Embedding failed for {att.id}: {emb_err}") + + att.is_processed = True + db.add(att) + except Exception as img_err: + logger.error(f"Failed to process attachment metadata for {att.id}: {img_err}") + + # Log this as a system AI interaction + duration_ms = (time.perf_counter() - start_time) * 1000 + interaction = AIInteraction( + workspace_id=ticket.workspace_id, + ticket_id=ticket.id, + agent_name="system:multimodal_indexing", + model_info=f"{settings.AI_TEXT_EMBEDDING_MODEL} + {settings.AI_IMAGE_EMBEDDING_MODEL}", + input_data={"text_length": len(text_to_embed), "img_count": len(attachments)}, + output_data={"status": "completed"}, + duration_ms={"total": round(duration_ms, 2)}, + is_automatic=True + ) + db.add(interaction) + + # --- 3. Record Completion Trace --- + await record_workflow_step( + db, ticket.id, ticket.workspace_id, "LIFECYCLE", + "TICKET_INDEXING_COMPLETE", + output_data={"text_length": len(text_to_embed), "img_count": len(attachments), "duration_ms": round(duration_ms, 2)}, + current_stage="READY_FOR_SEARCH" + ) + + await db.commit() + logger.info(f"Ticket {ticket.id} indexing complete and traced.") + except Exception as e: + logger.error(f"Failed to generate multimodal embedding for ticket {ticket_id}: {str(e)}") + +async def record_system_heartbeat(ctx): + """ + Periodic task to record infrastructure health snapshots. + Runs every 5 minutes (configured in nexus_worker.py). + """ + from core.config import get_settings + from arq import create_pool + from arq.connections import RedisSettings + settings = get_settings() + + logger.info("Recording system heartbeat...") + + async with async_session_factory() as db: + # 1. Database Heartbeat + db_start = time.perf_counter() + db_status = ServiceStatus.DOWN + db_latency = 0 + try: + from sqlalchemy import text + await db.execute(text("SELECT 1")) + db_status = ServiceStatus.UP + db_latency = (time.perf_counter() - db_start) * 1000 + except Exception as e: + logger.error(f"Heartbeat: Database check failed: {e}") + + db_heartbeat = MetaInfraHealth( + service_name="DATABASE", + status=db_status, + latency_ms=db_latency, + environment="production" + ) + db.add(db_heartbeat) + + # 2. Redis Heartbeat (Arq) + redis_start = time.perf_counter() + redis_status = ServiceStatus.DOWN + redis_latency = 0 + redis_metrics = {} + try: + # We use the pool from ctx if available, otherwise create a temp one + pool = ctx.get('redis') + if not pool: + pool = await create_pool(RedisSettings.from_dsn(settings.REDIS_URL)) + + # Check keys to gauge activity + job_keys = await pool.keys("arq:job:*") + redis_status = ServiceStatus.UP + redis_latency = (time.perf_counter() - redis_start) * 1000 + redis_metrics = {"pending_jobs": len(job_keys)} + except Exception as e: + logger.error(f"Heartbeat: Redis check failed: {e}") + + redis_heartbeat = MetaInfraHealth( + service_name="REDIS", + status=redis_status, + latency_ms=redis_latency, + metrics=redis_metrics, + environment="production" + ) + db.add(redis_heartbeat) + + # 3. Ollama Heartbeat + ollama_start = time.perf_counter() + ollama_status = ServiceStatus.DOWN + ollama_latency = 0 + ollama_metrics = {} + try: + async with httpx.AsyncClient(timeout=5.0) as client: + resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags") + if resp.status_code == 200: + ollama_status = ServiceStatus.UP + ollama_latency = (time.perf_counter() - ollama_start) * 1000 + ollama_metrics = {"models": resp.json().get("models", [])} + except Exception as e: + logger.error(f"Heartbeat: Ollama check failed: {e}") + + ollama_heartbeat = MetaInfraHealth( + service_name="OLLAMA", + status=ollama_status, + latency_ms=ollama_latency, + metrics=ollama_metrics, + environment="production" + ) + db.add(ollama_heartbeat) + + await db.commit() + logger.info("System heartbeat recorded successfully.") diff --git a/core/vision.py b/core/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..c1188d27e30193d4c06748c01bb7dede578a523b --- /dev/null +++ b/core/vision.py @@ -0,0 +1,98 @@ +import re +import base64 +import os +from uuid import UUID +from typing import List, Dict, Any, Optional +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from models.attachment import Attachment +from core.logging import get_logger + +logger = get_logger(__name__) + +# Pattern for Markdown images: ![alt](url_or_id) +IMAGE_PATTERN = re.compile(r'!\[.*?\]\((.*?)\)') + +async def resolve_image(db: AsyncSession, workspace_id: UUID, identifier: str) -> Optional[Dict[str, Any]]: + """Resolves a Markdown identifier (URL or UUID) to a Base64 data URI or public URL.""" + # 1. Direct Web URLs + if identifier.startswith(("http://", "https://")): + return { + "type": "image_url", + "image_url": {"url": identifier, "detail": "low"} + } + + # 2. Potential Attachment Reference (UUID) + try: + # Check if the identifier is a UUID or contains a UUID in a known path structure + # (e.g., /api/v1/tickets/attachments/UUID/download) + potential_uuid = identifier + if "/" in identifier: + parts = identifier.strip("/").split("/") + if "download" in parts: + potential_uuid = parts[parts.index("download") - 1] + else: + potential_uuid = parts[-1] + + attachment_id = UUID(potential_uuid) + + stmt = select(Attachment).where( + Attachment.id == attachment_id, + Attachment.workspace_id == workspace_id, + Attachment.deleted_at.is_(None) + ) + res = await db.execute(stmt) + attachment = res.scalar_one_or_none() + + if attachment: + from core.storage import get_storage_provider + storage = get_storage_provider() + + if attachment.storage_backend == "s3": + url = await storage.get_url(attachment.storage_path) + return { + "type": "image_url", + "image_url": {"url": url, "detail": "auto"} + } + + # Local fallback + local_path = storage.get_local_path(attachment.storage_path) + if os.path.exists(local_path): + with open(local_path, "rb") as f: + img_data = base64.b64encode(f.read()).decode("utf-8") + return { + "type": "image_url", + "image_url": { + "url": f"data:{attachment.content_type};base64,{img_data}", + "detail": "auto" + } + } + + except (ValueError, IndexError): + # Not a valid UUID or recognizable attachment link + pass + + return None + +async def extract_visual_context(db: AsyncSession, workspace_id: UUID, text: str, limit: int = 5) -> List[Dict[str, Any]]: + """ + Parses markdown text for images and resolves them into a format compatible with + OpenAI-style multimodal message payloads. + """ + if not text: + return [] + + matches = IMAGE_PATTERN.findall(text) + images = [] + + for identifier in matches: + if len(images) >= limit: + break + resolved = await resolve_image(db, workspace_id, identifier.strip()) + if resolved: + images.append(resolved) + + if images: + logger.info(f"Vision: Resolved {len(images)} images for multimodal context from workspace {workspace_id}") + + return images diff --git a/core/websockets.py b/core/websockets.py new file mode 100644 index 0000000000000000000000000000000000000000..f7b02767a642cca68b241d469007ccbe578de746 --- /dev/null +++ b/core/websockets.py @@ -0,0 +1,72 @@ +""" +WebSocket Connection Manager for real-time updates. +""" + +import json +from typing import Dict, List, Set, Any +from uuid import UUID +from fastapi import WebSocket + + +class ConnectionManager: + def __init__(self): + # Maps workspace_id -> Set of WebSockets + self.active_connections: Dict[UUID, Set[WebSocket]] = {} + # Maps ticket_id -> Set of WebSockets + self.ticket_connections: Dict[UUID, Set[WebSocket]] = {} + + async def connect(self, websocket: WebSocket, workspace_id: UUID): + await websocket.accept() + if workspace_id not in self.active_connections: + self.active_connections[workspace_id] = set() + self.active_connections[workspace_id].add(websocket) + + def disconnect(self, websocket: WebSocket, workspace_id: UUID): + if workspace_id in self.active_connections: + self.active_connections[workspace_id].discard(websocket) + + async def connect_ticket(self, websocket: WebSocket, ticket_id: UUID): + await websocket.accept() + if ticket_id not in self.ticket_connections: + self.ticket_connections[ticket_id] = set() + self.ticket_connections[ticket_id].add(websocket) + + def disconnect_ticket(self, websocket: WebSocket, ticket_id: UUID): + if ticket_id in self.ticket_connections: + self.ticket_connections[ticket_id].discard(websocket) + + async def broadcast_to_workspace(self, workspace_id: UUID, message: Any): + """Broadcast a message to all users in a specific workspace.""" + if workspace_id not in self.active_connections: + return + + disconnected = set() + payload = json.dumps(message) + + for connection in self.active_connections[workspace_id]: + try: + await connection.send_text(payload) + except Exception: + disconnected.add(connection) + + for conn in disconnected: + self.active_connections[workspace_id].discard(conn) + + async def broadcast_to_ticket(self, ticket_id: UUID, message: Any): + """Broadcast a message to all users viewing a specific ticket thread.""" + if ticket_id not in self.ticket_connections: + return + + disconnected = set() + payload = json.dumps(message) + + for connection in self.ticket_connections[ticket_id]: + try: + await connection.send_text(payload) + except Exception: + disconnected.add(connection) + + for conn in disconnected: + self.ticket_connections[ticket_id].discard(conn) + +manager = ConnectionManager() diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3d0ccd6df6b24339a0019aa9fccfad7fec6cced5 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,127 @@ +version: '3.8' + +services: + # db: + # image: pgvector/pgvector:pg16 + # container_name: customer_portal_db + # environment: + # POSTGRES_USER: postgres + # POSTGRES_PASSWORD: postgres + # POSTGRES_DB: customer_portal + # ports: + # - "5432:5432" + # volumes: + # - postgres_data:/var/lib/postgresql/data + # restart: unless-stopped + # healthcheck: + # test: ["CMD-SHELL", "pg_isready -U postgres -d customer_portal"] + # interval: 10s + # timeout: 5s + # retries: 5 + # networks: + # - app-network + + redis: + image: redis:7-alpine + container_name: customer_portal_redis + ports: + - "6379:6379" + restart: unless-stopped + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 5 + networks: + - app-network + + nexus-api: + build: + context: . + target: heavy + container_name: nexus_master_api + env_file: .env + extra_hosts: + - "host.docker.internal:host-gateway" + depends_on: + redis: + condition: service_healthy + ports: + - "8000:8000" + volumes: + - .:/app + - ./uploads:/app/uploads + - ./logs:/app/logs + command: ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] + networks: + - app-network + dns: + - 8.8.8.8 + - 8.8.4.4 + + nexus-worker-default: + build: + context: . + target: heavy + container_name: nexus_worker_default + env_file: .env + extra_hosts: + - "host.docker.internal:host-gateway" + command: ["arq", "nexus_worker.WorkerSettings"] + volumes: + - .:/app + depends_on: + redis: + condition: service_healthy + networks: + - app-network + dns: + - 8.8.8.8 + - 8.8.4.4 + + nexus-worker-critical: + build: + context: . + target: heavy + container_name: nexus_worker_critical + env_file: .env + extra_hosts: + - "host.docker.internal:host-gateway" + command: ["sh", "-c", "export QUEUE=arq:critical && arq nexus_worker.WorkerSettings"] + volumes: + - .:/app + depends_on: + redis: + condition: service_healthy + networks: + - app-network + dns: + - 8.8.8.8 + - 8.8.4.4 + + nexus-worker-ai: + build: + context: . + target: heavy + container_name: nexus_worker_ai + env_file: .env + extra_hosts: + - "host.docker.internal:host-gateway" + command: ["arq", "nexus_worker.WorkerSettings"] + volumes: + - .:/app + depends_on: + redis: + condition: service_healthy + networks: + - app-network + dns: + - 8.8.8.8 + - 8.8.4.4 + +networks: + app-network: + driver: bridge + +# volumes: +# postgres_data: diff --git a/frontend/apps/customer/.gitignore b/frontend/apps/customer/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a547bf36d8d11a4f89c59c144f24795749086dd1 --- /dev/null +++ b/frontend/apps/customer/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/frontend/apps/customer/README.md b/frontend/apps/customer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7dbf7ebf3b2a3d84ad526bc47810d1d211331b8b --- /dev/null +++ b/frontend/apps/customer/README.md @@ -0,0 +1,73 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/frontend/apps/customer/eslint.config.js b/frontend/apps/customer/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..5e6b472f583e34a1cca751440d4f241495475723 --- /dev/null +++ b/frontend/apps/customer/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/frontend/apps/customer/index.html b/frontend/apps/customer/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0c12d185f37639ee43f719acec5dd1d7518fd243 --- /dev/null +++ b/frontend/apps/customer/index.html @@ -0,0 +1,19 @@ + + + + + + + Nexus | Customer Portal + + + + + + +
+ + + diff --git a/frontend/apps/customer/package.json b/frontend/apps/customer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3fb0dade3e4c306580b63ecff8442f8e55284ae2 --- /dev/null +++ b/frontend/apps/customer/package.json @@ -0,0 +1,37 @@ +{ + "name": "customer", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@nexus/shared": "*", + "mermaid": "^11.13.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "react-markdown": "^10.1.0", + "react-syntax-highlighter": "^16.1.1", + "remark-gfm": "^4.0.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.4", + "@types/node": "^24.12.0", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@types/react-syntax-highlighter": "^15.5.13", + "@vitejs/plugin-react": "^6.0.1", + "eslint": "^9.39.4", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.4.0", + "typescript": "~5.9.3", + "typescript-eslint": "^8.57.0", + "vite": "^8.0.1", + "vite-tsconfig-paths": "^6.1.1" + } +} diff --git a/frontend/apps/customer/public/favicon.svg b/frontend/apps/customer/public/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..6893eb13237060adc0c968a690149a49faa2d7d3 --- /dev/null +++ b/frontend/apps/customer/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/apps/customer/public/icons.svg b/frontend/apps/customer/public/icons.svg new file mode 100644 index 0000000000000000000000000000000000000000..e9522193d9f796a9748e9ad8c952a5df73c87db9 --- /dev/null +++ b/frontend/apps/customer/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/apps/customer/src/App.css b/frontend/apps/customer/src/App.css new file mode 100644 index 0000000000000000000000000000000000000000..59e872a7136f53d0fcd8ed469cf5958116064c56 --- /dev/null +++ b/frontend/apps/customer/src/App.css @@ -0,0 +1,120 @@ +.nexus-shell { + display: flex; + background: #F9FAFB; /* COLORS.gray50 */ + min-height: 100vh; + font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; + letter-spacing: -0.02em; + color: #111827; /* COLORS.gray900 */ +} + +.nexus-main-frame { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; + overflow: hidden; +} + +.nexus-viewport { + flex: 1; + overflow-y: auto; +} + +/* Base styles to match reference JSX */ +* { + box-sizing: border-box; +} + +body { + margin: 0; + padding: 0; +} + +@keyframes branding-shimmer { + 0% { background-position: -200% 0; } + 100% { background-position: 200% 0; } +} + +@keyframes branding-pulse { + 0%, 100% { opacity: 1; filter: brightness(1) saturate(1); } + 50% { opacity: 0.9; filter: brightness(1.3) saturate(1.2); } +} + +.nexus-branding-animated { + background: linear-gradient( + 90deg, + #C2410C 0%, + #B91C1C 25%, + #991B1B 50%, + #B91C1C 75%, + #C2410C 100% + ); + background-size: 200% auto; + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + text-shadow: 0 0 1px rgba(194, 65, 12, 0.2); + animation: branding-shimmer 4s infinite linear, branding-pulse 3s infinite ease-in-out; + display: inline-block; + font-weight: 800; +} + +.nexus-loading-screen { + display: flex; + align-items: center; + justify-content: center; + height: 100vh; + background: radial-gradient(circle at 50% 50%, #F8FAFC 0%, #F1F5F9 100%); +} + +.nexus-loading-box { + background: rgba(255, 255, 255, 0.7); + backdrop-filter: blur(20px); + padding: 48px; + border-radius: 28px; + border: 1px solid rgba(255, 255, 255, 0.8); + display: flex; + flex-direction: column; + align-items: center; + gap: 24px; + box-shadow: 0 40px 100px rgba(30, 58, 138, 0.1); + max-width: 400px; + text-align: center; + animation: nexus-fade-in 0.8s ease-out; +} + +.nexus-loading-msg { + font-size: 14px; + font-weight: 700; + color: #64748B; + text-transform: uppercase; + letter-spacing: 0.1em; + margin: 0; +} + +.nexus-loading-bar { + width: 240px; + height: 6px; + background: #E2E8F0; + border-radius: 3px; + overflow: hidden; +} + +.nexus-loading-progress { + width: 40%; + height: 100%; + background: linear-gradient(90deg, #1E40AF, #3B82F6); + border-radius: 3px; + animation: nexus-loading-slide 2s infinite ease-in-out; +} + +@keyframes nexus-loading-slide { + 0% { transform: translateX(-100%); } + 50% { transform: translateX(150%); } + 100% { transform: translateX(-100%); } +} + +@keyframes nexus-fade-in { + from { opacity: 0; transform: translateY(20px); } + to { opacity: 1; transform: translateY(0); } +} diff --git a/frontend/apps/customer/src/App.tsx b/frontend/apps/customer/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a14bbb66e39924be1a14cdc8c4ab625cf2602a78 --- /dev/null +++ b/frontend/apps/customer/src/App.tsx @@ -0,0 +1,150 @@ +import { useState } from "react"; +import { useAuth, useTickets, LoginCard, setPortalType, NexusLogo } from "@nexus/shared"; + +setPortalType('customer'); +import { Sidebar } from "./components/Sidebar"; +import { TopBar } from "./components/TopBar"; +import { Dashboard } from "./components/Dashboard"; +import { TicketList } from "./components/TicketList"; +import { ThreadView } from "./components/ThreadView"; +import { KnowledgeBase } from "./components/KnowledgeBase"; +import { Analytics } from "./components/Analytics"; +import { WorkspaceView } from "./components/WorkspaceView"; +import { NewTicketModal } from "./components/NewTicketModal"; +import { NexusMasterAgent } from "./components/NexusMasterAgent"; +import { UserSettingsModal } from "./components/UserSettingsModal"; +import "./App.css"; + +const COLORS = { + brand: "#1E40AF", + gray50: "#F9FAFB", + gray100: "#F3F4F6", + gray200: "#E5E7EB", + gray800: "#1F2937", + gray900: "#111827", +}; + +export default function App() { + const { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth(); + const { tickets, loading: ticketsLoading, createTicket } = useTickets(); + + const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard"); + const [showNewTicket, setShowNewTicket] = useState(false); + const [showSettings, setShowSettings] = useState(false); + const [selectedTicket, setSelectedTicket] = useState(null); + + if (!token) { + return ; + } + + if (authLoading && !user) { + return ( +
+
+ +

Connecting to ecosystem...

+
+
+
+ ); + } + + const activeCount = tickets.filter(t => ["open", "acknowledged", "in_progress"].includes(t.status?.toLowerCase())).length; + + const pageConfig: Record = { + dashboard: { title: "Dashboard", subtitle: `Welcome back, ${user?.full_name?.split(' ')[0] || user?.email?.split('@')[0] || 'User'}` }, + tickets: { title: "Ticket Queue", subtitle: `${activeCount} active tasks Β· ${tickets.length} total cases` }, + kb: { title: "Knowledge Base", subtitle: "Browse self-service articles and guides" }, + analytics: { title: "Workspace Analytics", subtitle: "Operational performance and engagement metrics" }, + workspace: { title: "Workspace Settings", subtitle: "Organization identity, team members, and role-based access" }, + thread: { title: "Ticket Investigation", subtitle: selectedTicket?.id?.slice(0, 8) || 'Conversation' }, + }; + + const currentPage = pageConfig[active] || pageConfig.dashboard; + + const handleCreateTicket = async (form: any) => { + try { + await createTicket(form); + setShowNewTicket(false); + setActive("tickets"); + } catch (err) { + console.error("Failed to create ticket:", err); + } + }; + + return ( +
+ { setActive(v); setSelectedTicket(null); }} + onNewTicket={() => setShowNewTicket(true)} + onSettings={() => setShowSettings(true)} + user={user} + /> + +
+ {active !== "thread" && ( + { + setSelectedTicket(t); + setActive("thread"); + }} + /> + )} + +
+ {active === "dashboard" && ( + + )} + {active === "tickets" && ( + + )} + {active === "thread" && selectedTicket && ( + setActive("tickets")} + onNavigate={(t: any) => setSelectedTicket(t)} + /> + )} + {active === "kb" && setShowNewTicket(true)} />} + {active === "analytics" && } + {active === "workspace" && } +
+
+ + {showNewTicket && ( + setShowNewTicket(false)} + onCreate={handleCreateTicket} + /> + )} + + {showSettings && ( + setShowSettings(false)} + onUpdate={async () => { + await refreshUser(); + }} + /> + )} + + +
+ ); +} diff --git a/frontend/apps/customer/src/assets/react.svg b/frontend/apps/customer/src/assets/react.svg new file mode 100644 index 0000000000000000000000000000000000000000..6c87de9bb3358469122cc991d5cf578927246184 --- /dev/null +++ b/frontend/apps/customer/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/apps/customer/src/assets/vite.svg b/frontend/apps/customer/src/assets/vite.svg new file mode 100644 index 0000000000000000000000000000000000000000..5101b674df391399da71c767aa5c976426c9dc7a --- /dev/null +++ b/frontend/apps/customer/src/assets/vite.svg @@ -0,0 +1 @@ +Vite diff --git a/frontend/apps/customer/src/components/Analytics.tsx b/frontend/apps/customer/src/components/Analytics.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9082a5f63fce77d472563e8820c730086ff34915 --- /dev/null +++ b/frontend/apps/customer/src/components/Analytics.tsx @@ -0,0 +1,333 @@ +import React, { useState, useEffect } from 'react'; +import { StatusBadge, PriorityBadge } from './Badges'; +import { api } from '@nexus/shared'; +import ReactMarkdown from 'react-markdown'; + +const COLORS = { + brand: "#1E40AF", + brandLight: "rgba(30, 64, 175, 0.1)", + gray50: "#F9FAFB", + gray100: "#F3F4F6", + gray200: "#E5E7EB", + gray400: "#9CA3AF", + gray500: "#6B7280", + gray700: "#374151", + gray800: "#1F2937", + gray900: "#111827", +}; + +interface AnalyticsProps { + tickets: any[]; +} + +const Sparkline: React.FC<{ data: number[], color: string }> = ({ data, color }) => { + if (!data || data.length === 0) return null; + const max = Math.max(...data, 1); + const width = 100; + const height = 30; + const points = data.map((v, i) => `${(i / (data.length - 1)) * width},${height - (v / max) * height}`).join(' '); + return ( + + + + ); +}; + +export const Analytics: React.FC = ({ tickets }) => { + const [volumeData, setVolumeData] = useState>({}); + const [slaData, setSlaData] = useState(null); + const [csatData, setCsatData] = useState(null); + const [insights, setInsights] = useState(""); + const [loading, setLoading] = useState(true); + const [isResummarizing, setIsResummarizing] = useState(false); + + useEffect(() => { + fetchAnalytics(); + }, [tickets]); + + const fetchAnalytics = async () => { + setLoading(true); + try { + const [vol, sla, csat, ins] = await Promise.all([ + api.get('/reports/volume'), + api.get('/reports/sla'), + api.get('/reports/csat'), + api.get('/reports/insights') + ]); + setVolumeData(vol.data); + setSlaData(sla.data); + setCsatData(csat.data); + setInsights(ins.data.insights || ""); + } catch (err) { + console.error("Failed to fetch rich analytics:", err); + } finally { + setLoading(false); + } + }; + + const handleResummarize = async () => { + setIsResummarizing(true); + try { + const res = await api.get('/reports/insights'); + setInsights(res.data.insights || ""); + } catch (err) { + console.error("Resummarization failed:", err); + } finally { + setIsResummarizing(false); + } + }; + + const resolvedCount = tickets.filter(t => t.status === "RESOLVED" || t.status === "CLOSED").length; + const total = tickets.length; + const volumeValues = Object.values(volumeData); + + // --- Local Aggregations --- + const categoryCounts = tickets.reduce((acc: any, t) => { + const cat = t.category || "Uncategorized"; + acc[cat] = (acc[cat] || 0) + 1; + return acc; + }, {}); + const sortedCategories = Object.entries(categoryCounts).sort((a: any, b: any) => b[1] - a[1]); + + const priorityCounts = tickets.reduce((acc: any, t) => { + const rawPrio = (t.priority || "P2").toUpperCase(); + const PRIO_MAP: Record = { "P0": "URGENT", "P1": "HIGH", "P2": "MEDIUM", "P3": "LOW" }; + const prio = PRIO_MAP[rawPrio] || rawPrio; + acc[prio] = (acc[prio] || 0) + 1; + return acc; + }, {}); + + // --- Avg. Resolution Calculation --- + const resolvedTickets = tickets.filter(t => t.resolved_at && (t.status === "RESOLVED" || t.status === "CLOSED")); + let avgResHours = 0; + if (resolvedTickets.length > 0) { + const totalHours = resolvedTickets.reduce((acc, t) => { + const start = new Date(t.created_at).getTime(); + const end = new Date(t.resolved_at!).getTime(); + return acc + (end - start) / (1000 * 60 * 60); + }, 0); + avgResHours = totalHours / resolvedTickets.length; + } + + return ( +
+ {/* Header */} +
+

Workspace Analytics

+

Real-time operational metrics and historical trends

+
+ + {/* KPI Stats Grid */} +
+ {[ + { + label: "Active Tickets", + value: total - resolvedCount, + footer: `${total} Total Tickets`, + color: "hsl(217, 91%, 60%)", + icon: "πŸ“Š", + viz: 0 ? volumeValues : [0,0,0]} color="hsl(217, 91%, 60%)" /> + }, + { + label: "SLA Compliance", + value: slaData ? `${Math.round(slaData.sla_compliance_rate * 100)}%` : "100%", + footer: `${slaData?.breached_tickets || 0} Rule Breaches`, + color: "hsl(142, 71%, 45%)", + icon: "⚑", + viz:
+
+
+ }, + { + label: "Avg. Resolution", + value: avgResHours > 0 ? `${avgResHours.toFixed(1)}h` : "β€”", + footer: `${resolvedCount} Resolved Tickets`, + color: "hsl(262, 83%, 58%)", + icon: "βœ…", + viz:
Operational Threshold: 24h
+ }, + { + label: "CSAT Score", + value: csatData ? `${csatData.average_rating.toFixed(1)} / 5` : "4.8", + footer: `${csatData?.total_responses || 0} Valid Ratings`, + color: "hsl(38, 92%, 50%)", + icon: "⭐", + viz:
{"β˜…".repeat(Math.round(csatData?.average_rating || 5)) + "β˜†".repeat(5 - Math.round(csatData?.average_rating || 5))}
+ }, + ].map(s => ( +
+
+
+ {s.label} + {s.icon} +
+
{s.value}
+
+
+
{s.viz}
+
{s.footer}
+
+
+ ))} +
+ +
+ {/* Category Breakdown */} +
+
+ Ticket Volume by Category + Distribution Analysis +
+
+ {sortedCategories.length > 0 ? sortedCategories.map(([cat, count]: any) => ( +
+
+ {cat} + {count} +
+
+
+
+
+ )) :
No categorical data available
} +
+
+ + {/* Priority Breakdown */} +
+
Priority Distribution
+
+ {["URGENT", "HIGH", "MEDIUM", "LOW"].map(prio => { + const count = priorityCounts[prio] || 0; + const height = total > 0 ? (count / total) * 140 : 0; + return ( +
+
+ {prio} + {count} +
+ ); + })} +
+
+
+ + {/* Nexus Intelligence - Professional Narrative */} +
+ +
+
+
+ Nexus Workspace Intelligence +
+
+
+ AI-Synthesized Report +
+ +
+
+
+ {loading ? "Synthesizing workspace health narrative..." : ( +
+ {insights || "Workspace metrics are within normal operational parameters. All systems reporting healthy compliance levels."} +
+ )} +
+
+ +
+
Operational Activity History
+
+ + + + {["Ticket", "Subject", "Status", "Priority", "Duration"].map(h => ( + + ))} + + + + {tickets.slice(0, 10).map(t => ( + + + + + + + + ))} + +
{h}
{t.id.slice(0, 8)}{t.title} + {t.resolved_at ? `${Math.round((new Date(t.resolved_at).getTime() - new Date(t.created_at).getTime()) / (1000 * 60 * 60))}h` : "β€”"} +
+
+
+
+ ); +}; diff --git a/frontend/apps/customer/src/components/Badges.tsx b/frontend/apps/customer/src/components/Badges.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8e5a39e8e3f4c069f6c52dd8483640fe669ddc92 --- /dev/null +++ b/frontend/apps/customer/src/components/Badges.tsx @@ -0,0 +1,53 @@ +import React from 'react'; + +export const statusConfig: Record = { + OPEN: { label: "Open", bg: "#EFF6FF", color: "#1E40AF", dot: "#3B82F6" }, + ACKNOWLEDGED: { label: "Acknowledged", bg: "#F0FDF4", color: "#065F46", dot: "#10B981" }, + IN_PROGRESS: { label: "In Progress", bg: "#FFFBEB", color: "#92400E", dot: "#F59E0B" }, + RESOLVED: { label: "Resolved", bg: "#F0FDF4", color: "#14532D", dot: "#22C55E" }, + CLOSED: { label: "Closed", bg: "#F9FAFB", color: "#4B5563", dot: "#9CA3AF" }, +}; + +export const priorityConfig: Record = { + P0: { label: "Urgent", color: "#DC2626", bg: "#FEF2F2" }, + P1: { label: "High", color: "#EA580C", bg: "#FFF7ED" }, + P2: { label: "Medium", color: "#D97706", bg: "#FFFBEB" }, + P3: { label: "Low", color: "#65A30D", bg: "#F7FEE7" }, +}; + +export const StatusBadge: React.FC<{ status: string }> = ({ status }) => { + const c = statusConfig[status.toUpperCase()] || statusConfig.OPEN; + return ( + + + {c.label} + + ); +} + +export const PriorityBadge: React.FC<{ priority: string }> = ({ priority }) => { + const c = priorityConfig[priority.toUpperCase()] || priorityConfig.MEDIUM; + return ( + + {c.label} + + ); +} diff --git a/frontend/apps/customer/src/components/ChatWindow.module.css b/frontend/apps/customer/src/components/ChatWindow.module.css new file mode 100644 index 0000000000000000000000000000000000000000..5be41731c38f0c668b3f93561ca4ed151d06950e --- /dev/null +++ b/frontend/apps/customer/src/components/ChatWindow.module.css @@ -0,0 +1,79 @@ +.container { + display: flex; + flex-direction: column; + height: 100%; + max-width: 800px; + margin: 0 auto; + padding: 24px; +} + +.messages { + flex: 1; + overflow-y: auto; + padding: 16px; + display: flex; + flex-direction: column; + gap: 16px; + scrollbar-width: thin; +} + +.bubble { + max-width: 70%; + padding: 12px 18px; + border-radius: var(--radius-md); + font-size: 15px; + line-height: 1.4; +} + +.user { + align-self: flex-end; + background-color: var(--primary); + color: var(--text-inverse); + box-shadow: 0 4px 12px 0 var(--primary-glow); +} + +.assistant { + align-self: flex-start; + background-color: var(--bg-card); + color: var(--text-main); + border: 1px solid var(--border-subtle); +} + +.footer { + padding: 16px; + background-color: var(--bg-dark); + border-top: 1px solid var(--border-subtle); + display: flex; + gap: 12px; + align-items: flex-end; +} + +.input { + flex: 1; +} + +.sendBtn { + margin-bottom: 2px; +} + +/* Loading animation */ +.loading { + display: flex; + gap: 4px; + padding: 16px 20px; +} + +.dot { + width: 6px; + height: 6px; + background-color: var(--text-muted); + border-radius: 50%; + animation: bounce 0.6s infinite alternate; +} + +.dot:nth-child(2) { animation-delay: 0.2s; } +.dot:nth-child(3) { animation-delay: 0.4s; } + +@keyframes bounce { + to { transform: translateY(-4px); opacity: 0.5; } +} diff --git a/frontend/apps/customer/src/components/ChatWindow.tsx b/frontend/apps/customer/src/components/ChatWindow.tsx new file mode 100644 index 0000000000000000000000000000000000000000..613c983544c8799866b53d3048b462aaff430260 --- /dev/null +++ b/frontend/apps/customer/src/components/ChatWindow.tsx @@ -0,0 +1,91 @@ +import React, { useState, useRef, useEffect } from 'react'; +import { motion, AnimatePresence } from 'framer-motion'; +import { Button, Input } from '@nexus/shared'; +import styles from './ChatWindow.module.css'; + +interface Message { + role: 'user' | 'assistant'; + content: string; +} + +interface ChatWindowProps { + messages: Message[]; + onSendMessage: (text: string) => void; + loading?: boolean; +} + +export const ChatWindow: React.FC = ({ messages, onSendMessage, loading }) => { + const [input, setInput] = useState(''); + const scrollRef = useRef(null); + + useEffect(() => { + if (scrollRef.current) { + scrollRef.current.scrollTop = scrollRef.current.scrollHeight; + } + }, [messages, loading]); + + const handleSend = () => { + if (!input.trim()) return; + onSendMessage(input); + setInput(''); + }; + + return ( +
+
+ + {messages.length === 0 ? ( + +

Nexus is Ready

+

How can I assist you with your workspace today?

+
+ ) : ( + messages.map((msg, idx) => ( + +

{msg.content}

+
+ )) + )} + {loading && ( + +
+
+
+
+ )} +
+
+ +
+ setInput(e.target.value)} + onKeyPress={(e) => e.key === 'Enter' && handleSend()} + className={styles.input} + /> + +
+
+ ); +}; diff --git a/frontend/apps/customer/src/components/Dashboard.tsx b/frontend/apps/customer/src/components/Dashboard.tsx new file mode 100644 index 0000000000000000000000000000000000000000..139854a35ddac29590b618929f86d5df9c73fae6 --- /dev/null +++ b/frontend/apps/customer/src/components/Dashboard.tsx @@ -0,0 +1,227 @@ +import React, { useState, useEffect } from 'react'; +import { StatusBadge } from './Badges'; +import { api } from '@nexus/shared'; + +const COLORS = { + brand: "#1E40AF", + success: "#16A34A", + gray100: "#F3F4F6", + gray200: "#E5E7EB", + gray300: "#D1D5DB", + gray400: "#9CA3AF", + gray500: "#6B7280", + gray800: "#1F2937", + gray900: "#111827", + gray50: "#F9FAFB", + gray600: "#4B5563", +}; + +// MOCK_KB constant removed to use live data + +interface DashboardProps { + setActive: (tab: any) => void; + setSelectedTicket: (ticket: any) => void; + tickets: any[]; + loading: boolean; + user: any; +} + +export const Dashboard: React.FC = ({ setActive, setSelectedTicket, tickets, loading, user }) => { + const [suggestedArticles, setSuggestedArticles] = useState([]); + const [kbLoading, setKbLoading] = useState(false); + const [stats, setStats] = useState(null); + + const userTickets = user ? tickets.filter(t => t.created_by === user.id) : []; + const activeTickets = userTickets + .filter(t => t.status.toLowerCase() === "open" || t.status.toLowerCase() === "in_progress") + .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); + + useEffect(() => { + const fetchStats = async () => { + try { + const res = await api.get('/dashboard/stats'); + setStats(res.data); + } catch (err) { + console.error("Dashboard Stats Fetch Failed:", err); + } + }; + + const fetchSuggestions = async () => { + setKbLoading(true); + try { + if (activeTickets.length > 0) { + // Perform contextual search based on latest ticket + const res = await api.get('/kb/search', { params: { q: activeTickets[0].title } }); + setSuggestedArticles(res.data.results || []); + } else { + // Fallback to top recent articles + const res = await api.get('/kb/'); + setSuggestedArticles(res.data.slice(0, 4)); + } + } catch (err) { + console.error("Failed to fetch KB suggestions:", err); + } finally { + setKbLoading(false); + } + }; + + if (user) { + fetchStats(); + fetchSuggestions(); + } + }, [user, tickets.length]); + + const resolvedTickets = userTickets.filter(t => (t.status.toLowerCase() === "resolved" || t.status.toLowerCase() === "closed")); + const resolvedCount = resolvedTickets.length; + + // Calculate Resolution compliance against 72h threshold + const avgResVal = stats?.performance?.avg_resolution_hours || 0; + const avgResStr = avgResVal > 0 ? `${avgResVal}h` : "N/A"; + const withinThreshold = avgResVal > 0 && avgResVal <= 72; + + // CSAT Score from backend + const csatVal = stats?.performance?.csat_score || 0; + const csatStr = csatVal > 0 ? csatVal.toFixed(1) + "β˜…" : "N/A"; + const ratedCount = stats?.performance?.rated_count || 0; + + return ( +
+
+ {/* Left Section: Context */} +
+
Good morning,
+
{user?.full_name || 'Support Hub'}
+
+ {user ? ( + <>You have {activeTickets.length} open tickets and {tickets.length > 0 ? '1' : '0'} awaiting your reply. + ) : ( + "Loading your ecosystem..." + )} +
+ +
+ + {/* Right Section: Workspace Intelligence Hub */} +
+ {[ + { label: "WORKSPACE VOLUME", value: stats?.total_tickets || "0", sub: "Lifetime Tickets", icon: "πŸ“Š" }, + { label: "ACTIVE LOAD", value: (stats?.by_status?.open || 0) + (stats?.by_status?.in_progress || 0), sub: "Open Cases", icon: "⚑" }, + { label: "RESOLVED SUCCESS", value: stats?.by_status?.resolved || "0", sub: "Completed Tasks", icon: "βœ…" } + ].map(s => ( +
+
+
{s.label}
+
{s.icon}
+
+
{s.value}
+
{s.sub}
+
+ ))} +
+
+ +
+ {[ + { label: "Open tickets", value: activeTickets.length.toString(), sub: "Active cases", color: COLORS.brand }, + { label: "Resolved (Total)", value: resolvedCount.toString(), sub: "Lifetime count", color: COLORS.success }, + { + label: "Avg. resolution", + value: avgResStr, + sub: avgResVal > 0 ? `Threshold: 72h ${withinThreshold ? "βœ…" : "⚠️"}` : "Based on history", + color: withinThreshold ? COLORS.success : (avgResVal > 72 ? "#EF4444" : "#7C3AED") + }, + { + label: "CSAT score", + value: csatStr, + sub: ratedCount > 0 ? `${ratedCount} Valid Ratings` : "Based on feedback", + color: "#D97706" + }, + ].map(s => ( +
+
{s.label}
+
{s.value}
+
{s.sub}
+
+ ))} +
+ +
+
+
Latest updates
+ {loading ? ( +
Syncing with backend...
+ ) : activeTickets.length === 0 ? ( +
No active tickets
+ ) : activeTickets.slice(0, 5).map(t => ( +
{ setSelectedTicket(t); setActive("thread"); }} style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 0", borderTop: `1px solid ${COLORS.gray100}`, cursor: "pointer" }}> +
+
{t.title}
+
+ {t.id} + Β· + +
+
+
{new Date(t.created_at).toLocaleDateString()}
+
+ ))} +
+ +
+
+
Suggested articles
+ +
+ {kbLoading ? ( +
Analyzing Knowledge Base...
+ ) : suggestedArticles.length === 0 ? ( +
No relevant suggestions found.
+ ) : suggestedArticles.map(a => ( +
+
{a.title}
+
+ {a.category || "General"} + {a.score && ( + {(a.score * 100).toFixed(0)}% match + )} +
+
+ ))} +
+
+
+ ); +}; diff --git a/frontend/apps/customer/src/components/KnowledgeBase.tsx b/frontend/apps/customer/src/components/KnowledgeBase.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7e728a1c3451f3502f193fb1d22fbace1978c12c --- /dev/null +++ b/frontend/apps/customer/src/components/KnowledgeBase.tsx @@ -0,0 +1,352 @@ +import React, { useState, useEffect } from 'react'; +import { api } from '@nexus/shared'; + +const COLORS = { + brand: "#1E40AF", + brandLight: "#EFF6FF", + success: "#16A34A", + gray50: "#F9FAFB", + gray100: "#F3F4FB", + gray200: "#E5E7EB", + gray300: "#D1D5DB", + gray400: "#9CA3AF", + gray500: "#6B7280", + gray600: "#4B5563", + gray700: "#374151", + gray800: "#1F2937", + gray900: "#111827", +}; + +const ITEMS_PER_PAGE = 4; + +interface KnowledgeBaseProps { + onNewTicket?: () => void; +} + +export const KnowledgeBase: React.FC = ({ onNewTicket }) => { + const [articles, setArticles] = useState([]); + const [categories, setCategories] = useState([]); + const [loading, setLoading] = useState(true); + const [search, setSearch] = useState(""); + const [searchInput, setSearchInput] = useState(""); + const [suggestions, setSuggestions] = useState([]); + const [activeCategory, setActiveCategory] = useState(null); + const [sortBy, setSortBy] = useState<"newest" | "oldest">("newest"); + const [page, setPage] = useState(1); + const [selectedArticle, setSelectedArticle] = useState(null); + + useEffect(() => { + fetchCategories(); + }, []); + + useEffect(() => { + const delayDebounceFn = setTimeout(() => { + fetchArticles(); + }, search ? 400 : 0); + + return () => clearTimeout(delayDebounceFn); + }, [search, activeCategory, sortBy]); + + const fetchCategories = async () => { + try { + const res = await api.get('/kb/categories'); + setCategories(res.data || []); + } catch (err) { + console.error("Failed to load categories:", err); + } + }; + + const fetchArticles = async () => { + setLoading(true); + try { + let res; + if (search.trim().length > 1) { + res = await api.get('/kb/search', { params: { q: search, category: activeCategory } }); + setArticles(res.data.results || []); + setSuggestions(res.data.expanded_queries || []); + } else { + res = await api.get('/kb/', { params: { category: activeCategory } }); + let data = res.data || []; + // Local Sorting + data.sort((a: any, b: any) => { + const dateA = new Date(a.created_at).getTime(); + const dateB = new Date(b.created_at).getTime(); + return sortBy === "newest" ? dateB - dateA : dateA - dateB; + }); + setArticles(data); + setSuggestions([]); + } + setPage(1); + } catch (err) { + console.error("Failed to load KB articles:", err); + } finally { + setLoading(false); + } + }; + + const renderRichContent = (content: string) => { + if (!content) return null; + + // Pattern for Markdown images: ![alt](url) + const imgRegex = /!\[(.*?)\]\((.*?)\)/g; + const parts = content.split(imgRegex); + + const result = []; + for (let i = 0; i < parts.length; i++) { + if (i % 3 === 0) { + // Regular text + if (parts[i]) { + result.push( +
+ {parts[i]} +
+ ); + } + } else if (i % 3 === 1) { + // Alt text (skip, handled by next index) + continue; + } else { + // URL + const alt = parts[i-1]; + const url = parts[i]; + result.push( + {alt} + ); + } + } + + return result; + }; + + const paginated = articles.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE); + const totalPages = Math.ceil(articles.length / ITEMS_PER_PAGE); + + if (selectedArticle) { + return ( +
+ + +
+
+ + {selectedArticle.category || "N/A"} + + + Published by Admin β€’ {new Date(selectedArticle.created_at).toLocaleDateString()} + +
+

+ {selectedArticle.title} +

+
+
+ +
+ {renderRichContent(selectedArticle.content)} +
+ +
+
Found this guide useful?
+
If you still need assistance, our support team is available 24/7.
+ +
+
+ ); + } + + return ( +
+ {/* Premium Search Hero */} +
+

Knowledge Base

+

Expert guides and troubleshooting for everything Nexus.

+ +
+
+ setSearchInput(e.target.value)} + onKeyDown={e => { + if (e.key === 'Enter') { + setSearch(searchInput); + } + }} + placeholder="How can we help you today?" + style={{ + width: "100%", padding: "16px 20px 16px 52px", borderRadius: 16, border: `1px solid ${COLORS.gray200}`, + fontSize: 16, boxSizing: "border-box", outline: "none", boxShadow: "0 2px 10px rgba(0,0,0,0.03)", transition: "all 0.2s" + }} + /> + + πŸ” + {loading && searchInput.length > 0 && Searching AI...} +
+ +
+ SORT BY: + +
+
+ + {/* AI Suggestions */} + {suggestions.length > 0 && ( +
+ Suggestions: + {suggestions.map(s => ( + + ))} +
+ )} +
+ + {/* Category Toolbar */} +
+ + {categories.map(cat => ( + + ))} +
+ + {/* Article Feed */} + {loading && articles.length === 0 ? ( +
+
Connecting to help library...
+
+ ) : articles.length === 0 ? ( +
+
πŸ”
+

We couldn't find that

+

Try searching for broader terms or check a different category.

+
+ ) : ( +
+
+ {paginated.map(article => ( +
setSelectedArticle(article)} + style={{ cursor: "pointer", display: "flex" }} + > +
{ + e.currentTarget.style.transform = "translateY(-4px)"; + e.currentTarget.style.boxShadow = "0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 10px 10px -5px rgba(0, 0, 0, 0.04)"; + e.currentTarget.style.borderColor = COLORS.brand; + }} + onMouseLeave={e => { + e.currentTarget.style.transform = "none"; + e.currentTarget.style.boxShadow = "0 2px 4px rgba(0,0,0,0.02)"; + e.currentTarget.style.borderColor = COLORS.gray100; + }} + > + {article.category || "N/A"} +

{article.title}

+

+ {article.content.slice(0, 180)}... +

+
+ Published {new Date(article.created_at).toLocaleDateString()} + Read Guide β†’ +
+
+
+ ))} +
+ + {/* Pagination */} + {totalPages > 1 && ( +
+ +
Page {page} of {totalPages}
+ +
+ )} +
+ )} +
+ ); +}; diff --git a/frontend/apps/customer/src/components/NewTicketModal.tsx b/frontend/apps/customer/src/components/NewTicketModal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0a97906047adb23be9d19a6c5882bee649a7c2f6 --- /dev/null +++ b/frontend/apps/customer/src/components/NewTicketModal.tsx @@ -0,0 +1,94 @@ +import React, { useState } from 'react'; + +const COLORS = { + brand: "#1E40AF", + brandLight: "#EFF6FF", + gray200: "#E5E7EB", + gray400: "#9CA3AF", + gray500: "#6B7280", + gray600: "#4B5563", + gray800: "#1F2937", + gray900: "#111827", +}; + +interface NewTicketModalProps { + onClose: () => void; + onCreate: (form: any) => void; +} + +export const NewTicketModal: React.FC = ({ onClose, onCreate }) => { + const [form, setForm] = useState({ title: "", category: "Software", priority: "P2", description: "" }); + const [submitted, setSubmitted] = useState(false); + const [loading, setLoading] = useState(false); + + const handleSubmit = async () => { + if (!form.title || !form.description) return; + + setLoading(true); + try { + await onCreate(form); + setSubmitted(true); + setTimeout(onClose, 2000); + } catch (err) { + console.error("Submission failed", err); + // We could add local error state here if needed + } finally { + setLoading(false); + } + }; + + return ( +
+
+ {submitted ? ( +
+
βœ“
+
Ticket submitted!
+
Our AI is triaging your request now...
+
+ ) : ( + <> +
+
Create new ticket
+ +
+
+
+ + setForm(f => ({ ...f, title: e.target.value }))} placeholder="Briefly describe your issue" style={{ width: "100%", padding: "9px 12px", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, outline: "none", boxSizing: "border-box", color: COLORS.gray900, background: "#fff" }} /> +
+
+
+ + +
+
+ + +
+
+
+ +