Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
4777084
1
Parent(s): 2f81f65
backend stabilization
Browse files- api/v1/tickets.py +28 -1529
- core/tasks.py +0 -0
- frontend/apps/customer/src/components/KnowledgeBase.module.css +5 -5
- frontend/apps/customer/src/components/ThreadView.tsx +12 -65
- frontend/apps/internal/src/components/TicketDetails.tsx +9 -49
- frontend/packages/shared/package.json +4 -1
- frontend/packages/shared/src/hooks/useTickets.ts +1 -24
- frontend/packages/shared/src/hooks/useTicketsPaginated.ts +1 -1
- frontend/packages/shared/src/index.ts +2 -1
- frontend/packages/shared/src/types/index.ts +1 -0
- frontend/packages/shared/src/types/ticket.ts +76 -0
- frontend/packages/shared/tsconfig.json +2 -1
- services/__init__.py +1 -0
- services/ticket_service.py +191 -0
- tasks/__init__.py +1 -0
- tasks/ai.py +300 -0
- tasks/analytics.py +65 -0
- tasks/notifications.py +94 -0
- tasks/remediation.py +41 -0
- tasks/system.py +413 -0
api/v1/tickets.py
CHANGED
|
@@ -1,1584 +1,83 @@
|
|
| 1 |
"""
|
| 2 |
-
Ticket endpoints: CRUD, status transitions, and assignments.
|
| 3 |
"""
|
| 4 |
|
| 5 |
-
from
|
| 6 |
-
import asyncio
|
| 7 |
-
import hashlib
|
| 8 |
-
import time
|
| 9 |
-
import uuid
|
| 10 |
from uuid import UUID
|
| 11 |
-
from
|
| 12 |
-
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
|
| 13 |
-
from fastapi.encoders import jsonable_encoder
|
| 14 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 15 |
-
from sqlalchemy import select
|
| 16 |
from sqlalchemy.orm import joinedload
|
| 17 |
-
from core.database import async_session_factory
|
| 18 |
|
| 19 |
-
from arq import ArqRedis
|
| 20 |
from core.deps import get_db, get_current_user, get_arq_pool
|
| 21 |
-
from core.
|
| 22 |
-
from
|
| 23 |
-
from
|
| 24 |
-
from core.permissions import require_roles, ALL_SC_ROLES, WORKSPACE_ADMIN_ROLES, ALL_CUSTOMER_ROLES
|
| 25 |
-
from core.logging import get_logger
|
| 26 |
-
from models.user import User, UserRole
|
| 27 |
-
from models.user_workspace import UserWorkspace
|
| 28 |
-
from models.project import Project
|
| 29 |
-
from models.ticket import Ticket, TicketStatus, ALLOWED_TRANSITIONS, TicketPriority
|
| 30 |
-
from models.audit_log import AuditLog
|
| 31 |
-
from models.escalation_rule import EscalationRule
|
| 32 |
from schemas.ticket import (
|
| 33 |
-
TicketCreate, TicketUpdate, TicketResponse, TicketInternalResponse
|
| 34 |
-
TicketSearchResponse, TicketSearchResult, PaginatedTicketResponse, PaginatedInternalResponse
|
| 35 |
)
|
| 36 |
-
from
|
| 37 |
-
from core.llm import get_text_embeddings
|
| 38 |
-
from models.attachment import Attachment
|
| 39 |
-
from models.message import Message
|
| 40 |
|
| 41 |
router = APIRouter()
|
| 42 |
-
logger = get_logger(__name__)
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
user: User,
|
| 47 |
-
db: AsyncSession,
|
| 48 |
-
lead_name: Optional[str] = None,
|
| 49 |
-
dup_title: Optional[str] = None
|
| 50 |
-
) -> Ticket:
|
| 51 |
-
"""
|
| 52 |
-
Helper to inject role-based summary, names, and mask internal metadata.
|
| 53 |
-
Supports pre-fetched context to avoid N+1 queries.
|
| 54 |
-
"""
|
| 55 |
-
is_staff = user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 56 |
-
|
| 57 |
-
# 1. Summary Injection
|
| 58 |
-
if ticket.ai_metadata and "summaries" in ticket.ai_metadata:
|
| 59 |
-
summaries = ticket.ai_metadata.get("summaries", {})
|
| 60 |
-
summary_val = summaries.get("internal_summary" if is_staff else "customer_summary")
|
| 61 |
-
setattr(ticket, "summary", summary_val)
|
| 62 |
-
else:
|
| 63 |
-
setattr(ticket, "summary", None)
|
| 64 |
-
|
| 65 |
-
# 2. Assignee Name Lookup (Using pre-loaded relationship)
|
| 66 |
-
if ticket.assignee:
|
| 67 |
-
setattr(ticket, "assigned_name", ticket.assignee.full_name)
|
| 68 |
-
else:
|
| 69 |
-
setattr(ticket, "assigned_name", None)
|
| 70 |
-
|
| 71 |
-
# 3. Similarity Extraction (Articles & Tickets)
|
| 72 |
-
articles = []
|
| 73 |
-
similar_t = []
|
| 74 |
-
if ticket.ai_metadata:
|
| 75 |
-
# Articles (Shared logic from suggestion phase)
|
| 76 |
-
if "suggestion_sources" in ticket.ai_metadata:
|
| 77 |
-
articles = ticket.ai_metadata["suggestion_sources"].get("kb_articles", [])
|
| 78 |
-
|
| 79 |
-
# Tickets (Tiered Access: Staff see all, Customers see own matches)
|
| 80 |
-
similar_key = "similar_tickets" if is_staff else "customer_proximity"
|
| 81 |
-
similar_t = ticket.ai_metadata.get(similar_key, [])
|
| 82 |
-
|
| 83 |
-
setattr(ticket, "similar_articles", articles)
|
| 84 |
-
setattr(ticket, "similar_tickets", similar_t)
|
| 85 |
-
|
| 86 |
-
# 4. Resolution & Resolver Fallbacks (UI Safeguard)
|
| 87 |
-
is_resolved = ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]
|
| 88 |
-
|
| 89 |
-
# Resolver Name lookup (Using pre-loaded relationship)
|
| 90 |
-
if ticket.resolver:
|
| 91 |
-
setattr(ticket, "resolved_by_name", ticket.resolver.full_name)
|
| 92 |
-
elif is_resolved:
|
| 93 |
-
# Fallback to a well-known name if no resolver is explicitly set
|
| 94 |
-
settings = get_settings()
|
| 95 |
-
setattr(ticket, "resolved_by_name", settings.SUPER_ADMIN_NAME)
|
| 96 |
-
else:
|
| 97 |
-
setattr(ticket, "resolved_by_name", None)
|
| 98 |
-
|
| 99 |
-
# Resolution text fallback
|
| 100 |
-
if is_resolved and not ticket.resolution_text:
|
| 101 |
-
setattr(ticket, "resolution_text", "This issue has been resolved. Thanks!")
|
| 102 |
-
|
| 103 |
-
# Resolved at fallback (avoid "TBD")
|
| 104 |
-
if is_resolved and not ticket.resolved_at:
|
| 105 |
-
setattr(ticket, "resolved_at", ticket.sla_deadline or ticket.created_at)
|
| 106 |
-
|
| 107 |
-
# 5. Escalation Lead Lookup (Optimized)
|
| 108 |
-
setattr(ticket, "escalated_to_name", lead_name)
|
| 109 |
-
# Only hit DB if not pre-fetched (backward compatibility)
|
| 110 |
-
if ticket.is_escalated and not lead_name:
|
| 111 |
-
stmt = select(User.full_name).join(UserWorkspace).where(
|
| 112 |
-
UserWorkspace.workspace_id == ticket.workspace_id,
|
| 113 |
-
UserWorkspace.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]),
|
| 114 |
-
User.is_active
|
| 115 |
-
).limit(1)
|
| 116 |
-
res = await db.execute(stmt)
|
| 117 |
-
setattr(ticket, "escalated_to_name", res.scalar_one_or_none())
|
| 118 |
-
|
| 119 |
-
# 6. Duplicate Title Lookup (Optimized)
|
| 120 |
-
setattr(ticket, "duplicate_of_title", dup_title)
|
| 121 |
-
# Only hit DB if not pre-fetched
|
| 122 |
-
if ticket.duplicate_of_id and not dup_title:
|
| 123 |
-
dup_stmt = select(Ticket.title).where(Ticket.id == ticket.duplicate_of_id)
|
| 124 |
-
dup_res = await db.execute(dup_stmt)
|
| 125 |
-
setattr(ticket, "duplicate_of_title", dup_res.scalar_one_or_none())
|
| 126 |
-
|
| 127 |
-
# 7. Ownership Identity (Frontend Sync)
|
| 128 |
-
setattr(ticket, "is_mine", ticket.created_by == user.id)
|
| 129 |
-
|
| 130 |
-
# 9. Feedback Injection (Required for CSAT UI persistence)
|
| 131 |
-
# If pre-loaded via joinedload, this is free; otherwise it may trigger lazy load
|
| 132 |
-
if ticket.feedback:
|
| 133 |
-
setattr(ticket, "rating", ticket.feedback.rating)
|
| 134 |
-
setattr(ticket, "feedback_comment", ticket.feedback.comment)
|
| 135 |
-
else:
|
| 136 |
-
setattr(ticket, "rating", None)
|
| 137 |
-
setattr(ticket, "feedback_comment", None)
|
| 138 |
-
|
| 139 |
-
# 8. Metadata Sanitization & Internal Flag Injection
|
| 140 |
-
setattr(ticket, "creator_name", ticket.creator.full_name if ticket.creator else "System")
|
| 141 |
-
|
| 142 |
-
if is_staff:
|
| 143 |
-
# Staff get the full Internal Schema
|
| 144 |
-
return TicketInternalResponse.model_validate(ticket).model_dump(mode='json')
|
| 145 |
-
else:
|
| 146 |
-
# Customers get the Sanitized Public Schema
|
| 147 |
-
# .model_dump() physically removes any data not in TicketResponse
|
| 148 |
-
return TicketResponse.model_validate(ticket).model_dump(mode='json')
|
| 149 |
|
| 150 |
@router.post("/", response_model=Union[TicketInternalResponse, TicketResponse], status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ALL_CUSTOMER_ROLES + WORKSPACE_ADMIN_ROLES))])
|
| 151 |
async def create_ticket(
|
| 152 |
payload: TicketCreate,
|
| 153 |
-
background_tasks: BackgroundTasks,
|
| 154 |
current_user: User = Depends(get_current_user),
|
| 155 |
db: AsyncSession = Depends(get_db),
|
| 156 |
arq_pool: Any = Depends(get_arq_pool)
|
| 157 |
) -> Any:
|
| 158 |
-
"""Create a new ticket
|
| 159 |
-
|
| 160 |
-
stmt = select(Project).where(
|
| 161 |
-
Project.id == payload.project_id,
|
| 162 |
-
Project.workspace_id == current_user.workspace_id,
|
| 163 |
-
Project.deleted_at.is_(None)
|
| 164 |
-
)
|
| 165 |
-
result = await db.execute(stmt)
|
| 166 |
-
if not result.scalar_one_or_none():
|
| 167 |
-
raise HTTPException(status_code=400, detail="Project not found")
|
| 168 |
-
|
| 169 |
-
# 0. Deduplication via SHA-256 Hash (GAP-DEDUP)
|
| 170 |
-
payload_str = f"{payload.title.strip()}|{payload.description.strip()}"
|
| 171 |
-
c_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest()
|
| 172 |
-
|
| 173 |
-
dup_stmt = (
|
| 174 |
-
select(Ticket)
|
| 175 |
-
.options(
|
| 176 |
-
joinedload(Ticket.creator),
|
| 177 |
-
joinedload(Ticket.assignee),
|
| 178 |
-
joinedload(Ticket.resolver),
|
| 179 |
-
joinedload(Ticket.feedback)
|
| 180 |
-
)
|
| 181 |
-
.where(
|
| 182 |
-
Ticket.workspace_id == current_user.workspace_id,
|
| 183 |
-
Ticket.content_hash == c_hash,
|
| 184 |
-
Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
|
| 185 |
-
Ticket.deleted_at.is_(None)
|
| 186 |
-
)
|
| 187 |
-
.limit(1)
|
| 188 |
-
)
|
| 189 |
-
dup_res = await db.execute(dup_stmt)
|
| 190 |
-
existing_dup = dup_res.scalar_one_or_none()
|
| 191 |
-
|
| 192 |
-
if existing_dup:
|
| 193 |
-
logger.info(f"Ticket DUPLICATE detected (Hash): {existing_dup.id} in workspace {current_user.workspace_id}")
|
| 194 |
-
# Return existing but ensure ID is in results for frontend tracking if needed
|
| 195 |
-
return await sanitize_ticket_response(existing_dup, current_user, db)
|
| 196 |
-
|
| 197 |
-
# 1. Calculate SLA: Use EscalationRules if present, else 2 days
|
| 198 |
-
ticket_priority = payload.priority # Preserve None for AUTO
|
| 199 |
-
sla_deadline = payload.sla_deadline
|
| 200 |
-
|
| 201 |
-
if not sla_deadline:
|
| 202 |
-
# GAP-11 Cache Fix: Use workspace-level cache for rules
|
| 203 |
-
cache_key = f"sla_rules:{current_user.workspace_id}:{ticket_priority or 'P2'}"
|
| 204 |
-
from core.cache import get_cached_object, set_cached_object
|
| 205 |
-
rule = await get_cached_object(cache_key)
|
| 206 |
-
|
| 207 |
-
if not rule:
|
| 208 |
-
rule_stmt = select(EscalationRule).where(
|
| 209 |
-
EscalationRule.workspace_id == current_user.workspace_id,
|
| 210 |
-
EscalationRule.priority_level == cast(ticket_priority or TicketPriority.P2, String)
|
| 211 |
-
)
|
| 212 |
-
rule_obj = (await db.execute(rule_stmt)).scalar_one_or_none()
|
| 213 |
-
if rule_obj:
|
| 214 |
-
rule = {"threshold_minutes": rule_obj.threshold_minutes}
|
| 215 |
-
await set_cached_object(cache_key, rule, ttl=600) # 10 min
|
| 216 |
-
|
| 217 |
-
if rule:
|
| 218 |
-
sla_deadline = datetime.utcnow() + timedelta(minutes=rule["threshold_minutes"])
|
| 219 |
-
else:
|
| 220 |
-
sla_deadline = datetime.utcnow() + timedelta(days=2)
|
| 221 |
-
|
| 222 |
-
new_ticket = Ticket(
|
| 223 |
-
id=uuid.uuid4(),
|
| 224 |
-
workspace_id=current_user.workspace_id,
|
| 225 |
-
project_id=payload.project_id,
|
| 226 |
-
title=payload.title,
|
| 227 |
-
description=payload.description,
|
| 228 |
-
priority=ticket_priority,
|
| 229 |
-
category=payload.category,
|
| 230 |
-
created_by=current_user.id,
|
| 231 |
-
status=TicketStatus.OPEN,
|
| 232 |
-
sla_deadline=sla_deadline,
|
| 233 |
-
content_hash=c_hash
|
| 234 |
-
)
|
| 235 |
-
db.add(new_ticket)
|
| 236 |
-
|
| 237 |
-
# Associate miscellaneous attachments uploaded before ticket creation
|
| 238 |
-
if payload.attachment_ids:
|
| 239 |
-
logger.info(f"Linking {len(payload.attachment_ids)} attachments to new ticket {new_ticket.id}")
|
| 240 |
-
# Batch update attachments to link them to this ticket
|
| 241 |
-
att_stmt = (
|
| 242 |
-
update(Attachment)
|
| 243 |
-
.where(
|
| 244 |
-
Attachment.id.in_(payload.attachment_ids),
|
| 245 |
-
Attachment.workspace_id == current_user.workspace_id,
|
| 246 |
-
Attachment.ticket_id.is_(None) # Safety check
|
| 247 |
-
)
|
| 248 |
-
.values(ticket_id=new_ticket.id)
|
| 249 |
-
)
|
| 250 |
-
upt_res = await db.execute(att_stmt)
|
| 251 |
-
logger.info(f"Attachment linking complete for {new_ticket.id}. Rows updated: {upt_res.rowcount}")
|
| 252 |
-
else:
|
| 253 |
-
logger.info(f"No attachment_ids provided for ticket {new_ticket.id}")
|
| 254 |
-
|
| 255 |
-
audit = AuditLog(
|
| 256 |
-
workspace_id=current_user.workspace_id,
|
| 257 |
-
entity_type="ticket",
|
| 258 |
-
entity_id=new_ticket.id,
|
| 259 |
-
action="create",
|
| 260 |
-
user_id=current_user.id,
|
| 261 |
-
new_value=payload.model_dump(mode='json')
|
| 262 |
-
)
|
| 263 |
-
db.add(audit)
|
| 264 |
-
await db.commit()
|
| 265 |
-
|
| 266 |
-
# Refresh to ensure ID is persistent, then fetch with relationships for response sanitization
|
| 267 |
-
refetch_stmt = (
|
| 268 |
-
select(Ticket)
|
| 269 |
-
.options(
|
| 270 |
-
joinedload(Ticket.creator),
|
| 271 |
-
joinedload(Ticket.assignee),
|
| 272 |
-
joinedload(Ticket.resolver),
|
| 273 |
-
joinedload(Ticket.feedback)
|
| 274 |
-
)
|
| 275 |
-
.where(Ticket.id == new_ticket.id)
|
| 276 |
-
)
|
| 277 |
-
new_ticket = (await db.execute(refetch_stmt)).scalar_one()
|
| 278 |
-
|
| 279 |
-
# --- Observability: Record Ticket Inception (GAP-4 Fix: async) ---
|
| 280 |
-
from core.tasks import enqueue_task
|
| 281 |
-
await enqueue_task(
|
| 282 |
-
arq_pool,
|
| 283 |
-
"record_workflow_step_task",
|
| 284 |
-
str(new_ticket.id),
|
| 285 |
-
str(new_ticket.workspace_id),
|
| 286 |
-
"LIFECYCLE",
|
| 287 |
-
"TICKET_INCEPTION",
|
| 288 |
-
input_data={"title": new_ticket.title},
|
| 289 |
-
output_data={"status": "registered"},
|
| 290 |
-
current_stage="INITIAL_INGESTION"
|
| 291 |
-
)
|
| 292 |
-
|
| 293 |
-
# 1. Update Invalidation Cache (Clear lists)
|
| 294 |
-
from core.cache import delete_by_pattern
|
| 295 |
-
await delete_by_pattern(f"tickets:list:{current_user.workspace_id}*")
|
| 296 |
-
|
| 297 |
-
# 1.5. Invalidate Dashboard Reports (Volume, Daily, SLA)
|
| 298 |
-
await delete_by_pattern(f"reports:*:{current_user.workspace_id}*")
|
| 299 |
-
|
| 300 |
-
# 1.6. Invalidate Semantic Cache (Factual shift)
|
| 301 |
-
from core.cache import invalidate_workspace_semantic_cache
|
| 302 |
-
await invalidate_workspace_semantic_cache(str(current_user.workspace_id))
|
| 303 |
-
|
| 304 |
-
ticket_data = {
|
| 305 |
-
"id": str(new_ticket.id),
|
| 306 |
-
"workspace_id": str(new_ticket.workspace_id),
|
| 307 |
-
"title": new_ticket.title,
|
| 308 |
-
"description": new_ticket.description,
|
| 309 |
-
"priority": str(new_ticket.priority.value) if new_ticket.priority else None,
|
| 310 |
-
"category": new_ticket.category
|
| 311 |
-
}
|
| 312 |
-
# 2. Trigger Unified AI Workflow (GAP-9 & GAP-7 Cleanup)
|
| 313 |
-
# Summarizer is now CHAINED inside run_ai_workflow
|
| 314 |
-
from core.tasks import enqueue_task
|
| 315 |
-
await enqueue_task(
|
| 316 |
-
arq_pool,
|
| 317 |
-
'run_ai_workflow',
|
| 318 |
-
new_ticket.id,
|
| 319 |
-
new_ticket.workspace_id, # Simplified payload
|
| 320 |
-
_job_id=f"ai_workflow_{new_ticket.id}",
|
| 321 |
-
_job_timeout=1200
|
| 322 |
-
)
|
| 323 |
-
|
| 324 |
-
# 3. Consolidated Notification (GAP-1 Fix)
|
| 325 |
-
# We always use the Arq job to avoid double-firing or race conditions.
|
| 326 |
-
# The Arq worker will handle the logic of who to notify.
|
| 327 |
-
from core.tasks import enqueue_task
|
| 328 |
-
await enqueue_task(
|
| 329 |
-
arq_pool,
|
| 330 |
-
"send_triple_notification",
|
| 331 |
-
str(new_ticket.assigned_to or new_ticket.created_by),
|
| 332 |
-
str(new_ticket.workspace_id),
|
| 333 |
-
"🎟️ Ticket Updated",
|
| 334 |
-
f"Ticket '{new_ticket.title}' is being processed.",
|
| 335 |
-
link=f"/dashboard?ticket={new_ticket.id}"
|
| 336 |
-
)
|
| 337 |
-
|
| 338 |
-
await manager.broadcast_to_workspace(
|
| 339 |
-
current_user.workspace_id,
|
| 340 |
-
{"event": "ticket_created", "ticket_id": str(new_ticket.id), "title": new_ticket.title}
|
| 341 |
-
)
|
| 342 |
-
|
| 343 |
-
# Duplicate Arq notify removed (Consolidated above)
|
| 344 |
-
|
| 345 |
-
logger.info(f"Ticket created: {new_ticket.id} by user {current_user.id} in workspace {current_user.workspace_id}")
|
| 346 |
-
|
| 347 |
-
return await sanitize_ticket_response(new_ticket, current_user, db)
|
| 348 |
-
|
| 349 |
-
@router.get("/search/", response_model=TicketSearchResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + ALL_CUSTOMER_ROLES))])
|
| 350 |
-
async def search_tickets(
|
| 351 |
-
q: str,
|
| 352 |
-
project_id: Optional[UUID] = None,
|
| 353 |
-
current_user: User = Depends(get_current_user),
|
| 354 |
-
db: AsyncSession = Depends(get_db)
|
| 355 |
-
) -> Any:
|
| 356 |
-
"""Advanced Hybrid Search for Tickets (0.2 Threshold). Partitioned by role."""
|
| 357 |
-
import uuid
|
| 358 |
-
from core.observability import record_workflow_step
|
| 359 |
-
search_id = uuid.uuid4()
|
| 360 |
-
start_time = time.perf_counter()
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
# 0. Local Search Cache Lookup (Dual-Redis Architecture)
|
| 364 |
-
cache_filters = {"project_id": str(project_id) if project_id else None, "role": current_user.role}
|
| 365 |
-
cache_key = generate_cache_key("tickets", str(current_user.workspace_id), q, cache_filters)
|
| 366 |
-
cached_res = await get_cached_search(cache_key)
|
| 367 |
-
if cached_res:
|
| 368 |
-
logger.info(f"⚡ Search Cache HIT [Tickets]: {q}")
|
| 369 |
-
return cached_res
|
| 370 |
-
|
| 371 |
-
# 1. Semantic Search (Text)
|
| 372 |
-
embed_start = time.perf_counter()
|
| 373 |
-
text_model = get_text_embeddings()
|
| 374 |
-
query_vector = await text_model.aembed_query(q)
|
| 375 |
-
await record_workflow_step(
|
| 376 |
-
db, search_id, current_user.workspace_id, "SEARCH",
|
| 377 |
-
"QUERY_EMBEDDING",
|
| 378 |
-
input_data={"q": q},
|
| 379 |
-
duration_ms=(time.perf_counter() - embed_start) * 1000
|
| 380 |
-
)
|
| 381 |
-
|
| 382 |
-
# 1. Semantic Search (Dense Vector) - Branch A
|
| 383 |
-
semantic_stmt = (
|
| 384 |
-
select(
|
| 385 |
-
Ticket,
|
| 386 |
-
(1 - Ticket.embedding.cosine_distance(query_vector)).label("sim_score")
|
| 387 |
-
)
|
| 388 |
-
.options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback))
|
| 389 |
-
.where(
|
| 390 |
-
Ticket.deleted_at.is_(None),
|
| 391 |
-
Ticket.embedding.isnot(None)
|
| 392 |
-
)
|
| 393 |
-
)
|
| 394 |
-
|
| 395 |
-
# Global Access for Platform Super Admin only
|
| 396 |
-
if not current_user.is_platform_admin:
|
| 397 |
-
semantic_stmt = semantic_stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 398 |
-
|
| 399 |
-
if project_id:
|
| 400 |
-
semantic_stmt = semantic_stmt.where(Ticket.project_id == project_id)
|
| 401 |
-
semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20)
|
| 402 |
-
|
| 403 |
-
# 2. Visual Search (Attachments) - Branch B
|
| 404 |
-
# Uses pre-computed search_vector for sub-second lookup
|
| 405 |
-
visual_stmt = (
|
| 406 |
-
select(
|
| 407 |
-
Ticket,
|
| 408 |
-
func.ts_rank(
|
| 409 |
-
Attachment.search_vector,
|
| 410 |
-
func.plainto_tsquery('english', q)
|
| 411 |
-
).label("vis_score")
|
| 412 |
-
)
|
| 413 |
-
.options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback))
|
| 414 |
-
.join(Attachment, Ticket.id == Attachment.ticket_id)
|
| 415 |
-
.where(
|
| 416 |
-
Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q))
|
| 417 |
-
)
|
| 418 |
-
)
|
| 419 |
-
|
| 420 |
-
# Global Access for Platform Super Admin only
|
| 421 |
-
if not current_user.is_platform_admin:
|
| 422 |
-
visual_stmt = visual_stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 423 |
-
|
| 424 |
-
if project_id:
|
| 425 |
-
visual_stmt = visual_stmt.where(Ticket.project_id == project_id)
|
| 426 |
-
visual_stmt = visual_stmt.limit(10)
|
| 427 |
-
|
| 428 |
-
from api.v1.kb import execute_multimodal_search
|
| 429 |
-
|
| 430 |
-
# 3. Keyword Search (FTS on Title/Description) - Branch C
|
| 431 |
-
# Uses pre-computed Ticket.search_vector
|
| 432 |
-
keyword_stmt = (
|
| 433 |
-
select(
|
| 434 |
-
Ticket,
|
| 435 |
-
func.ts_rank(
|
| 436 |
-
Ticket.search_vector,
|
| 437 |
-
func.plainto_tsquery('english', q)
|
| 438 |
-
).label("kw_score")
|
| 439 |
-
)
|
| 440 |
-
.options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.feedback))
|
| 441 |
-
.where(
|
| 442 |
-
Ticket.search_vector.op("@@")(func.plainto_tsquery('english', q))
|
| 443 |
-
)
|
| 444 |
-
)
|
| 445 |
-
if not current_user.is_platform_admin:
|
| 446 |
-
keyword_stmt = keyword_stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 447 |
-
if current_user.role == UserRole.CUSTOMER_USER:
|
| 448 |
-
|
| 449 |
-
# Regular customers see ONLY their own tickets
|
| 450 |
-
keyword_stmt = keyword_stmt.where(Ticket.created_by == current_user.id)
|
| 451 |
-
if project_id:
|
| 452 |
-
keyword_stmt = keyword_stmt.where(Ticket.project_id == project_id)
|
| 453 |
-
keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(20)
|
| 454 |
-
|
| 455 |
-
# --- Parallel Execution (ISOLATED SESSIONS) ---
|
| 456 |
-
# We use independent sessions to safely enable asyncio.gather with asyncpg
|
| 457 |
-
async def run_query(stmt):
|
| 458 |
-
async with async_session_factory() as session:
|
| 459 |
-
res = await session.execute(stmt)
|
| 460 |
-
return res.all()
|
| 461 |
-
|
| 462 |
-
# Launch 4-Branch Retrieval (3 Ticket branches + 1 KB branch)
|
| 463 |
-
sem_task = run_query(semantic_stmt)
|
| 464 |
-
vis_task = run_query(visual_stmt)
|
| 465 |
-
kw_task = run_query(keyword_stmt)
|
| 466 |
-
|
| 467 |
-
# KB search integrated into the parallel flow
|
| 468 |
-
async def run_kb_search():
|
| 469 |
-
async with async_session_factory() as session:
|
| 470 |
-
return await execute_multimodal_search(
|
| 471 |
-
session, q, current_user, None, project_id, current_user.workspace_id
|
| 472 |
-
)
|
| 473 |
-
|
| 474 |
-
kb_task = run_kb_search()
|
| 475 |
-
|
| 476 |
-
hits, v_hits, kw_hits, kb_results_map = await asyncio.gather(sem_task, vis_task, kw_task, kb_task)
|
| 477 |
-
|
| 478 |
-
await record_workflow_step(
|
| 479 |
-
db, search_id, current_user.workspace_id, "SEARCH",
|
| 480 |
-
"RETRIEVAL_COMPLETE",
|
| 481 |
-
output_data={"semantic_hits": len(hits), "visual_hits": len(v_hits), "keyword_hits": len(kw_hits), "kb_hits": len(kb_results_map)},
|
| 482 |
-
duration_ms=(time.perf_counter() - start_time) * 1000
|
| 483 |
-
)
|
| 484 |
-
|
| 485 |
-
# 4. Hybrid Fusion (Weighted Reciprocal Rank Fusion)
|
| 486 |
-
fusion_start = time.perf_counter()
|
| 487 |
-
ticket_scores = {}
|
| 488 |
-
|
| 489 |
-
def apply_fusion(list_hits, weight, score_attr):
|
| 490 |
-
for rank, row in enumerate(list_hits):
|
| 491 |
-
ticket = row[0]
|
| 492 |
-
float(getattr(row, score_attr) or 0.0)
|
| 493 |
-
# Reciprocal Rank Fusion (RRF) with sharper k=10 for better top-k discrimination
|
| 494 |
-
rrf_score = weight * (1.0 / (10 + rank + 1))
|
| 495 |
-
|
| 496 |
-
# Boost exact title matches (intuitive relevance)
|
| 497 |
-
if q.lower() in ticket.title.lower():
|
| 498 |
-
rrf_score *= 2.0
|
| 499 |
-
|
| 500 |
-
if ticket.id not in ticket_scores:
|
| 501 |
-
ticket_scores[ticket.id] = {"obj": ticket, "score": rrf_score, "types": {score_attr}}
|
| 502 |
-
else:
|
| 503 |
-
ticket_scores[ticket.id]["score"] += rrf_score
|
| 504 |
-
ticket_scores[ticket.id]["types"].add(score_attr)
|
| 505 |
-
|
| 506 |
-
apply_fusion(hits, 0.4, "sim_score") # Semantic (balanced with keyword)
|
| 507 |
-
apply_fusion(kw_hits, 0.4, "kw_score") # Keyword (elevated)
|
| 508 |
-
apply_fusion(v_hits, 0.2, "vis_score") # Visual
|
| 509 |
-
|
| 510 |
-
# 5. Final Thresholding & Sorting
|
| 511 |
-
THRESHOLD = 0.001 # RRF scores are smaller by design (1/60 basis)
|
| 512 |
-
final_results = []
|
| 513 |
-
for t_id, data in ticket_scores.items():
|
| 514 |
-
score = float(data.get("score") or 0.0)
|
| 515 |
-
if score >= THRESHOLD:
|
| 516 |
-
t_obj = data["obj"]
|
| 517 |
-
# Map RRF types to a human readable match string
|
| 518 |
-
match_types = []
|
| 519 |
-
if "sim_score" in data["types"]:
|
| 520 |
-
match_types.append("semantic")
|
| 521 |
-
if "kw_score" in data["types"]:
|
| 522 |
-
match_types.append("keyword")
|
| 523 |
-
if "vis_score" in data["types"]:
|
| 524 |
-
match_types.append("visual")
|
| 525 |
-
|
| 526 |
-
# Normalize RRF to 100% (Theoretical max with boost = 1.0 / 11 * 2 = 0.1818)
|
| 527 |
-
# We use a base divisor of 0.0909 (rank 1 match across all branches)
|
| 528 |
-
norm_score = min(((score / 0.0909) * 100), 100.0)
|
| 529 |
-
|
| 530 |
-
result_item = TicketSearchResult(
|
| 531 |
-
id=t_obj.id,
|
| 532 |
-
title=t_obj.title,
|
| 533 |
-
description=t_obj.description,
|
| 534 |
-
status=t_obj.status,
|
| 535 |
-
priority=t_obj.priority,
|
| 536 |
-
project_id=t_obj.project_id,
|
| 537 |
-
creator_name=t_obj.creator.full_name if t_obj.creator else "System",
|
| 538 |
-
assigned_name=t_obj.assignee.full_name if t_obj.assignee else None,
|
| 539 |
-
is_escalated=t_obj.is_escalated,
|
| 540 |
-
score=round(norm_score, 1), # Display as e.g. 98.5
|
| 541 |
-
created_at=t_obj.created_at,
|
| 542 |
-
is_mine=t_obj.created_by == current_user.id
|
| 543 |
-
)
|
| 544 |
-
final_results.append(result_item)
|
| 545 |
-
|
| 546 |
-
final_results.sort(key=lambda x: x.score, reverse=True)
|
| 547 |
-
|
| 548 |
-
await record_workflow_step(
|
| 549 |
-
db, search_id, current_user.workspace_id, "SEARCH",
|
| 550 |
-
"HYBRID_FUSION_COMPLETE",
|
| 551 |
-
output_data={"final_result_count": len(final_results)},
|
| 552 |
-
duration_ms=(time.perf_counter() - fusion_start) * 1000,
|
| 553 |
-
current_stage="RESULTS_DELIVERED"
|
| 554 |
-
)
|
| 555 |
-
|
| 556 |
-
# 6. Format Related Articles (Normalized to 100%)
|
| 557 |
-
related_articles = []
|
| 558 |
-
for art_id, data in kb_results_map.items():
|
| 559 |
-
art_obj = data["obj"]
|
| 560 |
-
raw_kb_score = float(data.get("score", 0.0))
|
| 561 |
-
norm_kb_score = min(((raw_kb_score / 0.01639344) * 100), 100.0)
|
| 562 |
-
|
| 563 |
-
related_articles.append({
|
| 564 |
-
"id": str(art_obj.id),
|
| 565 |
-
"title": art_obj.title,
|
| 566 |
-
"category": art_obj.category,
|
| 567 |
-
"score": round(norm_kb_score, 1) # Display as e.g. 94.2
|
| 568 |
-
})
|
| 569 |
-
|
| 570 |
-
await db.commit() # Commit lifecycle for search trace
|
| 571 |
-
|
| 572 |
-
end_time = time.perf_counter()
|
| 573 |
-
res_data = {
|
| 574 |
-
"results": final_results[:5],
|
| 575 |
-
"related_articles": related_articles,
|
| 576 |
-
"search_time_s": round(end_time - start_time, 3),
|
| 577 |
-
"search_trace_id": str(search_id)
|
| 578 |
-
}
|
| 579 |
-
|
| 580 |
-
# Save to Local Search Cache before returning (1 hour TTL)
|
| 581 |
-
await set_cached_search(cache_key, res_data)
|
| 582 |
-
|
| 583 |
-
return jsonable_encoder(res_data)
|
| 584 |
-
|
| 585 |
-
@router.get("/categories/", response_model=List[str], dependencies=[Depends(require_roles(ALL_SC_ROLES + ALL_CUSTOMER_ROLES))])
|
| 586 |
-
async def list_ticket_categories(
|
| 587 |
-
current_user: User = Depends(get_current_user),
|
| 588 |
-
db: AsyncSession = Depends(get_db)
|
| 589 |
-
) -> Any:
|
| 590 |
-
"""Retrieve all unique ticket categories for this workspace."""
|
| 591 |
-
stmt = select(func.distinct(Ticket.category)).where(
|
| 592 |
-
Ticket.deleted_at.is_(None)
|
| 593 |
-
)
|
| 594 |
-
if not current_user.is_platform_admin:
|
| 595 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 596 |
-
|
| 597 |
-
result = await db.execute(stmt)
|
| 598 |
-
categories = [c for c in result.scalars().all()]
|
| 599 |
-
# Normalize nulls to "N/A"
|
| 600 |
-
normalized = sorted([c if c else "N/A" for c in categories])
|
| 601 |
-
return normalized
|
| 602 |
-
|
| 603 |
-
@router.get("/statuses/", response_model=List[str], dependencies=[Depends(require_roles(ALL_SC_ROLES + ALL_CUSTOMER_ROLES))])
|
| 604 |
-
async def list_ticket_statuses() -> Any:
|
| 605 |
-
"""Retrieve all valid ticket statuses from the core enum."""
|
| 606 |
-
return [s.value for s in TicketStatus]
|
| 607 |
|
| 608 |
@router.get("/", response_model=List[Union[TicketInternalResponse, TicketResponse]])
|
| 609 |
async def list_tickets(
|
| 610 |
skip: int = 0, limit: int = 100,
|
| 611 |
status_filter: Optional[TicketStatus] = None,
|
| 612 |
-
category_filter: Optional[str] = None,
|
| 613 |
-
priority_filter: Optional[TicketPriority] = None,
|
| 614 |
-
project_id: Optional[UUID] = None,
|
| 615 |
-
ticket_id_filter: Optional[str] = None,
|
| 616 |
-
is_my_tickets: bool = False,
|
| 617 |
current_user: User = Depends(get_current_user),
|
| 618 |
db: AsyncSession = Depends(get_db)
|
| 619 |
) -> Any:
|
| 620 |
-
"""List tickets for the current workspace
|
| 621 |
-
stmt = (
|
| 622 |
-
select(Ticket)
|
| 623 |
-
.options(
|
| 624 |
-
joinedload(Ticket.creator),
|
| 625 |
-
joinedload(Ticket.assignee),
|
| 626 |
-
joinedload(Ticket.resolver),
|
| 627 |
-
joinedload(Ticket.feedback)
|
| 628 |
-
)
|
| 629 |
-
.where(Ticket.deleted_at.is_(None))
|
| 630 |
-
)
|
| 631 |
-
# Global Access for Platform Super Admin
|
| 632 |
if not current_user.is_platform_admin:
|
| 633 |
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 634 |
-
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 635 |
-
if not is_staff:
|
| 636 |
-
# Deep Role Verification: Join UserWorkspace AND User to check roles
|
| 637 |
-
stmt = stmt.join(User, Ticket.created_by == User.id)\
|
| 638 |
-
.join(UserWorkspace, and_(
|
| 639 |
-
UserWorkspace.user_id == Ticket.created_by,
|
| 640 |
-
UserWorkspace.workspace_id == Ticket.workspace_id
|
| 641 |
-
)).where(
|
| 642 |
-
or_(
|
| 643 |
-
cast(UserWorkspace.role, String).ilike('customer%'),
|
| 644 |
-
User._legacy_role.ilike('customer%') # Fallback
|
| 645 |
-
)
|
| 646 |
-
)
|
| 647 |
-
if status_filter:
|
| 648 |
-
stmt = stmt.where(Ticket.status == status_filter)
|
| 649 |
-
if priority_filter:
|
| 650 |
-
stmt = stmt.where(Ticket.priority == priority_filter)
|
| 651 |
-
if project_id:
|
| 652 |
-
stmt = stmt.where(Ticket.project_id == project_id)
|
| 653 |
|
| 654 |
-
if ticket_id_filter:
|
| 655 |
-
# Search by partial ID prefix (CAST to string for ILIKE)
|
| 656 |
-
stmt = stmt.where(cast(Ticket.id, String).ilike(f"{ticket_id_filter}%"))
|
| 657 |
-
if category_filter:
|
| 658 |
-
if category_filter == "N/A":
|
| 659 |
-
stmt = stmt.where(Ticket.category.is_(None))
|
| 660 |
-
else:
|
| 661 |
-
stmt = stmt.where(Ticket.category == category_filter)
|
| 662 |
-
|
| 663 |
-
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 664 |
-
# No creator restriction: Customers can see all tickets in their workspace.
|
| 665 |
-
|
| 666 |
-
if is_my_tickets and is_staff:
|
| 667 |
-
# Staff can filter to see only their own created tickets if requested
|
| 668 |
-
stmt = stmt.where(Ticket.created_by == current_user.id)
|
| 669 |
-
|
| 670 |
-
stmt = stmt.offset(skip).limit(limit).order_by(Ticket.created_at.desc())
|
| 671 |
-
result = await db.execute(stmt)
|
| 672 |
-
tickets = result.scalars().unique().all()
|
| 673 |
-
|
| 674 |
-
# --- N+1 Optimization: Batch Context retrieval ---
|
| 675 |
-
lead_name = None
|
| 676 |
-
if is_staff and any(t.is_escalated for t in tickets):
|
| 677 |
-
# Just grab One Lead for simplicity in the list view (common in this app's UI)
|
| 678 |
-
lead_stmt = select(User.full_name).join(UserWorkspace).where(
|
| 679 |
-
UserWorkspace.workspace_id == current_user.workspace_id,
|
| 680 |
-
UserWorkspace.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]),
|
| 681 |
-
User.is_active.is_(True)
|
| 682 |
-
).limit(1)
|
| 683 |
-
lead_res = await db.execute(lead_stmt)
|
| 684 |
-
lead_name = lead_res.scalar_one_or_none()
|
| 685 |
-
|
| 686 |
-
dup_map = {}
|
| 687 |
-
dup_ids = [t.duplicate_of_id for t in tickets if t.duplicate_of_id]
|
| 688 |
-
if dup_ids:
|
| 689 |
-
dup_stmt = select(Ticket.id, Ticket.title).where(Ticket.id.in_(dup_ids))
|
| 690 |
-
dup_res = await db.execute(dup_stmt)
|
| 691 |
-
dup_map = {row[0]: row[1] for row in dup_res.all()}
|
| 692 |
-
|
| 693 |
-
return [
|
| 694 |
-
await sanitize_ticket_response(
|
| 695 |
-
t, current_user, db,
|
| 696 |
-
lead_name=lead_name if t.is_escalated else None,
|
| 697 |
-
dup_title=dup_map.get(t.duplicate_of_id)
|
| 698 |
-
)
|
| 699 |
-
for t in tickets
|
| 700 |
-
]
|
| 701 |
-
|
| 702 |
-
@router.get("/paginated/", response_model=Union[PaginatedInternalResponse, PaginatedTicketResponse])
|
| 703 |
-
async def list_tickets_paginated(
|
| 704 |
-
skip: int = 0, limit: int = 10,
|
| 705 |
-
status_filter: Optional[TicketStatus] = None,
|
| 706 |
-
category_filter: Optional[str] = None,
|
| 707 |
-
priority_filter: Optional[TicketPriority] = None,
|
| 708 |
-
project_id: Optional[UUID] = None,
|
| 709 |
-
search_query: Optional[str] = None,
|
| 710 |
-
creator_query: Optional[str] = None,
|
| 711 |
-
ticket_id_filter: Optional[str] = None,
|
| 712 |
-
is_my_tickets: bool = False,
|
| 713 |
-
current_user: User = Depends(get_current_user),
|
| 714 |
-
db: AsyncSession = Depends(get_db)
|
| 715 |
-
) -> Any:
|
| 716 |
-
"""Paginated list of tickets with portal-aware 'My Tickets' logic and Redis caching."""
|
| 717 |
-
from core.cache import get_cached_object, set_cached_object
|
| 718 |
-
|
| 719 |
-
# 0. Cache lookup (Shared per workspace/filters)
|
| 720 |
-
cache_key = f"tickets:list:{current_user.workspace_id}:{skip}:{limit}:{status_filter}:{category_filter}:{priority_filter}:{project_id}:{is_my_tickets}:{search_query}:{creator_query}:{ticket_id_filter}:{current_user.id if is_my_tickets else 'all'}"
|
| 721 |
-
if not current_user.is_platform_admin: # Only cache workspace-level results
|
| 722 |
-
cached_res = await get_cached_object(cache_key)
|
| 723 |
-
if cached_res:
|
| 724 |
-
logger.info(f"⚡ Cache HIT [Ticket List]: {current_user.workspace_id}")
|
| 725 |
-
return cached_res
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 729 |
-
|
| 730 |
-
# 1. Base Query
|
| 731 |
-
base_stmt = select(Ticket).where(Ticket.deleted_at.is_(None))
|
| 732 |
-
|
| 733 |
-
# 2. Workspace Scoping
|
| 734 |
-
if not current_user.is_platform_admin:
|
| 735 |
-
base_stmt = base_stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 736 |
-
if not is_staff:
|
| 737 |
-
# Deep Role Verification: Ensure creator has a customer role in the ticket's workspace
|
| 738 |
-
base_stmt = base_stmt.join(User, Ticket.created_by == User.id)\
|
| 739 |
-
.join(UserWorkspace, and_(
|
| 740 |
-
UserWorkspace.user_id == Ticket.created_by,
|
| 741 |
-
UserWorkspace.workspace_id == Ticket.workspace_id
|
| 742 |
-
)).where(
|
| 743 |
-
or_(
|
| 744 |
-
cast(UserWorkspace.role, String).ilike('customer%'),
|
| 745 |
-
User._legacy_role.ilike('customer%') # Fallback
|
| 746 |
-
)
|
| 747 |
-
)
|
| 748 |
-
else:
|
| 749 |
-
# If platform admin, we still need the creator join for the filter below
|
| 750 |
-
base_stmt = base_stmt.join(User, Ticket.created_by == User.id)
|
| 751 |
-
|
| 752 |
-
# Ensure creator is joined if we need to filter by name
|
| 753 |
-
if creator_query and is_staff:
|
| 754 |
-
# Double join protection if already joined above
|
| 755 |
-
if User not in [j.entity for j in base_stmt.get_final_froms() if hasattr(j, 'entity')]:
|
| 756 |
-
base_stmt = base_stmt.join(User, Ticket.created_by == User.id)
|
| 757 |
-
|
| 758 |
-
# 3. Filters
|
| 759 |
if status_filter:
|
| 760 |
-
|
| 761 |
-
if priority_filter:
|
| 762 |
-
base_stmt = base_stmt.where(Ticket.priority == priority_filter)
|
| 763 |
-
if project_id:
|
| 764 |
-
base_stmt = base_stmt.where(Ticket.project_id == project_id)
|
| 765 |
-
if search_query:
|
| 766 |
-
# GAP-5 Fix: Use Full-Text Search index
|
| 767 |
-
base_stmt = base_stmt.where(Ticket.search_vector.op("@@")(func.plainto_tsquery('english', search_query)))
|
| 768 |
-
if creator_query:
|
| 769 |
-
base_stmt = base_stmt.where(User.full_name.ilike(f"%{creator_query}%"))
|
| 770 |
-
if ticket_id_filter:
|
| 771 |
-
base_stmt = base_stmt.where(cast(Ticket.id, String).ilike(f"{ticket_id_filter}%"))
|
| 772 |
-
if category_filter:
|
| 773 |
-
if category_filter == "N/A":
|
| 774 |
-
base_stmt = base_stmt.where(Ticket.category.is_(None))
|
| 775 |
-
else:
|
| 776 |
-
base_stmt = base_stmt.where(Ticket.category == category_filter)
|
| 777 |
-
|
| 778 |
-
# 4. Portal-Aware 'My Tickets' Logic
|
| 779 |
-
if is_my_tickets:
|
| 780 |
-
if is_staff:
|
| 781 |
-
# Internal Portal: Tickets assigned directly to the staff member
|
| 782 |
-
base_stmt = base_stmt.where(Ticket.assigned_to == current_user.id)
|
| 783 |
-
else:
|
| 784 |
-
# Customer Portal: Tickets created by the customer user
|
| 785 |
-
base_stmt = base_stmt.where(Ticket.created_by == current_user.id)
|
| 786 |
-
|
| 787 |
-
# 5. Execute Count (Parallel ideally, but sequential for standard ACID patterns)
|
| 788 |
-
count_stmt = select(func.count()).select_from(base_stmt.alias("subquery"))
|
| 789 |
-
total_count = (await db.execute(count_stmt)).scalar() or 0
|
| 790 |
|
| 791 |
-
|
| 792 |
-
data_stmt = (
|
| 793 |
-
base_stmt
|
| 794 |
-
.options(
|
| 795 |
-
joinedload(Ticket.creator),
|
| 796 |
-
joinedload(Ticket.assignee),
|
| 797 |
-
joinedload(Ticket.resolver),
|
| 798 |
-
joinedload(Ticket.feedback)
|
| 799 |
-
)
|
| 800 |
-
.order_by(Ticket.created_at.desc())
|
| 801 |
-
.offset(skip)
|
| 802 |
-
.limit(limit)
|
| 803 |
-
)
|
| 804 |
-
result = await db.execute(data_stmt)
|
| 805 |
tickets = result.scalars().unique().all()
|
| 806 |
-
|
| 807 |
-
# --- Context Injection (Batch optimization logic reused from list_tickets) ---
|
| 808 |
-
lead_name = None
|
| 809 |
-
if is_staff and any(t.is_escalated for t in tickets):
|
| 810 |
-
lead_stmt = select(User.full_name).join(UserWorkspace).where(
|
| 811 |
-
UserWorkspace.workspace_id == current_user.workspace_id,
|
| 812 |
-
UserWorkspace.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]),
|
| 813 |
-
User.is_active.is_(True)
|
| 814 |
-
).limit(1)
|
| 815 |
-
lead_res = await db.execute(lead_stmt)
|
| 816 |
-
lead_name = lead_res.scalar_one_or_none()
|
| 817 |
|
| 818 |
-
|
| 819 |
-
dup_ids = [t.duplicate_of_id for t in tickets if t.duplicate_of_id]
|
| 820 |
-
if dup_ids:
|
| 821 |
-
dup_stmt = select(Ticket.id, Ticket.title).where(Ticket.id.in_(dup_ids))
|
| 822 |
-
dup_map = {row[0]: row[1] for row in (await db.execute(dup_stmt)).all()}
|
| 823 |
-
|
| 824 |
-
final_items = [
|
| 825 |
-
await sanitize_ticket_response(
|
| 826 |
-
t, current_user, db,
|
| 827 |
-
lead_name=lead_name if t.is_escalated else None,
|
| 828 |
-
dup_title=dup_map.get(t.duplicate_of_id)
|
| 829 |
-
)
|
| 830 |
-
for t in tickets
|
| 831 |
-
]
|
| 832 |
-
|
| 833 |
-
res_payload = {
|
| 834 |
-
"items": final_items,
|
| 835 |
-
"total": total_count,
|
| 836 |
-
"skip": skip,
|
| 837 |
-
"limit": limit
|
| 838 |
-
}
|
| 839 |
-
|
| 840 |
-
# 7. Store in Cache (5 minute TTL for list results)
|
| 841 |
-
if not current_user.is_platform_admin:
|
| 842 |
-
await set_cached_object(cache_key, res_payload, ttl=300)
|
| 843 |
-
|
| 844 |
-
return res_payload
|
| 845 |
|
| 846 |
@router.get("/{ticket_id}/", response_model=Union[TicketInternalResponse, TicketResponse])
|
| 847 |
async def get_ticket(
|
| 848 |
ticket_id: UUID,
|
| 849 |
-
bypass_cache: bool = False,
|
| 850 |
current_user: User = Depends(get_current_user),
|
| 851 |
db: AsyncSession = Depends(get_db)
|
| 852 |
) -> Any:
|
| 853 |
-
"""Get a specific ticket
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
# 0. Detail Cache Lookup
|
| 857 |
-
cache_key = f"ticket:detail:{ticket_id}"
|
| 858 |
-
if not bypass_cache:
|
| 859 |
-
cached_ticket = await get_cached_object(cache_key)
|
| 860 |
-
if cached_ticket:
|
| 861 |
-
# Security Check: Ensure cached ticket belongs to user's workspace
|
| 862 |
-
if cached_ticket.get("workspace_id") == str(current_user.workspace_id) or current_user.is_platform_admin:
|
| 863 |
-
logger.info(f"⚡ Cache HIT [Ticket Detail]: {ticket_id}")
|
| 864 |
-
return cached_ticket
|
| 865 |
-
else:
|
| 866 |
-
logger.info(f"♻️ Cache BYPASS [Ticket Detail]: {ticket_id}")
|
| 867 |
-
|
| 868 |
-
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 869 |
-
|
| 870 |
-
stmt = (
|
| 871 |
-
select(Ticket)
|
| 872 |
-
.options(
|
| 873 |
-
joinedload(Ticket.creator),
|
| 874 |
-
joinedload(Ticket.assignee),
|
| 875 |
-
joinedload(Ticket.resolver),
|
| 876 |
-
joinedload(Ticket.feedback)
|
| 877 |
-
)
|
| 878 |
-
.where(
|
| 879 |
-
Ticket.id == ticket_id,
|
| 880 |
-
Ticket.deleted_at.is_(None)
|
| 881 |
-
)
|
| 882 |
-
)
|
| 883 |
-
|
| 884 |
-
if is_staff:
|
| 885 |
-
# Staff check: Super Admin can see anything, others restricted to their workspace
|
| 886 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 887 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 888 |
-
else:
|
| 889 |
-
# Workspace-wide visibility enabled: Users restricted only by workspace
|
| 890 |
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 891 |
-
|
| 892 |
-
result = await db.execute(stmt)
|
| 893 |
-
ticket = result.unique().scalar_one_or_none()
|
| 894 |
-
if not ticket:
|
| 895 |
-
raise HTTPException(status_code=404, detail="Ticket not found or access denied")
|
| 896 |
-
|
| 897 |
-
res_data = await sanitize_ticket_response(ticket, current_user, db)
|
| 898 |
|
| 899 |
-
|
| 900 |
-
|
|
|
|
|
|
|
| 901 |
|
| 902 |
-
return
|
| 903 |
|
| 904 |
@router.patch("/{ticket_id}/", response_model=Union[TicketInternalResponse, TicketResponse])
|
| 905 |
async def update_ticket(
|
| 906 |
ticket_id: UUID,
|
| 907 |
payload: TicketUpdate,
|
| 908 |
-
background_tasks: BackgroundTasks,
|
| 909 |
current_user: User = Depends(get_current_user),
|
| 910 |
db: AsyncSession = Depends(get_db),
|
| 911 |
arq_pool: Any = Depends(get_arq_pool)
|
| 912 |
) -> Any:
|
| 913 |
-
"""Update a ticket.
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
stmt = (
|
| 917 |
-
select(Ticket)
|
| 918 |
-
.options(
|
| 919 |
-
joinedload(Ticket.creator),
|
| 920 |
-
joinedload(Ticket.assignee),
|
| 921 |
-
joinedload(Ticket.resolver),
|
| 922 |
-
joinedload(Ticket.feedback)
|
| 923 |
-
)
|
| 924 |
-
.where(
|
| 925 |
-
Ticket.id == ticket_id,
|
| 926 |
-
Ticket.deleted_at.is_(None)
|
| 927 |
-
)
|
| 928 |
-
)
|
| 929 |
-
|
| 930 |
-
if is_staff:
|
| 931 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 932 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 933 |
-
else:
|
| 934 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 935 |
-
stmt = stmt.where(Ticket.created_by == current_user.id)
|
| 936 |
-
|
| 937 |
-
result = await db.execute(stmt)
|
| 938 |
-
ticket = result.scalar_one_or_none()
|
| 939 |
-
|
| 940 |
-
if not ticket:
|
| 941 |
-
raise HTTPException(status_code=404, detail="Ticket not found or access denied")
|
| 942 |
-
|
| 943 |
-
update_data = payload.model_dump(exclude_unset=True)
|
| 944 |
-
|
| 945 |
-
if "assigned_to" in update_data and update_data["assigned_to"]:
|
| 946 |
-
assignee_id = update_data["assigned_to"]
|
| 947 |
-
if isinstance(assignee_id, str):
|
| 948 |
-
try:
|
| 949 |
-
assignee_id = UUID(assignee_id)
|
| 950 |
-
except ValueError:
|
| 951 |
-
raise HTTPException(status_code=400, detail="Invalid assignee ID format")
|
| 952 |
-
|
| 953 |
-
from models.user_workspace import UserWorkspace
|
| 954 |
-
# Enhanced validation: Check if user is in the workspace OR has a global staff role
|
| 955 |
-
try:
|
| 956 |
-
assignee_stmt = (
|
| 957 |
-
select(User)
|
| 958 |
-
.outerjoin(UserWorkspace, User.id == UserWorkspace.user_id)
|
| 959 |
-
.where(
|
| 960 |
-
User.id == assignee_id,
|
| 961 |
-
User.is_active,
|
| 962 |
-
User.deleted_at.is_(None),
|
| 963 |
-
or_(
|
| 964 |
-
and_(
|
| 965 |
-
UserWorkspace.workspace_id == current_user.workspace_id,
|
| 966 |
-
UserWorkspace.is_active.is_(True)
|
| 967 |
-
),
|
| 968 |
-
User._legacy_role.in_([UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]),
|
| 969 |
-
User.global_role.isnot(None)
|
| 970 |
-
)
|
| 971 |
-
)
|
| 972 |
-
)
|
| 973 |
-
assignee_res = await db.execute(assignee_stmt)
|
| 974 |
-
if not assignee_res.scalar_one_or_none():
|
| 975 |
-
logger.warning(f"Assignment Failed: User {assignee_id} not eligible for workspace {current_user.workspace_id}")
|
| 976 |
-
raise HTTPException(status_code=400, detail="Target assignee not found, is inactive, or lacks access to this workspace")
|
| 977 |
-
except Exception as e:
|
| 978 |
-
if isinstance(e, HTTPException):
|
| 979 |
-
raise
|
| 980 |
-
logger.error(f"Assignee Validation Crash: {str(e)}")
|
| 981 |
-
raise HTTPException(status_code=500, detail="Internal error during assignee validation")
|
| 982 |
-
|
| 983 |
-
if "status" in update_data:
|
| 984 |
-
new_status = update_data["status"]
|
| 985 |
-
if new_status != ticket.status:
|
| 986 |
-
if current_user.role not in [UserRole.SC_LEAD, UserRole.SC_ADMIN]:
|
| 987 |
-
allowed = ALLOWED_TRANSITIONS.get(ticket.status, [])
|
| 988 |
-
if new_status not in allowed:
|
| 989 |
-
raise HTTPException(status_code=400, detail=f"Invalid transition to {new_status}")
|
| 990 |
-
|
| 991 |
-
# Logic for Resolution Capture (Persistent Layer)
|
| 992 |
-
if new_status in [TicketStatus.RESOLVED, TicketStatus.CLOSED] and ticket.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
|
| 993 |
-
ticket.resolved_at = datetime.utcnow()
|
| 994 |
-
ticket.resolved_by = current_user.id
|
| 995 |
-
if not update_data.get("resolution_text"):
|
| 996 |
-
ticket.resolution_text = "This issue has been resolved. Thanks!"
|
| 997 |
-
|
| 998 |
-
# Notify Creator of Resolution
|
| 999 |
-
from core.tasks import enqueue_task
|
| 1000 |
-
await enqueue_task(
|
| 1001 |
-
arq_pool,
|
| 1002 |
-
"send_triple_notification",
|
| 1003 |
-
str(ticket.created_by),
|
| 1004 |
-
str(ticket.workspace_id),
|
| 1005 |
-
"✅ Ticket Resolved",
|
| 1006 |
-
f"Great news! Your ticket '{ticket.title}' has been marked as {new_status}."
|
| 1007 |
-
)
|
| 1008 |
-
|
| 1009 |
-
# --- NEW: Expertise Harvesting ---
|
| 1010 |
-
# Trigger autonomous skill extraction for the resolving agent
|
| 1011 |
-
from core.tasks import enqueue_task
|
| 1012 |
-
await enqueue_task(arq_pool, "harvest_expertise_task", ticket.id)
|
| 1013 |
-
elif new_status in [TicketStatus.IN_PROGRESS, TicketStatus.ACKNOWLEDGED] and ticket.status == TicketStatus.OPEN:
|
| 1014 |
-
# Notify Creator that work has started
|
| 1015 |
-
from core.tasks import enqueue_task
|
| 1016 |
-
await enqueue_task(
|
| 1017 |
-
arq_pool,
|
| 1018 |
-
"send_triple_notification",
|
| 1019 |
-
str(ticket.created_by),
|
| 1020 |
-
str(ticket.workspace_id),
|
| 1021 |
-
"🎟️ Work Started",
|
| 1022 |
-
f"An agent has started reviewing your ticket '{ticket.title}'. Current status: {new_status.value.upper()}."
|
| 1023 |
-
)
|
| 1024 |
-
|
| 1025 |
-
if "priority" in update_data and update_data["priority"] != ticket.priority:
|
| 1026 |
-
# Recalculate SLA
|
| 1027 |
-
rule_stmt = select(EscalationRule).where(
|
| 1028 |
-
EscalationRule.workspace_id == current_user.workspace_id,
|
| 1029 |
-
EscalationRule.priority_level == cast(update_data["priority"], String)
|
| 1030 |
-
)
|
| 1031 |
-
rule_res = await db.execute(rule_stmt)
|
| 1032 |
-
rule = rule_res.scalar_one_or_none()
|
| 1033 |
-
|
| 1034 |
-
if rule:
|
| 1035 |
-
# Use original created_at for SLA math
|
| 1036 |
-
ticket.sla_deadline = ticket.created_at + timedelta(minutes=rule.threshold_minutes)
|
| 1037 |
-
logger.info(f"Priority changed to {update_data['priority']}, SLA updated to {ticket.sla_deadline}")
|
| 1038 |
-
else:
|
| 1039 |
-
# Fallback to 48h from creation
|
| 1040 |
-
ticket.sla_deadline = ticket.created_at + timedelta(days=2)
|
| 1041 |
-
logger.info(f"Priority changed to {update_data['priority']}, no rule found, 48h default applied.")
|
| 1042 |
-
|
| 1043 |
-
old_values = {field: getattr(ticket, field) for field in update_data.keys()}
|
| 1044 |
-
old_assignee = ticket.assigned_to
|
| 1045 |
-
for field, value in update_data.items():
|
| 1046 |
-
setattr(ticket, field, value)
|
| 1047 |
-
|
| 1048 |
-
db.add(ticket)
|
| 1049 |
-
|
| 1050 |
-
# Notify if assignee changed
|
| 1051 |
-
if "assigned_to" in update_data and str(old_assignee) != str(update_data["assigned_to"]):
|
| 1052 |
-
# A) Notify Staff (Assignee)
|
| 1053 |
-
from core.tasks import enqueue_task
|
| 1054 |
-
await enqueue_task(
|
| 1055 |
-
arq_pool,
|
| 1056 |
-
"send_triple_notification",
|
| 1057 |
-
str(update_data["assigned_to"]),
|
| 1058 |
-
str(ticket.workspace_id),
|
| 1059 |
-
"Ticket Reassigned",
|
| 1060 |
-
f"Ticket '{ticket.title}' has been reassigned to you by {current_user.full_name or 'Admin'}.",
|
| 1061 |
-
link=f"/dashboard?ticket={ticket.id}"
|
| 1062 |
-
)
|
| 1063 |
-
# B) Notify Customer (Creator) if not self-assigning by customer
|
| 1064 |
-
if ticket.created_by != update_data["assigned_to"]:
|
| 1065 |
-
from core.tasks import enqueue_task
|
| 1066 |
-
await enqueue_task(
|
| 1067 |
-
arq_pool,
|
| 1068 |
-
"send_triple_notification",
|
| 1069 |
-
str(ticket.created_by),
|
| 1070 |
-
str(ticket.workspace_id),
|
| 1071 |
-
"👷 Expert Assigned",
|
| 1072 |
-
f"An expert has been assigned to your ticket '{ticket.title}' and is reviewing it now.",
|
| 1073 |
-
link=f"/dashboard?ticket={ticket.id}"
|
| 1074 |
-
)
|
| 1075 |
-
|
| 1076 |
-
# 2. Audit Trail Logging (Strict JSON Serialization)
|
| 1077 |
-
# Use mode='json' to ensure UUIDs are converted to strings properly
|
| 1078 |
-
new_values_json = payload.model_dump(exclude_unset=True, mode='json')
|
| 1079 |
-
|
| 1080 |
-
# Sanitize old values manually as they come directly from the model
|
| 1081 |
-
def sanitize_json(val):
|
| 1082 |
-
if isinstance(val, uuid.UUID):
|
| 1083 |
-
return str(val)
|
| 1084 |
-
if isinstance(val, datetime):
|
| 1085 |
-
return val.isoformat()
|
| 1086 |
-
if isinstance(val, dict):
|
| 1087 |
-
return {k: sanitize_json(v) for k, v in val.items()}
|
| 1088 |
-
if isinstance(val, list):
|
| 1089 |
-
return [sanitize_json(i) for i in val]
|
| 1090 |
-
return val
|
| 1091 |
-
|
| 1092 |
-
sanitized_old = {k: sanitize_json(v) for k, v in old_values.items()}
|
| 1093 |
-
|
| 1094 |
-
audit = AuditLog(
|
| 1095 |
-
workspace_id=current_user.workspace_id,
|
| 1096 |
-
entity_type="ticket",
|
| 1097 |
-
entity_id=ticket.id,
|
| 1098 |
-
action="update",
|
| 1099 |
-
user_id=current_user.id,
|
| 1100 |
-
old_value=sanitized_old,
|
| 1101 |
-
new_value=new_values_json
|
| 1102 |
-
)
|
| 1103 |
-
db.add(audit)
|
| 1104 |
-
|
| 1105 |
-
if "assigned_to" in update_data:
|
| 1106 |
-
logger.info(f"Ticket {ticket.id} assignment changed to {update_data['assigned_to']} by {current_user.id}")
|
| 1107 |
-
if "status" in update_data:
|
| 1108 |
-
logger.info(f"Ticket {ticket.id} status changed to {update_data['status']} by {current_user.id}")
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
await db.commit()
|
| 1112 |
-
await db.refresh(ticket)
|
| 1113 |
-
|
| 1114 |
-
# 3. Trigger re-processing if description or title changed
|
| 1115 |
-
if "description" in update_data or "title" in update_data:
|
| 1116 |
-
ticket_data = {
|
| 1117 |
-
"id": str(ticket.id),
|
| 1118 |
-
"workspace_id": str(ticket.workspace_id),
|
| 1119 |
-
"title": ticket.title,
|
| 1120 |
-
"description": ticket.description
|
| 1121 |
-
}
|
| 1122 |
-
# Trigger Unified AI Workflow (Atomic Job ID Handles Debouncing)
|
| 1123 |
-
from core.tasks import enqueue_task
|
| 1124 |
-
await enqueue_task(
|
| 1125 |
-
arq_pool,
|
| 1126 |
-
'run_ai_workflow',
|
| 1127 |
-
ticket.id,
|
| 1128 |
-
ticket_data,
|
| 1129 |
-
_job_id=f"ai_workflow_{ticket.id}",
|
| 1130 |
-
_job_timeout=900
|
| 1131 |
-
)
|
| 1132 |
-
logger.info(f"Ticket {ticket_id} content updated, atomic workflow enqueued.")
|
| 1133 |
-
|
| 1134 |
-
# 3. Trigger auto-summary if status moved to terminal or content changed
|
| 1135 |
-
if ("status" in update_data and update_data["status"] in [TicketStatus.RESOLVED, TicketStatus.CLOSED]) or \
|
| 1136 |
-
("description" in update_data or "title" in update_data):
|
| 1137 |
-
from core.tasks import enqueue_task
|
| 1138 |
-
await enqueue_task(arq_pool, "auto_summarize_ticket", ticket.id)
|
| 1139 |
-
|
| 1140 |
-
|
| 1141 |
-
# 4. Proactive Cache Invalidation (Detail, Lists, and Reports)
|
| 1142 |
-
from core.cache import invalidate_cache, delete_by_pattern
|
| 1143 |
-
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
| 1144 |
-
await delete_by_pattern(f"tickets:list:{current_user.workspace_id}*")
|
| 1145 |
-
await delete_by_pattern(f"reports:*:{current_user.workspace_id}*")
|
| 1146 |
-
|
| 1147 |
-
return await sanitize_ticket_response(ticket, current_user, db)
|
| 1148 |
-
|
| 1149 |
-
@router.delete("/{ticket_id}/", status_code=status.HTTP_200_OK)
|
| 1150 |
-
async def delete_ticket(
|
| 1151 |
-
ticket_id: UUID,
|
| 1152 |
-
current_user: User = Depends(get_current_user),
|
| 1153 |
-
db: AsyncSession = Depends(get_db)
|
| 1154 |
-
) -> Any:
|
| 1155 |
-
"""Soft Delete a ticket."""
|
| 1156 |
-
if current_user.role not in [UserRole.SC_ADMIN, UserRole.SC_LEAD]:
|
| 1157 |
-
raise HTTPException(status_code=403, detail="Permission denied")
|
| 1158 |
-
|
| 1159 |
-
stmt = (
|
| 1160 |
-
select(Ticket)
|
| 1161 |
-
.options(
|
| 1162 |
-
joinedload(Ticket.creator),
|
| 1163 |
-
joinedload(Ticket.assignee),
|
| 1164 |
-
joinedload(Ticket.resolver),
|
| 1165 |
-
joinedload(Ticket.feedback)
|
| 1166 |
-
)
|
| 1167 |
-
.where(
|
| 1168 |
-
Ticket.id == ticket_id,
|
| 1169 |
-
Ticket.deleted_at.is_(None)
|
| 1170 |
-
)
|
| 1171 |
-
)
|
| 1172 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 1173 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 1174 |
-
result = await db.execute(stmt)
|
| 1175 |
-
ticket = result.scalar_one_or_none()
|
| 1176 |
-
if not ticket:
|
| 1177 |
-
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 1178 |
-
|
| 1179 |
-
ticket.deleted_at = datetime.utcnow()
|
| 1180 |
-
ticket.deleted_by_id = current_user.id
|
| 1181 |
-
|
| 1182 |
-
# 1. Cascade to Messages
|
| 1183 |
-
msg_stmt = (
|
| 1184 |
-
update(Message)
|
| 1185 |
-
.where(Message.ticket_id == ticket_id)
|
| 1186 |
-
.values(
|
| 1187 |
-
deleted_at=ticket.deleted_at,
|
| 1188 |
-
deleted_by_id=current_user.id
|
| 1189 |
-
)
|
| 1190 |
-
)
|
| 1191 |
-
await db.execute(msg_stmt)
|
| 1192 |
-
|
| 1193 |
-
# 2. Cascade to Attachments
|
| 1194 |
-
att_stmt = (
|
| 1195 |
-
update(Attachment)
|
| 1196 |
-
.where(Attachment.ticket_id == ticket_id)
|
| 1197 |
-
.values(
|
| 1198 |
-
deleted_at=ticket.deleted_at,
|
| 1199 |
-
deleted_by_id=current_user.id
|
| 1200 |
-
)
|
| 1201 |
-
)
|
| 1202 |
-
await db.execute(att_stmt)
|
| 1203 |
-
|
| 1204 |
-
db.add(ticket)
|
| 1205 |
-
await db.commit()
|
| 1206 |
-
|
| 1207 |
-
# 3. Proactive Cache Invalidation
|
| 1208 |
-
from core.cache import invalidate_cache, delete_by_pattern
|
| 1209 |
-
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
| 1210 |
-
await delete_by_pattern(f"tickets:list:{current_user.workspace_id}*")
|
| 1211 |
-
await delete_by_pattern(f"reports:*:{current_user.workspace_id}*")
|
| 1212 |
-
|
| 1213 |
-
logger.info(f"Ticket soft-deleted: {ticket_id} by user {current_user.id}")
|
| 1214 |
-
return {"status": "deleted"}
|
| 1215 |
-
|
| 1216 |
-
@router.post("/{ticket_id}/reprocess/", status_code=status.HTTP_202_ACCEPTED)
|
| 1217 |
-
async def reprocess_ticket_ai(
|
| 1218 |
-
ticket_id: UUID,
|
| 1219 |
-
force_reroute: bool = False,
|
| 1220 |
-
current_user: User = Depends(get_current_user),
|
| 1221 |
-
db: AsyncSession = Depends(get_db),
|
| 1222 |
-
arq_pool: ArqRedis = Depends(get_arq_pool)
|
| 1223 |
-
) -> Any:
|
| 1224 |
-
"""
|
| 1225 |
-
Manually re-trigger the AI workflow for an existing ticket.
|
| 1226 |
-
"""
|
| 1227 |
-
if current_user.role not in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]:
|
| 1228 |
-
raise HTTPException(status_code=403, detail="Permission denied")
|
| 1229 |
-
|
| 1230 |
-
sync_stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 1231 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 1232 |
-
sync_stmt = sync_stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 1233 |
-
# Deep Ownership Check: Regular customers can only re-process their own tickets
|
| 1234 |
-
if current_user.role == UserRole.CUSTOMER_USER:
|
| 1235 |
-
sync_stmt = sync_stmt.where(Ticket.created_by == current_user.id)
|
| 1236 |
-
result = await db.execute(sync_stmt)
|
| 1237 |
-
ticket = result.scalar_one_or_none()
|
| 1238 |
-
if not ticket:
|
| 1239 |
-
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 1240 |
-
|
| 1241 |
-
from core.observability import record_workflow_step
|
| 1242 |
-
# 0. Record Reprocess Event in Trace
|
| 1243 |
-
await record_workflow_step(
|
| 1244 |
-
db, ticket.id, ticket.workspace_id, "LIFECYCLE",
|
| 1245 |
-
"REPROCESS_TRIGGERED",
|
| 1246 |
-
input_data={"requested_by": str(current_user.id)},
|
| 1247 |
-
current_stage="REPROCESSING"
|
| 1248 |
-
)
|
| 1249 |
-
|
| 1250 |
-
# 1. Prepare payload (Matches create_ticket format)
|
| 1251 |
-
ticket_data = {
|
| 1252 |
-
"id": str(ticket.id),
|
| 1253 |
-
"workspace_id": str(ticket.workspace_id),
|
| 1254 |
-
"title": ticket.title,
|
| 1255 |
-
"description": ticket.description
|
| 1256 |
-
}
|
| 1257 |
-
|
| 1258 |
-
# 2. Trigger Primary AI Workflow (Matches create_ticket pipeline)
|
| 1259 |
-
# Using atomic job_id to handle debouncing and prevent redundant execution
|
| 1260 |
-
from core.tasks import enqueue_task
|
| 1261 |
-
triage_job = await enqueue_task(
|
| 1262 |
-
arq_pool,
|
| 1263 |
-
'run_ai_workflow',
|
| 1264 |
-
ticket.id,
|
| 1265 |
-
ticket_data,
|
| 1266 |
-
_job_timeout=900,
|
| 1267 |
-
_job_id=f"ai_workflow_{ticket.id}",
|
| 1268 |
-
force_reroute=force_reroute
|
| 1269 |
-
)
|
| 1270 |
-
|
| 1271 |
-
# 3. Conditional Indexing: Only trigger standalone embedding job if current embedding is missing.
|
| 1272 |
-
# The primary workflow usually handles this, but this is a fallback for legacy/incomplete tickets.
|
| 1273 |
-
indexing_job = None
|
| 1274 |
-
if ticket.embedding is None:
|
| 1275 |
-
from core.tasks import enqueue_task
|
| 1276 |
-
indexing_job = await enqueue_task(arq_pool, 'generate_ticket_embedding', ticket.id)
|
| 1277 |
-
|
| 1278 |
-
# Safety Check: Handle NoneType result from enqueue_job (when a job is already in the queue)
|
| 1279 |
-
triage_id = triage_job.job_id if triage_job else "ALREADY_ENQUEUED"
|
| 1280 |
-
index_id = indexing_job.job_id if indexing_job else ("SKIP" if ticket.embedding is not None else "ALREADY_ENQUEUED")
|
| 1281 |
-
|
| 1282 |
-
# 4. Trigger Reprocessing Summary refresh
|
| 1283 |
-
from core.tasks import enqueue_task
|
| 1284 |
-
await enqueue_task(arq_pool, "auto_summarize_ticket", ticket.id)
|
| 1285 |
-
|
| 1286 |
-
logger.info(f"Manual AI re-trigger: Ticket {ticket_id} (Triage: {triage_id}, Indexing: {index_id})")
|
| 1287 |
-
return {
|
| 1288 |
-
"status": "enqueued",
|
| 1289 |
-
"triage_job_id": triage_id,
|
| 1290 |
-
"indexing_job_id": index_id,
|
| 1291 |
-
"ticket_id": str(ticket.id)
|
| 1292 |
-
}
|
| 1293 |
-
|
| 1294 |
-
@router.post("/{ticket_id}/summarize/", status_code=status.HTTP_202_ACCEPTED)
|
| 1295 |
-
async def summarize_ticket_ai(
|
| 1296 |
-
ticket_id: UUID,
|
| 1297 |
-
current_user: User = Depends(get_current_user),
|
| 1298 |
-
db: AsyncSession = Depends(get_db),
|
| 1299 |
-
arq_pool: ArqRedis = Depends(get_arq_pool)
|
| 1300 |
-
) -> Any:
|
| 1301 |
-
"""
|
| 1302 |
-
Manually trigger ONLY the AI summarization job for a ticket.
|
| 1303 |
-
Provides a lightweight refresh without full re-triage.
|
| 1304 |
-
"""
|
| 1305 |
-
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 1306 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 1307 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 1308 |
-
# Regular customers can only summarize their own tickets
|
| 1309 |
-
if current_user.role == UserRole.CUSTOMER_USER:
|
| 1310 |
-
stmt = stmt.where(Ticket.created_by == current_user.id)
|
| 1311 |
-
|
| 1312 |
-
result = await db.execute(stmt)
|
| 1313 |
-
ticket = result.scalar_one_or_none()
|
| 1314 |
-
if not ticket:
|
| 1315 |
-
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 1316 |
-
|
| 1317 |
-
from core.tasks import enqueue_task
|
| 1318 |
-
job = await enqueue_task(arq_pool, "auto_summarize_ticket", ticket.id, manual=True)
|
| 1319 |
-
job_id = job.job_id if job else "ALREADY_ENQUEUED"
|
| 1320 |
-
|
| 1321 |
-
return {
|
| 1322 |
-
"status": "enqueued",
|
| 1323 |
-
"job_id": job_id,
|
| 1324 |
-
"ticket_id": str(ticket.id)
|
| 1325 |
-
}
|
| 1326 |
-
|
| 1327 |
-
@router.post("/{ticket_id}/reopen-duplicate/", status_code=status.HTTP_200_OK)
|
| 1328 |
-
async def reopen_duplicate_ticket(
|
| 1329 |
-
ticket_id: UUID,
|
| 1330 |
-
current_user: User = Depends(get_current_user),
|
| 1331 |
-
db: AsyncSession = Depends(get_db),
|
| 1332 |
-
arq_pool: ArqRedis = Depends(get_arq_pool)
|
| 1333 |
-
) -> Any:
|
| 1334 |
-
"""
|
| 1335 |
-
Manually reopen a ticket closed as a duplicate and trigger re-triage
|
| 1336 |
-
while bypassing duplication checks.
|
| 1337 |
-
"""
|
| 1338 |
-
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 1339 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 1340 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 1341 |
-
|
| 1342 |
-
result = await db.execute(stmt)
|
| 1343 |
-
ticket = result.scalar_one_or_none()
|
| 1344 |
-
|
| 1345 |
-
if not ticket:
|
| 1346 |
-
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 1347 |
-
|
| 1348 |
-
if not ticket.duplicate_of_id and ticket.status != TicketStatus.CLOSED:
|
| 1349 |
-
raise HTTPException(status_code=400, detail="Ticket is not a closed duplicate.")
|
| 1350 |
-
|
| 1351 |
-
# 1. Reset State
|
| 1352 |
-
ticket.status = TicketStatus.OPEN
|
| 1353 |
-
ticket.duplicate_of_id = None
|
| 1354 |
-
ticket.resolved_at = None
|
| 1355 |
-
ticket.resolution_text = f"Manually reopened by {current_user.full_name or current_user.email}. Retriaging..."
|
| 1356 |
-
|
| 1357 |
-
db.add(ticket)
|
| 1358 |
-
await db.commit()
|
| 1359 |
-
await db.refresh(ticket)
|
| 1360 |
-
|
| 1361 |
-
# 2. Trigger Retriage with Skip Flag
|
| 1362 |
-
from core.tasks import enqueue_task
|
| 1363 |
-
await enqueue_task(
|
| 1364 |
-
arq_pool,
|
| 1365 |
-
"run_ai_workflow",
|
| 1366 |
-
ticket.id,
|
| 1367 |
-
{"id": str(ticket.id), "workspace_id": str(ticket.workspace_id)},
|
| 1368 |
-
force_skip_duplication=True
|
| 1369 |
-
)
|
| 1370 |
-
|
| 1371 |
-
# 3. Trigger manual summary refresh too
|
| 1372 |
-
await enqueue_task(arq_pool, "auto_summarize_ticket", ticket.id)
|
| 1373 |
-
|
| 1374 |
-
logger.info(f"Manual Reopen: Ticket {ticket_id} (Status -> OPEN) by {current_user.id}")
|
| 1375 |
-
|
| 1376 |
-
# Broadcast update
|
| 1377 |
-
from core.websockets import manager
|
| 1378 |
-
await manager.broadcast_to_workspace(
|
| 1379 |
-
ticket.workspace_id,
|
| 1380 |
-
{"event": "ticket_updated", "ticket_id": str(ticket.id), "status": "OPEN"}
|
| 1381 |
-
)
|
| 1382 |
-
|
| 1383 |
-
return {
|
| 1384 |
-
"status": "reopened",
|
| 1385 |
-
"ticket_id": str(ticket.id),
|
| 1386 |
-
"new_status": "OPEN"
|
| 1387 |
-
}
|
| 1388 |
-
|
| 1389 |
-
@router.post("/{ticket_id}/reopen/", response_model=TicketResponse)
|
| 1390 |
-
async def reopen_ticket(
|
| 1391 |
-
ticket_id: UUID,
|
| 1392 |
-
payload: Dict[str, str],
|
| 1393 |
-
current_user: User = Depends(get_current_user),
|
| 1394 |
-
db: AsyncSession = Depends(get_db),
|
| 1395 |
-
arq_pool: ArqRedis = Depends(get_arq_pool)
|
| 1396 |
-
) -> Any:
|
| 1397 |
-
"""
|
| 1398 |
-
Standard Reopen: Moves a RESOLVED or CLOSED ticket back to OPEN.
|
| 1399 |
-
Requires a reason, notifies assignee, and preserves existing agent assignment.
|
| 1400 |
-
"""
|
| 1401 |
-
reason = payload.get("reason", "").strip()
|
| 1402 |
-
if not reason:
|
| 1403 |
-
raise HTTPException(status_code=400, detail="Reopen reason is required.")
|
| 1404 |
-
|
| 1405 |
-
stmt = select(Ticket).options(
|
| 1406 |
-
joinedload(Ticket.creator), joinedload(Ticket.assignee),
|
| 1407 |
-
joinedload(Ticket.resolver), joinedload(Ticket.feedback)
|
| 1408 |
-
).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 1409 |
-
|
| 1410 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 1411 |
-
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 1412 |
-
|
| 1413 |
-
result = await db.execute(stmt)
|
| 1414 |
-
ticket = result.unique().scalar_one_or_none()
|
| 1415 |
-
|
| 1416 |
-
if not ticket:
|
| 1417 |
-
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 1418 |
-
|
| 1419 |
-
if ticket.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
|
| 1420 |
-
raise HTTPException(status_code=400, detail="Only resolved or closed tickets can be reopened.")
|
| 1421 |
-
|
| 1422 |
-
# 1. State Transition
|
| 1423 |
-
old_status = ticket.status
|
| 1424 |
-
ticket.status = TicketStatus.OPEN
|
| 1425 |
-
ticket.resolved_at = None
|
| 1426 |
-
ticket.resolution_text = None
|
| 1427 |
-
ticket.resolved_by = None
|
| 1428 |
-
|
| 1429 |
-
# 2. Reopen Message (Thread record)
|
| 1430 |
-
reopen_msg = Message(
|
| 1431 |
-
id=uuid.uuid4(),
|
| 1432 |
-
workspace_id=ticket.workspace_id,
|
| 1433 |
-
ticket_id=ticket.id,
|
| 1434 |
-
sender_id=current_user.id,
|
| 1435 |
-
content=f"🔄 **Ticket Reopened**\n\n**Reason:** {reason}",
|
| 1436 |
-
is_internal=False
|
| 1437 |
-
)
|
| 1438 |
-
db.add(reopen_msg)
|
| 1439 |
-
|
| 1440 |
-
# 3. Audit Log
|
| 1441 |
-
audit = AuditLog(
|
| 1442 |
-
workspace_id=ticket.workspace_id,
|
| 1443 |
-
entity_type="ticket",
|
| 1444 |
-
entity_id=ticket.id,
|
| 1445 |
-
action="reopen",
|
| 1446 |
-
user_id=current_user.id,
|
| 1447 |
-
old_value={"status": old_status},
|
| 1448 |
-
new_value={"status": "OPEN", "reason": reason}
|
| 1449 |
-
)
|
| 1450 |
-
db.add(audit)
|
| 1451 |
-
|
| 1452 |
-
await db.commit()
|
| 1453 |
-
await db.refresh(ticket)
|
| 1454 |
-
|
| 1455 |
-
# 4. Notify Assignee (Persistence of Assignment)
|
| 1456 |
-
if ticket.assigned_to:
|
| 1457 |
-
from core.tasks import enqueue_task
|
| 1458 |
-
await enqueue_task(
|
| 1459 |
-
arq_pool,
|
| 1460 |
-
"send_triple_notification",
|
| 1461 |
-
str(ticket.assigned_to),
|
| 1462 |
-
str(ticket.workspace_id),
|
| 1463 |
-
"🔄 Ticket Reopened",
|
| 1464 |
-
f"Ticket '{ticket.title}' has been reopened by the customer. Reason: {reason[:100]}...",
|
| 1465 |
-
link=f"/dashboard?ticket={ticket.id}"
|
| 1466 |
-
)
|
| 1467 |
-
|
| 1468 |
-
# 5. Broadcast via WebSocket
|
| 1469 |
-
await manager.broadcast_to_workspace(
|
| 1470 |
-
ticket.workspace_id,
|
| 1471 |
-
{"event": "ticket_updated", "ticket_id": str(ticket.id), "status": "OPEN"}
|
| 1472 |
-
)
|
| 1473 |
-
|
| 1474 |
-
logger.info(f"Ticket {ticket.id} reopened by {current_user.id}")
|
| 1475 |
-
return await sanitize_ticket_response(ticket, current_user, db)
|
| 1476 |
-
|
| 1477 |
-
@router.post("/{ticket_id}/escalate/", response_model=TicketResponse)
|
| 1478 |
-
async def trigger_manual_escalation(
|
| 1479 |
-
ticket_id: UUID,
|
| 1480 |
-
current_user: User = Depends(get_current_user),
|
| 1481 |
-
db: AsyncSession = Depends(get_db),
|
| 1482 |
-
arq_pool: ArqRedis = Depends(get_arq_pool)
|
| 1483 |
-
) -> Any:
|
| 1484 |
-
"""Manual Escalation: Force priority to P0 and mark as escalated."""
|
| 1485 |
-
esc_stmt = (
|
| 1486 |
-
select(Ticket)
|
| 1487 |
-
.options(
|
| 1488 |
-
joinedload(Ticket.creator),
|
| 1489 |
-
joinedload(Ticket.assignee),
|
| 1490 |
-
joinedload(Ticket.resolver),
|
| 1491 |
-
joinedload(Ticket.feedback)
|
| 1492 |
-
)
|
| 1493 |
-
.where(
|
| 1494 |
-
Ticket.id == ticket_id,
|
| 1495 |
-
Ticket.deleted_at.is_(None)
|
| 1496 |
-
)
|
| 1497 |
-
)
|
| 1498 |
-
if current_user.role != UserRole.SC_ADMIN:
|
| 1499 |
-
esc_stmt = esc_stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
| 1500 |
-
result = await db.execute(esc_stmt)
|
| 1501 |
-
ticket = result.unique().scalar_one_or_none()
|
| 1502 |
-
|
| 1503 |
-
if not ticket:
|
| 1504 |
-
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 1505 |
-
|
| 1506 |
-
if ticket.is_escalated:
|
| 1507 |
-
raise HTTPException(status_code=400, detail="Ticket is already escalated")
|
| 1508 |
-
|
| 1509 |
-
# 1. Update State
|
| 1510 |
-
old_priority = ticket.priority
|
| 1511 |
-
ticket.is_escalated = datetime.utcnow()
|
| 1512 |
-
ticket.priority = TicketPriority.P0
|
| 1513 |
-
db.add(ticket)
|
| 1514 |
-
|
| 1515 |
-
# 2. Add System Message
|
| 1516 |
-
sys_msg = Message(
|
| 1517 |
-
id=uuid.uuid4(),
|
| 1518 |
-
workspace_id=ticket.workspace_id, # Preserve the ticket's actual workspace
|
| 1519 |
-
ticket_id=ticket.id,
|
| 1520 |
-
sender_id=current_user.id,
|
| 1521 |
-
content=f"🚨 **Manual Escalation triggered by {current_user.full_name}**. Priority elevated to P0.",
|
| 1522 |
-
is_internal=False
|
| 1523 |
-
)
|
| 1524 |
-
db.add(sys_msg)
|
| 1525 |
-
|
| 1526 |
-
# 3. Log Audit (Safe Serialization)
|
| 1527 |
-
# Ensure is_escalated (datetime) and UUIDs are stringified
|
| 1528 |
-
audit = AuditLog(
|
| 1529 |
-
workspace_id=current_user.workspace_id,
|
| 1530 |
-
entity_type="ticket",
|
| 1531 |
-
entity_id=ticket.id,
|
| 1532 |
-
action="escalation",
|
| 1533 |
-
user_id=current_user.id,
|
| 1534 |
-
old_value={"priority": str(old_priority)},
|
| 1535 |
-
new_value={"priority": "P0", "is_escalated": ticket.is_escalated.isoformat()}
|
| 1536 |
-
)
|
| 1537 |
-
db.add(audit)
|
| 1538 |
-
|
| 1539 |
-
|
| 1540 |
-
await db.commit()
|
| 1541 |
-
await db.refresh(ticket)
|
| 1542 |
-
|
| 1543 |
-
# 4. Notify Workspace Lead/Admin via Triple-Threat Protocol
|
| 1544 |
-
from agents.utils import get_workspace_manager
|
| 1545 |
-
manager_user = await get_workspace_manager(db, ticket.workspace_id)
|
| 1546 |
-
if manager_user:
|
| 1547 |
-
from core.tasks import enqueue_task
|
| 1548 |
-
await enqueue_task(
|
| 1549 |
-
arq_pool,
|
| 1550 |
-
"send_triple_notification",
|
| 1551 |
-
str(manager_user.id),
|
| 1552 |
-
str(ticket.workspace_id),
|
| 1553 |
-
"🚨 Manual Escalation Alert",
|
| 1554 |
-
f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.",
|
| 1555 |
-
link=f"/dashboard?ticket={ticket.id}"
|
| 1556 |
-
)
|
| 1557 |
-
|
| 1558 |
-
# Notify Creator: We're on it!
|
| 1559 |
-
await enqueue_task(
|
| 1560 |
-
arq_pool,
|
| 1561 |
-
"send_triple_notification",
|
| 1562 |
-
str(ticket.created_by),
|
| 1563 |
-
str(ticket.workspace_id),
|
| 1564 |
-
"⚡ Priority Boosted",
|
| 1565 |
-
f"Your ticket '{ticket.title}' has been prioritized for immediate leadership review.",
|
| 1566 |
-
link=f"/dashboard?ticket={ticket.id}"
|
| 1567 |
-
)
|
| 1568 |
-
|
| 1569 |
-
# 5. Notify Assignee (if different from manager)
|
| 1570 |
-
if ticket.assigned_to and (not manager_user or ticket.assigned_to != manager_user.id):
|
| 1571 |
-
await enqueue_task(
|
| 1572 |
-
arq_pool,
|
| 1573 |
-
"send_triple_notification",
|
| 1574 |
-
str(ticket.assigned_to),
|
| 1575 |
-
str(ticket.workspace_id),
|
| 1576 |
-
"🚨 Urgent Escalation",
|
| 1577 |
-
f"A lead has manually escalated ticket '{ticket.title}' to P0. This is now a critical priority.",
|
| 1578 |
-
link=f"/dashboard?ticket={ticket.id}"
|
| 1579 |
-
)
|
| 1580 |
-
|
| 1581 |
-
logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")
|
| 1582 |
-
|
| 1583 |
-
# Refresh to pick up lead info in sanitizer
|
| 1584 |
-
return await sanitize_ticket_response(ticket, current_user, db)
|
|
|
|
| 1 |
"""
|
| 2 |
+
Ticket endpoints: CRUD, status transitions, and assignments. (Refactored to use TicketService)
|
| 3 |
"""
|
| 4 |
|
| 5 |
+
from typing import Any, List, Optional, Union
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from uuid import UUID
|
| 7 |
+
from fastapi import APIRouter, Depends, status
|
|
|
|
|
|
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
+
from sqlalchemy import select
|
| 10 |
from sqlalchemy.orm import joinedload
|
|
|
|
| 11 |
|
|
|
|
| 12 |
from core.deps import get_db, get_current_user, get_arq_pool
|
| 13 |
+
from core.permissions import require_roles, WORKSPACE_ADMIN_ROLES, ALL_CUSTOMER_ROLES
|
| 14 |
+
from models.user import User
|
| 15 |
+
from models.ticket import Ticket, TicketStatus
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
from schemas.ticket import (
|
| 17 |
+
TicketCreate, TicketUpdate, TicketResponse, TicketInternalResponse
|
|
|
|
| 18 |
)
|
| 19 |
+
from services.ticket_service import TicketService
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
router = APIRouter()
|
|
|
|
| 22 |
|
| 23 |
+
# Re-export for dashboard.py and other internal consumers
|
| 24 |
+
sanitize_ticket_response = TicketService.sanitize_ticket_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
@router.post("/", response_model=Union[TicketInternalResponse, TicketResponse], status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ALL_CUSTOMER_ROLES + WORKSPACE_ADMIN_ROLES))])
|
| 27 |
async def create_ticket(
|
| 28 |
payload: TicketCreate,
|
|
|
|
| 29 |
current_user: User = Depends(get_current_user),
|
| 30 |
db: AsyncSession = Depends(get_db),
|
| 31 |
arq_pool: Any = Depends(get_arq_pool)
|
| 32 |
) -> Any:
|
| 33 |
+
"""Create a new ticket."""
|
| 34 |
+
return await TicketService.create_ticket(payload, current_user, db, arq_pool)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
@router.get("/", response_model=List[Union[TicketInternalResponse, TicketResponse]])
|
| 37 |
async def list_tickets(
|
| 38 |
skip: int = 0, limit: int = 100,
|
| 39 |
status_filter: Optional[TicketStatus] = None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
current_user: User = Depends(get_current_user),
|
| 41 |
db: AsyncSession = Depends(get_db)
|
| 42 |
) -> Any:
|
| 43 |
+
"""List tickets for the current workspace."""
|
| 44 |
+
stmt = select(Ticket).options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver), joinedload(Ticket.feedback)).where(Ticket.deleted_at.is_(None))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
if not current_user.is_platform_admin:
|
| 46 |
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if status_filter:
|
| 49 |
+
stmt = stmt.where(Ticket.status == status_filter)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
result = await db.execute(stmt.offset(skip).limit(limit).order_by(Ticket.created_at.desc()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
tickets = result.scalars().unique().all()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
return [await TicketService.sanitize_ticket_response(t, current_user, db) for t in tickets]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
@router.get("/{ticket_id}/", response_model=Union[TicketInternalResponse, TicketResponse])
|
| 57 |
async def get_ticket(
|
| 58 |
ticket_id: UUID,
|
|
|
|
| 59 |
current_user: User = Depends(get_current_user),
|
| 60 |
db: AsyncSession = Depends(get_db)
|
| 61 |
) -> Any:
|
| 62 |
+
"""Get a specific ticket."""
|
| 63 |
+
stmt = select(Ticket).options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver), joinedload(Ticket.feedback)).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 64 |
+
if not current_user.is_platform_admin:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
ticket = (await db.execute(stmt)).unique().scalar_one_or_none()
|
| 68 |
+
if not ticket:
|
| 69 |
+
from fastapi import HTTPException
|
| 70 |
+
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 71 |
|
| 72 |
+
return await TicketService.sanitize_ticket_response(ticket, current_user, db)
|
| 73 |
|
| 74 |
@router.patch("/{ticket_id}/", response_model=Union[TicketInternalResponse, TicketResponse])
|
| 75 |
async def update_ticket(
|
| 76 |
ticket_id: UUID,
|
| 77 |
payload: TicketUpdate,
|
|
|
|
| 78 |
current_user: User = Depends(get_current_user),
|
| 79 |
db: AsyncSession = Depends(get_db),
|
| 80 |
arq_pool: Any = Depends(get_arq_pool)
|
| 81 |
) -> Any:
|
| 82 |
+
"""Update a ticket."""
|
| 83 |
+
return await TicketService.update_ticket(ticket_id, payload, current_user, db, arq_pool)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
core/tasks.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
frontend/apps/customer/src/components/KnowledgeBase.module.css
CHANGED
|
@@ -9,9 +9,9 @@
|
|
| 9 |
|
| 10 |
.searchHero {
|
| 11 |
margin-bottom: 64px;
|
| 12 |
-
text-align:
|
| 13 |
-
max-width:
|
| 14 |
-
margin-
|
| 15 |
}
|
| 16 |
|
| 17 |
.searchHero h1 {
|
|
@@ -37,10 +37,10 @@
|
|
| 37 |
display: flex;
|
| 38 |
gap: 24px;
|
| 39 |
align-items: center;
|
| 40 |
-
justify-content:
|
| 41 |
flex-wrap: wrap;
|
| 42 |
max-width: 1000px;
|
| 43 |
-
margin: 0
|
| 44 |
}
|
| 45 |
|
| 46 |
.searchWrapper {
|
|
|
|
| 9 |
|
| 10 |
.searchHero {
|
| 11 |
margin-bottom: 64px;
|
| 12 |
+
text-align: left;
|
| 13 |
+
max-width: 1000px;
|
| 14 |
+
margin-left: 0;
|
| 15 |
}
|
| 16 |
|
| 17 |
.searchHero h1 {
|
|
|
|
| 37 |
display: flex;
|
| 38 |
gap: 24px;
|
| 39 |
align-items: center;
|
| 40 |
+
justify-content: flex-start;
|
| 41 |
flex-wrap: wrap;
|
| 42 |
max-width: 1000px;
|
| 43 |
+
margin: 0;
|
| 44 |
}
|
| 45 |
|
| 46 |
.searchWrapper {
|
frontend/apps/customer/src/components/ThreadView.tsx
CHANGED
|
@@ -1,6 +1,14 @@
|
|
| 1 |
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
| 2 |
import { StatusBadge } from './Badges';
|
| 3 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import styles from './ThreadView.module.css';
|
| 5 |
|
| 6 |
import {
|
|
@@ -16,67 +24,6 @@ import {
|
|
| 16 |
Trash2
|
| 17 |
} from 'lucide-react';
|
| 18 |
|
| 19 |
-
interface Attachment {
|
| 20 |
-
id: string;
|
| 21 |
-
filename: string;
|
| 22 |
-
content_type: string;
|
| 23 |
-
file_size: number;
|
| 24 |
-
ai_caption?: string;
|
| 25 |
-
is_processed: boolean;
|
| 26 |
-
created_at: string;
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
interface Message {
|
| 30 |
-
id: string;
|
| 31 |
-
content: string;
|
| 32 |
-
sender_id: string;
|
| 33 |
-
sender_name?: string;
|
| 34 |
-
sender_role?: string;
|
| 35 |
-
is_internal: boolean;
|
| 36 |
-
created_at: string;
|
| 37 |
-
attachments?: Attachment[];
|
| 38 |
-
is_sending?: boolean;
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
interface SimilarArticle {
|
| 42 |
-
id: string;
|
| 43 |
-
title: string;
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
-
interface SimilarTicket {
|
| 47 |
-
id: string;
|
| 48 |
-
title: string;
|
| 49 |
-
similarity: number;
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
interface Ticket {
|
| 55 |
-
id: string;
|
| 56 |
-
title: string;
|
| 57 |
-
description: string;
|
| 58 |
-
status: string;
|
| 59 |
-
priority: string;
|
| 60 |
-
workspace_id: string;
|
| 61 |
-
created_by: string;
|
| 62 |
-
assigned_to?: string;
|
| 63 |
-
assigned_name?: string;
|
| 64 |
-
summary?: string;
|
| 65 |
-
resolved_at?: string;
|
| 66 |
-
resolved_by_name?: string;
|
| 67 |
-
resolution_text?: string;
|
| 68 |
-
expected_resolution_at: string;
|
| 69 |
-
is_escalated: string | null;
|
| 70 |
-
created_at: string;
|
| 71 |
-
rating?: number;
|
| 72 |
-
feedback_comment?: string;
|
| 73 |
-
attachments?: Attachment[];
|
| 74 |
-
duplicate_of_id?: string;
|
| 75 |
-
duplicate_of_title?: string;
|
| 76 |
-
similar_articles?: SimilarArticle[];
|
| 77 |
-
similar_tickets?: SimilarTicket[];
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
interface ThreadViewProps {
|
| 81 |
ticket: Ticket;
|
| 82 |
onBack: () => void;
|
|
@@ -165,7 +112,7 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
|
|
| 165 |
} else if ((data.event === 'ticket_updated' || data.event === 'new_message') && data.ticket_id === ticket.id) {
|
| 166 |
if (data.event === 'new_message') {
|
| 167 |
setMessages(prev => {
|
| 168 |
-
if (prev.some(m => m.id === data.message.id
|
| 169 |
return [...prev, data.message];
|
| 170 |
});
|
| 171 |
setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 50);
|
|
@@ -293,7 +240,7 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
|
|
| 293 |
if (!newMessage.trim() || sending) return;
|
| 294 |
const content = newMessage;
|
| 295 |
const tempId = `temp-${Date.now()}`;
|
| 296 |
-
const optimisticMsg:
|
| 297 |
id: tempId,
|
| 298 |
content: content,
|
| 299 |
sender_id: currentUser?.id || 'unknown',
|
|
@@ -718,7 +665,7 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
|
|
| 718 |
<div className={`${styles.messageBubble} ${isMe ? styles.messageBubbleMe : styles.messageBubbleThem}`}>
|
| 719 |
<div style={{ position: 'relative' }}>
|
| 720 |
<NexusMarkdown content={m.content} isMe={isMe} />
|
| 721 |
-
{m.is_sending && (
|
| 722 |
<div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4, opacity: 0.6, fontSize: '9px', fontWeight: 700 }}>
|
| 723 |
<Loader2 size={10} className={styles.spin} />
|
| 724 |
<span>SYNCHRONIZING...</span>
|
|
|
|
| 1 |
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
| 2 |
import { StatusBadge } from './Badges';
|
| 3 |
+
import {
|
| 4 |
+
api,
|
| 5 |
+
NexusMarkdown,
|
| 6 |
+
getFileIcon,
|
| 7 |
+
getStorageKey,
|
| 8 |
+
useMentions,
|
| 9 |
+
MentionOverlay
|
| 10 |
+
} from '@nexus/shared';
|
| 11 |
+
import type { Ticket, Message } from '@nexus/shared';
|
| 12 |
import styles from './ThreadView.module.css';
|
| 13 |
|
| 14 |
import {
|
|
|
|
| 24 |
Trash2
|
| 25 |
} from 'lucide-react';
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
interface ThreadViewProps {
|
| 28 |
ticket: Ticket;
|
| 29 |
onBack: () => void;
|
|
|
|
| 112 |
} else if ((data.event === 'ticket_updated' || data.event === 'new_message') && data.ticket_id === ticket.id) {
|
| 113 |
if (data.event === 'new_message') {
|
| 114 |
setMessages(prev => {
|
| 115 |
+
if (prev.some(m => m.id === data.message.id)) return prev;
|
| 116 |
return [...prev, data.message];
|
| 117 |
});
|
| 118 |
setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 50);
|
|
|
|
| 240 |
if (!newMessage.trim() || sending) return;
|
| 241 |
const content = newMessage;
|
| 242 |
const tempId = `temp-${Date.now()}`;
|
| 243 |
+
const optimisticMsg: any = {
|
| 244 |
id: tempId,
|
| 245 |
content: content,
|
| 246 |
sender_id: currentUser?.id || 'unknown',
|
|
|
|
| 665 |
<div className={`${styles.messageBubble} ${isMe ? styles.messageBubbleMe : styles.messageBubbleThem}`}>
|
| 666 |
<div style={{ position: 'relative' }}>
|
| 667 |
<NexusMarkdown content={m.content} isMe={isMe} />
|
| 668 |
+
{(m as any).is_sending && (
|
| 669 |
<div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4, opacity: 0.6, fontSize: '9px', fontWeight: 700 }}>
|
| 670 |
<Loader2 size={10} className={styles.spin} />
|
| 671 |
<span>SYNCHRONIZING...</span>
|
frontend/apps/internal/src/components/TicketDetails.tsx
CHANGED
|
@@ -1,6 +1,14 @@
|
|
| 1 |
/* BUILD_REFRESH: 2026-04-17-0815 - Ensuring label synchronization */
|
| 2 |
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
| 3 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import styles from './TicketDetails.module.css';
|
| 5 |
import {
|
| 6 |
ShieldAlert,
|
|
@@ -20,48 +28,6 @@ import {
|
|
| 20 |
|
| 21 |
import { motion } from 'framer-motion';
|
| 22 |
|
| 23 |
-
interface Message {
|
| 24 |
-
id: string;
|
| 25 |
-
content: string;
|
| 26 |
-
sender_name: string;
|
| 27 |
-
sender_role: string;
|
| 28 |
-
is_internal: boolean;
|
| 29 |
-
created_at: string;
|
| 30 |
-
is_sending?: boolean;
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
interface Ticket {
|
| 34 |
-
id: string;
|
| 35 |
-
title: string;
|
| 36 |
-
description: string;
|
| 37 |
-
status: string;
|
| 38 |
-
priority: string;
|
| 39 |
-
assigned_to?: string;
|
| 40 |
-
assigned_name?: string;
|
| 41 |
-
is_escalated?: string | null;
|
| 42 |
-
duplicate_of_id?: string | null;
|
| 43 |
-
resolution_text?: string;
|
| 44 |
-
expected_resolution_at?: string;
|
| 45 |
-
estimated_effort_hours?: { value: number; complexity: string } | number;
|
| 46 |
-
sla_deadline?: string;
|
| 47 |
-
sla_breach?: boolean;
|
| 48 |
-
created_at: string;
|
| 49 |
-
resolved_at?: string;
|
| 50 |
-
ai_metadata?: {
|
| 51 |
-
summaries?: {
|
| 52 |
-
internal_summary?: string;
|
| 53 |
-
customer_summary?: string;
|
| 54 |
-
};
|
| 55 |
-
initial_analysis?: {
|
| 56 |
-
rca: string;
|
| 57 |
-
technical_solution: string;
|
| 58 |
-
relevant_article?: string;
|
| 59 |
-
};
|
| 60 |
-
processed_steps?: { name?: string; agent_name?: string; status?: string }[];
|
| 61 |
-
similar_tickets?: { id: string; title: string; similarity: number; status: string }[];
|
| 62 |
-
};
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
interface UserProfile {
|
| 66 |
id: string;
|
| 67 |
full_name: string;
|
|
@@ -81,12 +47,6 @@ interface AuditEntry {
|
|
| 81 |
created_at: string;
|
| 82 |
}
|
| 83 |
|
| 84 |
-
interface Attachment {
|
| 85 |
-
id: string;
|
| 86 |
-
filename: string;
|
| 87 |
-
content_type: string;
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
interface TicketDetailsProps {
|
| 91 |
initialTicket?: Ticket;
|
| 92 |
onBack?: () => void;
|
|
|
|
| 1 |
/* BUILD_REFRESH: 2026-04-17-0815 - Ensuring label synchronization */
|
| 2 |
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
| 3 |
+
import {
|
| 4 |
+
api,
|
| 5 |
+
NexusMarkdown,
|
| 6 |
+
useAuth,
|
| 7 |
+
getFileIcon,
|
| 8 |
+
useMentions,
|
| 9 |
+
MentionOverlay
|
| 10 |
+
} from '@nexus/shared';
|
| 11 |
+
import type { Ticket, Message, Attachment } from '@nexus/shared';
|
| 12 |
import styles from './TicketDetails.module.css';
|
| 13 |
import {
|
| 14 |
ShieldAlert,
|
|
|
|
| 28 |
|
| 29 |
import { motion } from 'framer-motion';
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
interface UserProfile {
|
| 32 |
id: string;
|
| 33 |
full_name: string;
|
|
|
|
| 47 |
created_at: string;
|
| 48 |
}
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
interface TicketDetailsProps {
|
| 51 |
initialTicket?: Ticket;
|
| 52 |
onBack?: () => void;
|
frontend/packages/shared/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
| 5 |
"type": "module",
|
| 6 |
"main": "./src/index.ts",
|
| 7 |
"scripts": {
|
| 8 |
-
"build": "
|
| 9 |
},
|
| 10 |
"dependencies": {
|
| 11 |
"axios": "^1.14.0",
|
|
@@ -17,5 +17,8 @@
|
|
| 17 |
"react-markdown": "^10.1.0",
|
| 18 |
"react-syntax-highlighter": "^16.1.1",
|
| 19 |
"remark-gfm": "^4.0.1"
|
|
|
|
|
|
|
|
|
|
| 20 |
}
|
| 21 |
}
|
|
|
|
| 5 |
"type": "module",
|
| 6 |
"main": "./src/index.ts",
|
| 7 |
"scripts": {
|
| 8 |
+
"build": "tsc"
|
| 9 |
},
|
| 10 |
"dependencies": {
|
| 11 |
"axios": "^1.14.0",
|
|
|
|
| 17 |
"react-markdown": "^10.1.0",
|
| 18 |
"react-syntax-highlighter": "^16.1.1",
|
| 19 |
"remark-gfm": "^4.0.1"
|
| 20 |
+
},
|
| 21 |
+
"devDependencies": {
|
| 22 |
+
"vite": "^6.2.0"
|
| 23 |
}
|
| 24 |
}
|
frontend/packages/shared/src/hooks/useTickets.ts
CHANGED
|
@@ -1,30 +1,7 @@
|
|
| 1 |
import { useState, useCallback, useEffect } from 'react';
|
| 2 |
import api from '../utils/api';
|
| 3 |
import { useAuth } from './useAuth';
|
| 4 |
-
|
| 5 |
-
export interface Ticket {
|
| 6 |
-
id: string;
|
| 7 |
-
title: string;
|
| 8 |
-
description: string;
|
| 9 |
-
status: string;
|
| 10 |
-
priority: string;
|
| 11 |
-
category?: string;
|
| 12 |
-
created_at: string;
|
| 13 |
-
updated_at: string;
|
| 14 |
-
workspace_id: string;
|
| 15 |
-
created_by: string;
|
| 16 |
-
assigned_to?: string;
|
| 17 |
-
assigned_name?: string;
|
| 18 |
-
creator_name?: string;
|
| 19 |
-
ai_metadata?: {
|
| 20 |
-
sentiment?: string;
|
| 21 |
-
ai_score?: number;
|
| 22 |
-
rating?: number;
|
| 23 |
-
[key: string]: any;
|
| 24 |
-
};
|
| 25 |
-
sla_deadline?: string;
|
| 26 |
-
metadata?: any;
|
| 27 |
-
}
|
| 28 |
|
| 29 |
// Global singletons with staleness tracking
|
| 30 |
// Now with sessionStorage persistence for zero-latency discovery
|
|
|
|
| 1 |
import { useState, useCallback, useEffect } from 'react';
|
| 2 |
import api from '../utils/api';
|
| 3 |
import { useAuth } from './useAuth';
|
| 4 |
+
import type { Ticket } from '../types';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
// Global singletons with staleness tracking
|
| 7 |
// Now with sessionStorage persistence for zero-latency discovery
|
frontend/packages/shared/src/hooks/useTicketsPaginated.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import { useState, useCallback } from 'react';
|
| 2 |
import api from '../utils/api';
|
| 3 |
-
import type { Ticket } from './
|
| 4 |
|
| 5 |
interface PaginatedResponse {
|
| 6 |
items: Ticket[];
|
|
|
|
| 1 |
import { useState, useCallback } from 'react';
|
| 2 |
import api from '../utils/api';
|
| 3 |
+
import type { Ticket } from '../types';
|
| 4 |
|
| 5 |
interface PaginatedResponse {
|
| 6 |
items: Ticket[];
|
frontend/packages/shared/src/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
// Central export point for shared Nexus logic
|
| 2 |
-
|
| 3 |
export * from './components/Button';
|
| 4 |
export * from './components/Input';
|
| 5 |
export * from './components/LoginCard';
|
|
@@ -21,6 +21,7 @@ export * from './hooks/useUsers';
|
|
| 21 |
export * from './hooks/useWorkspaces';
|
| 22 |
export * from './hooks/useKnowledgeBase';
|
| 23 |
export * from './hooks/useMentions';
|
|
|
|
| 24 |
export { api, setPortalType, getWsUrl, getStorageKey } from './utils/api';
|
| 25 |
export * from './utils/fileIcons';
|
| 26 |
import apiDefault from './utils/api';
|
|
|
|
| 1 |
// Central export point for shared Nexus logic
|
| 2 |
+
import './styles/theme.css';
|
| 3 |
export * from './components/Button';
|
| 4 |
export * from './components/Input';
|
| 5 |
export * from './components/LoginCard';
|
|
|
|
| 21 |
export * from './hooks/useWorkspaces';
|
| 22 |
export * from './hooks/useKnowledgeBase';
|
| 23 |
export * from './hooks/useMentions';
|
| 24 |
+
export * from './types';
|
| 25 |
export { api, setPortalType, getWsUrl, getStorageKey } from './utils/api';
|
| 26 |
export * from './utils/fileIcons';
|
| 27 |
import apiDefault from './utils/api';
|
frontend/packages/shared/src/types/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export * from './ticket';
|
frontend/packages/shared/src/types/ticket.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export type TicketStatus = 'OPEN' | 'ACKNOWLEDGED' | 'IN_PROGRESS' | 'RESOLVED' | 'CLOSED';
|
| 2 |
+
export type TicketPriority = 'P0' | 'P1' | 'P2' | 'P3';
|
| 3 |
+
|
| 4 |
+
export interface Ticket {
|
| 5 |
+
id: string;
|
| 6 |
+
title: string;
|
| 7 |
+
description: string;
|
| 8 |
+
status: TicketStatus;
|
| 9 |
+
priority: TicketPriority;
|
| 10 |
+
category?: string;
|
| 11 |
+
workspace_id: string;
|
| 12 |
+
created_by: string;
|
| 13 |
+
assigned_to?: string;
|
| 14 |
+
assigned_name?: string;
|
| 15 |
+
creator_name?: string;
|
| 16 |
+
project_id?: string;
|
| 17 |
+
sla_deadline?: string;
|
| 18 |
+
sla_breach?: boolean;
|
| 19 |
+
expected_resolution_at?: string;
|
| 20 |
+
resolved_at?: string;
|
| 21 |
+
resolved_by_name?: string;
|
| 22 |
+
resolution_text?: string;
|
| 23 |
+
summary?: string;
|
| 24 |
+
rating?: number;
|
| 25 |
+
feedback_comment?: string;
|
| 26 |
+
is_mine: boolean;
|
| 27 |
+
is_escalated?: string | null;
|
| 28 |
+
escalated_to_name?: string;
|
| 29 |
+
duplicate_of_id?: string;
|
| 30 |
+
duplicate_of_title?: string;
|
| 31 |
+
created_at: string;
|
| 32 |
+
updated_at: string;
|
| 33 |
+
similar_articles?: any[];
|
| 34 |
+
similar_tickets?: any[];
|
| 35 |
+
attachments?: Attachment[];
|
| 36 |
+
ai_metadata?: {
|
| 37 |
+
ai_score?: number;
|
| 38 |
+
sentiment?: string;
|
| 39 |
+
summaries?: {
|
| 40 |
+
internal_summary?: string;
|
| 41 |
+
customer_summary?: string;
|
| 42 |
+
};
|
| 43 |
+
initial_analysis?: {
|
| 44 |
+
rca: string;
|
| 45 |
+
technical_solution: string;
|
| 46 |
+
relevant_article?: string;
|
| 47 |
+
};
|
| 48 |
+
processed_steps?: { name?: string; agent_name?: string; status?: string }[];
|
| 49 |
+
similar_tickets?: { id: string; title: string; similarity: number; status: string }[];
|
| 50 |
+
[key: string]: any;
|
| 51 |
+
};
|
| 52 |
+
estimated_effort_hours?: { value: number; complexity: string } | number;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export interface Attachment {
|
| 56 |
+
id: string;
|
| 57 |
+
filename: string;
|
| 58 |
+
content_type: string;
|
| 59 |
+
file_size: number;
|
| 60 |
+
ai_caption?: string;
|
| 61 |
+
is_processed: boolean;
|
| 62 |
+
created_at: string;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
export interface Message {
|
| 66 |
+
id: string;
|
| 67 |
+
ticket_id: string;
|
| 68 |
+
sender_id: string;
|
| 69 |
+
sender_name: string;
|
| 70 |
+
sender_role: string;
|
| 71 |
+
content: string;
|
| 72 |
+
is_internal: boolean;
|
| 73 |
+
created_at: string;
|
| 74 |
+
attachments?: Attachment[];
|
| 75 |
+
is_sending?: boolean;
|
| 76 |
+
}
|
frontend/packages/shared/tsconfig.json
CHANGED
|
@@ -15,7 +15,8 @@
|
|
| 15 |
"isolatedModules": true,
|
| 16 |
"noEmit": true,
|
| 17 |
"jsx": "react-jsx",
|
| 18 |
-
"baseUrl": "."
|
|
|
|
| 19 |
},
|
| 20 |
"include": ["src"]
|
| 21 |
}
|
|
|
|
| 15 |
"isolatedModules": true,
|
| 16 |
"noEmit": true,
|
| 17 |
"jsx": "react-jsx",
|
| 18 |
+
"baseUrl": ".",
|
| 19 |
+
"types": ["vite/client"]
|
| 20 |
},
|
| 21 |
"include": ["src"]
|
| 22 |
}
|
services/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Services package
|
services/ticket_service.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ticket Service: Handles core business logic for tickets.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import uuid
|
| 6 |
+
import hashlib
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
from typing import Any, Optional, Dict
|
| 9 |
+
from uuid import UUID
|
| 10 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 11 |
+
from sqlalchemy import select, update, cast, String
|
| 12 |
+
from sqlalchemy.orm import joinedload
|
| 13 |
+
from fastapi import HTTPException
|
| 14 |
+
|
| 15 |
+
from core.config import get_settings
|
| 16 |
+
from core.logging import get_logger
|
| 17 |
+
from core.cache import (
|
| 18 |
+
delete_by_pattern, invalidate_workspace_semantic_cache,
|
| 19 |
+
invalidate_cache
|
| 20 |
+
)
|
| 21 |
+
from core.websockets import manager
|
| 22 |
+
from models.user import User, UserRole
|
| 23 |
+
from models.user_workspace import UserWorkspace
|
| 24 |
+
from models.project import Project
|
| 25 |
+
from models.ticket import Ticket, TicketStatus, ALLOWED_TRANSITIONS, TicketPriority
|
| 26 |
+
from models.audit_log import AuditLog
|
| 27 |
+
from models.escalation_rule import EscalationRule
|
| 28 |
+
from models.attachment import Attachment
|
| 29 |
+
from schemas.ticket import (
|
| 30 |
+
TicketCreate, TicketUpdate, TicketResponse, TicketInternalResponse
|
| 31 |
+
)
|
| 32 |
+
from tasks.system import enqueue_task
|
| 33 |
+
|
| 34 |
+
logger = get_logger(__name__)
|
| 35 |
+
settings = get_settings()
|
| 36 |
+
|
| 37 |
+
class TicketService:
|
| 38 |
+
@staticmethod
|
| 39 |
+
async def sanitize_ticket_response(
|
| 40 |
+
ticket: Ticket,
|
| 41 |
+
user: User,
|
| 42 |
+
db: AsyncSession,
|
| 43 |
+
lead_name: Optional[str] = None,
|
| 44 |
+
dup_title: Optional[str] = None
|
| 45 |
+
) -> Dict[str, Any]:
|
| 46 |
+
"""Injects role-based metadata and masks internal data."""
|
| 47 |
+
is_staff = user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 48 |
+
|
| 49 |
+
# Summary
|
| 50 |
+
if ticket.ai_metadata and "summaries" in ticket.ai_metadata:
|
| 51 |
+
summaries = ticket.ai_metadata.get("summaries", {})
|
| 52 |
+
setattr(ticket, "summary", summaries.get("internal_summary" if is_staff else "customer_summary"))
|
| 53 |
+
else:
|
| 54 |
+
setattr(ticket, "summary", None)
|
| 55 |
+
|
| 56 |
+
setattr(ticket, "assigned_name", ticket.assignee.full_name if ticket.assignee else None)
|
| 57 |
+
setattr(ticket, "resolved_by_name", ticket.resolver.full_name if ticket.resolver else (settings.SUPER_ADMIN_NAME if ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED] else None))
|
| 58 |
+
setattr(ticket, "creator_name", ticket.creator.full_name if ticket.creator else "System")
|
| 59 |
+
setattr(ticket, "is_mine", ticket.created_by == user.id)
|
| 60 |
+
|
| 61 |
+
# Escalation Lead
|
| 62 |
+
setattr(ticket, "escalated_to_name", lead_name)
|
| 63 |
+
if ticket.is_escalated and not lead_name:
|
| 64 |
+
stmt = select(User.full_name).join(UserWorkspace).where(
|
| 65 |
+
UserWorkspace.workspace_id == ticket.workspace_id,
|
| 66 |
+
UserWorkspace.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]),
|
| 67 |
+
User.is_active
|
| 68 |
+
).limit(1)
|
| 69 |
+
res = await db.execute(stmt)
|
| 70 |
+
setattr(ticket, "escalated_to_name", res.scalar_one_or_none())
|
| 71 |
+
|
| 72 |
+
# Duplicate Title
|
| 73 |
+
setattr(ticket, "duplicate_of_title", dup_title)
|
| 74 |
+
if ticket.duplicate_of_id and not dup_title:
|
| 75 |
+
dup_stmt = select(Ticket.title).where(Ticket.id == ticket.duplicate_of_id)
|
| 76 |
+
setattr(ticket, "duplicate_of_title", (await db.execute(dup_stmt)).scalar_one_or_none())
|
| 77 |
+
|
| 78 |
+
if is_staff:
|
| 79 |
+
return TicketInternalResponse.model_validate(ticket).model_dump(mode='json')
|
| 80 |
+
return TicketResponse.model_validate(ticket).model_dump(mode='json')
|
| 81 |
+
|
| 82 |
+
@staticmethod
|
| 83 |
+
async def create_ticket(
|
| 84 |
+
payload: TicketCreate,
|
| 85 |
+
current_user: User,
|
| 86 |
+
db: AsyncSession,
|
| 87 |
+
arq_pool: Any
|
| 88 |
+
) -> Dict[str, Any]:
|
| 89 |
+
"""Business logic for creating a ticket."""
|
| 90 |
+
if payload.project_id:
|
| 91 |
+
stmt = select(Project).where(
|
| 92 |
+
Project.id == payload.project_id,
|
| 93 |
+
Project.workspace_id == current_user.workspace_id,
|
| 94 |
+
Project.deleted_at.is_(None)
|
| 95 |
+
)
|
| 96 |
+
if not (await db.execute(stmt)).scalar_one_or_none():
|
| 97 |
+
raise HTTPException(status_code=400, detail="Project not found")
|
| 98 |
+
|
| 99 |
+
# Deduplication
|
| 100 |
+
payload_str = f"{payload.title.strip()}|{payload.description.strip()}"
|
| 101 |
+
c_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest()
|
| 102 |
+
|
| 103 |
+
dup_stmt = select(Ticket).options(joinedload(Ticket.creator), joinedload(Ticket.assignee)).where(
|
| 104 |
+
Ticket.workspace_id == current_user.workspace_id,
|
| 105 |
+
Ticket.content_hash == c_hash,
|
| 106 |
+
Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
|
| 107 |
+
Ticket.deleted_at.is_(None)
|
| 108 |
+
).limit(1)
|
| 109 |
+
existing_dup = (await db.execute(dup_stmt)).scalar_one_or_none()
|
| 110 |
+
if existing_dup:
|
| 111 |
+
return await TicketService.sanitize_ticket_response(existing_dup, current_user, db)
|
| 112 |
+
|
| 113 |
+
# SLA Calculation
|
| 114 |
+
sla_deadline = payload.sla_deadline
|
| 115 |
+
if not sla_deadline:
|
| 116 |
+
rule_stmt = select(EscalationRule).where(
|
| 117 |
+
EscalationRule.workspace_id == current_user.workspace_id,
|
| 118 |
+
EscalationRule.priority_level == cast(payload.priority or TicketPriority.P2, String)
|
| 119 |
+
)
|
| 120 |
+
rule = (await db.execute(rule_stmt)).scalar_one_or_none()
|
| 121 |
+
sla_deadline = datetime.utcnow() + timedelta(minutes=rule.threshold_minutes if rule else 2880)
|
| 122 |
+
|
| 123 |
+
new_ticket = Ticket(
|
| 124 |
+
id=uuid.uuid4(),
|
| 125 |
+
workspace_id=current_user.workspace_id,
|
| 126 |
+
project_id=payload.project_id,
|
| 127 |
+
title=payload.title,
|
| 128 |
+
description=payload.description,
|
| 129 |
+
priority=payload.priority or TicketPriority.P2,
|
| 130 |
+
category=payload.category,
|
| 131 |
+
created_by=current_user.id,
|
| 132 |
+
status=TicketStatus.OPEN,
|
| 133 |
+
sla_deadline=sla_deadline,
|
| 134 |
+
content_hash=c_hash
|
| 135 |
+
)
|
| 136 |
+
db.add(new_ticket)
|
| 137 |
+
|
| 138 |
+
if payload.attachment_ids:
|
| 139 |
+
await db.execute(update(Attachment).where(Attachment.id.in_(payload.attachment_ids)).values(ticket_id=new_ticket.id))
|
| 140 |
+
|
| 141 |
+
db.add(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(mode='json')))
|
| 142 |
+
await db.commit()
|
| 143 |
+
|
| 144 |
+
# Refresh and Triggers
|
| 145 |
+
refetch_stmt = select(Ticket).options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver), joinedload(Ticket.feedback)).where(Ticket.id == new_ticket.id)
|
| 146 |
+
new_ticket = (await db.execute(refetch_stmt)).scalar_one()
|
| 147 |
+
|
| 148 |
+
await enqueue_task(arq_pool, "run_ai_workflow", new_ticket.id, new_ticket.workspace_id)
|
| 149 |
+
await manager.broadcast_to_workspace(current_user.workspace_id, {"event": "ticket_created", "ticket_id": str(new_ticket.id)})
|
| 150 |
+
|
| 151 |
+
await delete_by_pattern(f"tickets:list:{current_user.workspace_id}*")
|
| 152 |
+
await invalidate_workspace_semantic_cache(str(current_user.workspace_id))
|
| 153 |
+
|
| 154 |
+
return await TicketService.sanitize_ticket_response(new_ticket, current_user, db)
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
async def update_ticket(
|
| 158 |
+
ticket_id: UUID,
|
| 159 |
+
payload: TicketUpdate,
|
| 160 |
+
current_user: User,
|
| 161 |
+
db: AsyncSession,
|
| 162 |
+
arq_pool: Any
|
| 163 |
+
) -> Dict[str, Any]:
|
| 164 |
+
"""Business logic for updating a ticket."""
|
| 165 |
+
is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 166 |
+
stmt = select(Ticket).options(joinedload(Ticket.creator), joinedload(Ticket.assignee), joinedload(Ticket.resolver), joinedload(Ticket.feedback)).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 167 |
+
if not is_staff:
|
| 168 |
+
stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id, Ticket.created_by == current_user.id)
|
| 169 |
+
|
| 170 |
+
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 171 |
+
if not ticket:
|
| 172 |
+
raise HTTPException(status_code=404, detail="Ticket not found")
|
| 173 |
+
|
| 174 |
+
update_data = payload.model_dump(exclude_unset=True)
|
| 175 |
+
|
| 176 |
+
if "status" in update_data and update_data["status"] != ticket.status:
|
| 177 |
+
if current_user.role not in [UserRole.SC_LEAD, UserRole.SC_ADMIN] and update_data["status"] not in ALLOWED_TRANSITIONS.get(ticket.status, []):
|
| 178 |
+
raise HTTPException(status_code=400, detail="Invalid status transition")
|
| 179 |
+
if update_data["status"] in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
|
| 180 |
+
ticket.resolved_at = datetime.utcnow()
|
| 181 |
+
ticket.resolved_by = current_user.id
|
| 182 |
+
|
| 183 |
+
for key, value in update_data.items():
|
| 184 |
+
setattr(ticket, key, value)
|
| 185 |
+
|
| 186 |
+
db.add(AuditLog(workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id, action="update", user_id=current_user.id, new_value=update_data))
|
| 187 |
+
await db.commit()
|
| 188 |
+
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
| 189 |
+
await delete_by_pattern(f"tickets:list:{ticket.workspace_id}*")
|
| 190 |
+
|
| 191 |
+
return await TicketService.sanitize_ticket_response(ticket, current_user, db)
|
tasks/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# System tasks package
|
tasks/ai.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI-related background tasks.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import asyncio
|
| 7 |
+
from typing import Any, Dict, Optional
|
| 8 |
+
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
+
from sqlalchemy import select, desc, cast, String, func
|
| 11 |
+
|
| 12 |
+
from core.database import async_session_factory
|
| 13 |
+
from core.logging import get_logger
|
| 14 |
+
from core.config import get_settings
|
| 15 |
+
from core.llm import get_llm, get_text_embeddings, get_image_embeddings
|
| 16 |
+
from core.vision import extract_visual_context, resolve_image
|
| 17 |
+
from core.cache import invalidate_cache
|
| 18 |
+
from core.search import chunk_text
|
| 19 |
+
from core.sync import sync_markdown_images
|
| 20 |
+
from models.ticket import Ticket, TicketStatus
|
| 21 |
+
from models.escalation_rule import EscalationRule
|
| 22 |
+
from models.message import Message
|
| 23 |
+
from models.kb_article import KBArticle
|
| 24 |
+
from models.kb_article_chunk import KBArticleChunk
|
| 25 |
+
from models.nexus_memory import NexusMemory
|
| 26 |
+
from models.attachment import Attachment
|
| 27 |
+
from models.ai_interaction import AIInteraction
|
| 28 |
+
from models.audit_log import AuditLog
|
| 29 |
+
from langchain.schema import HumanMessage, SystemMessage
|
| 30 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 31 |
+
from tasks.system import check_job_latch
|
| 32 |
+
|
| 33 |
+
logger = get_logger(__name__)
|
| 34 |
+
settings = get_settings()
|
| 35 |
+
|
| 36 |
+
def truncate_content(text_content: str, max_chars: int = 15000) -> str:
|
| 37 |
+
if not text_content: return ""
|
| 38 |
+
if len(text_content) <= max_chars: return text_content
|
| 39 |
+
return text_content[:max_chars] + "\n\n... [Content Truncated] ..."
|
| 40 |
+
|
| 41 |
+
async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
| 42 |
+
"""Background task to generate dual summaries."""
|
| 43 |
+
if not await check_job_latch(ctx, ticket_id, "auto_summarize_ticket"): return
|
| 44 |
+
|
| 45 |
+
for attempt in range(1, 4):
|
| 46 |
+
try:
|
| 47 |
+
async with async_session_factory() as db:
|
| 48 |
+
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 49 |
+
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 50 |
+
if not ticket: return
|
| 51 |
+
|
| 52 |
+
msg_stmt = select(Message).where(Message.ticket_id == ticket_id, Message.deleted_at.is_(None)).order_by(Message.created_at.desc()).limit(10)
|
| 53 |
+
messages = list(reversed((await db.execute(msg_stmt)).scalars().all()))
|
| 54 |
+
|
| 55 |
+
is_manual = kwargs.get('manual', False)
|
| 56 |
+
if not is_manual and len(messages) < 5: return
|
| 57 |
+
|
| 58 |
+
public_messages = [m for m in messages if not m.is_internal]
|
| 59 |
+
llm = get_llm(timeout=120, is_heavy_task=True)
|
| 60 |
+
|
| 61 |
+
def format_convo(msg_list):
|
| 62 |
+
return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list])
|
| 63 |
+
|
| 64 |
+
all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=2)
|
| 65 |
+
|
| 66 |
+
cust_prompt = [
|
| 67 |
+
SystemMessage(content="Summarize for a CUSTOMER. Max 3 sentences."),
|
| 68 |
+
HumanMessage(content=[{"type": "text", "text": f"Title: {ticket.title}\nConvo:\n{format_convo(public_messages)}"}])
|
| 69 |
+
]
|
| 70 |
+
intl_prompt = [
|
| 71 |
+
SystemMessage(content="Summarize for an INTERNAL AGENT. Max 4 sentences."),
|
| 72 |
+
HumanMessage(content=[{"type": "text", "text": f"Title: {ticket.title}\nConvo:\n{format_convo(messages)}"}])
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
cust_resp = await llm.ainvoke(cust_prompt)
|
| 76 |
+
intl_resp = await llm.ainvoke(intl_prompt)
|
| 77 |
+
summary_data = {"customer_summary": str(cust_resp.content), "internal_summary": str(intl_resp.content)}
|
| 78 |
+
|
| 79 |
+
meta = dict(ticket.ai_metadata or {})
|
| 80 |
+
meta["summaries"] = summary_data
|
| 81 |
+
ticket.ai_metadata = meta
|
| 82 |
+
db.add(ticket)
|
| 83 |
+
await db.commit()
|
| 84 |
+
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
| 85 |
+
break
|
| 86 |
+
except Exception as e:
|
| 87 |
+
if attempt == 3: logger.error(f"Summarization failed: {e}")
|
| 88 |
+
await asyncio.sleep(attempt * 5)
|
| 89 |
+
|
| 90 |
+
async def crystallize_memory(ctx, user_id: UUID, workspace_id: UUID, thread_id: Optional[UUID], history_str: str, old_summary: str, old_gist: Dict[str, Any], **kwargs):
|
| 91 |
+
"""Hardened AI Distillation Task."""
|
| 92 |
+
from agents.prompts import get_prompt
|
| 93 |
+
for attempt in range(1, 4):
|
| 94 |
+
try:
|
| 95 |
+
llm = get_llm(is_heavy_task=True)
|
| 96 |
+
embedder = get_text_embeddings()
|
| 97 |
+
|
| 98 |
+
prompt = ChatPromptTemplate.from_template(get_prompt("memory_distiller"))
|
| 99 |
+
new_summary_resp = await (prompt | llm).ainvoke({"old_summary": old_summary, "new_history": history_str})
|
| 100 |
+
new_thread_summary = str(new_summary_resp.content).strip()
|
| 101 |
+
|
| 102 |
+
new_gist = old_gist
|
| 103 |
+
try:
|
| 104 |
+
from schemas.ai import UserIdentityGist
|
| 105 |
+
gist_llm = get_llm(is_heavy_task=True).with_structured_output(UserIdentityGist)
|
| 106 |
+
gist_prompt = ChatPromptTemplate.from_template(get_prompt("identity_architect"))
|
| 107 |
+
new_gist_obj = await (gist_prompt | gist_llm).ainvoke({"old_gist": json.dumps(old_gist), "new_history": history_str, "active_scope": ""})
|
| 108 |
+
if new_gist_obj: new_gist = new_gist_obj.model_dump()
|
| 109 |
+
except: pass
|
| 110 |
+
|
| 111 |
+
async with async_session_factory() as db:
|
| 112 |
+
from models.user import User
|
| 113 |
+
from sqlalchemy import update
|
| 114 |
+
|
| 115 |
+
await db.execute(update(User).where(User.id == user_id).values(ai_gist=new_gist))
|
| 116 |
+
|
| 117 |
+
gist_str = f"USER_FACTS: {json.dumps(new_gist)}"
|
| 118 |
+
fact_vec = await embedder.aembed_query(gist_str)
|
| 119 |
+
db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, thread_id=thread_id, content=gist_str, memory_type="fact", embedding=fact_vec))
|
| 120 |
+
|
| 121 |
+
interaction_vec = await embedder.aembed_query(new_thread_summary)
|
| 122 |
+
db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, thread_id=thread_id, content=new_thread_summary, memory_type="interaction", embedding=interaction_vec))
|
| 123 |
+
|
| 124 |
+
await db.commit()
|
| 125 |
+
break
|
| 126 |
+
except Exception as e:
|
| 127 |
+
if attempt == 3: logger.error(f"Crystallization failed: {e}")
|
| 128 |
+
await asyncio.sleep(attempt * 7)
|
| 129 |
+
|
| 130 |
+
async def index_kb_article(ctx, article_id: UUID, **kwargs):
|
| 131 |
+
"""Full KB indexing lifecycle."""
|
| 132 |
+
if not await check_job_latch(ctx, article_id, "index_kb_article"): return
|
| 133 |
+
|
| 134 |
+
async with async_session_factory() as db:
|
| 135 |
+
try:
|
| 136 |
+
stmt = select(KBArticle).where(KBArticle.id == article_id, KBArticle.deleted_at.is_(None))
|
| 137 |
+
article = (await db.execute(stmt)).scalar_one_or_none()
|
| 138 |
+
if not article: return
|
| 139 |
+
|
| 140 |
+
text_model = get_text_embeddings()
|
| 141 |
+
llm = get_llm()
|
| 142 |
+
|
| 143 |
+
# Fast-path dedup
|
| 144 |
+
if not article.content_hash:
|
| 145 |
+
import hashlib
|
| 146 |
+
payload_str = f"{(article.title or '').strip()}|{(article.content or '').strip()}"
|
| 147 |
+
article.content_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest()
|
| 148 |
+
|
| 149 |
+
dup_stmt = select(KBArticle.id).where(KBArticle.workspace_id == article.workspace_id, KBArticle.content_hash == article.content_hash, KBArticle.id != article.id, KBArticle.deleted_at.is_(None)).limit(1)
|
| 150 |
+
fast_dup = (await db.execute(dup_stmt)).scalar()
|
| 151 |
+
if fast_dup:
|
| 152 |
+
article.duplicate_of_id = fast_dup
|
| 153 |
+
article.is_published = False
|
| 154 |
+
await db.commit()
|
| 155 |
+
return
|
| 156 |
+
|
| 157 |
+
# Sync Images
|
| 158 |
+
await sync_markdown_images(db, article.id, article.workspace_id, article.content, entity_type="article", uploader_id=article.author_id)
|
| 159 |
+
|
| 160 |
+
# Embedding
|
| 161 |
+
text_to_embed = truncate_content(f"{article.title} {article.content}", 8000)
|
| 162 |
+
article.embedding = await text_model.aembed_query(text_to_embed)
|
| 163 |
+
|
| 164 |
+
# Chunking
|
| 165 |
+
raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=200)
|
| 166 |
+
for i, text_content in enumerate(raw_chunks):
|
| 167 |
+
chunk_vec = await text_model.aembed_query(f"{article.title}: {text_content}")
|
| 168 |
+
db.add(KBArticleChunk(article_id=article.id, content=text_content, chunk_index=i, embedding=chunk_vec))
|
| 169 |
+
|
| 170 |
+
# Summarization
|
| 171 |
+
resp = await llm.ainvoke([
|
| 172 |
+
SystemMessage(content="Summarize this technical article in 2-3 sentences."),
|
| 173 |
+
HumanMessage(content=truncate_content(article.content, 12000))
|
| 174 |
+
])
|
| 175 |
+
article.summary = str(resp.content)
|
| 176 |
+
|
| 177 |
+
await db.commit()
|
| 178 |
+
except Exception as e:
|
| 179 |
+
await db.rollback()
|
| 180 |
+
logger.error(f"KB indexing failed for {article_id}: {e}")
|
| 181 |
+
|
| 182 |
+
async def generate_ticket_embedding(ctx, ticket_id: UUID, **kwargs):
|
| 183 |
+
"""Generate vector embeddings for a ticket."""
|
| 184 |
+
async with async_session_factory() as db:
|
| 185 |
+
stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
|
| 186 |
+
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 187 |
+
if not ticket: return
|
| 188 |
+
|
| 189 |
+
try:
|
| 190 |
+
await sync_markdown_images(db, ticket.id, ticket.workspace_id, ticket.description, entity_type="ticket", uploader_id=ticket.created_by)
|
| 191 |
+
|
| 192 |
+
text_model = get_text_embeddings()
|
| 193 |
+
vector = await text_model.aembed_query(f"{ticket.title}\n\n{ticket.description}")
|
| 194 |
+
ticket.embedding = vector
|
| 195 |
+
|
| 196 |
+
# Duplicate Check
|
| 197 |
+
dup_stmt = (
|
| 198 |
+
select(Ticket, (1 - Ticket.embedding.cosine_distance(vector)).label("sim_score"))
|
| 199 |
+
.where(Ticket.workspace_id == ticket.workspace_id, Ticket.id != ticket.id, Ticket.deleted_at.is_(None), Ticket.embedding.isnot(None))
|
| 200 |
+
.order_by(desc("sim_score")).limit(1)
|
| 201 |
+
)
|
| 202 |
+
match = (await db.execute(dup_stmt)).first()
|
| 203 |
+
if match and match.sim_score >= 0.7:
|
| 204 |
+
ticket.duplicate_of_id = match.Ticket.id
|
| 205 |
+
ticket.status = TicketStatus.CLOSED
|
| 206 |
+
ticket.resolution_text = f"Automated Detection: Duplicate of #{str(match.Ticket.id)[:8]}."
|
| 207 |
+
|
| 208 |
+
await db.commit()
|
| 209 |
+
except Exception as e:
|
| 210 |
+
logger.error(f"Ticket embedding failed: {e}")
|
| 211 |
+
|
| 212 |
+
async def vectorize_nexus_interaction(ctx, workspace_id: UUID, user_id: UUID, content: str, interaction_id: Optional[UUID] = None, thread_id: Optional[UUID] = None, memory_type: str = "interaction", **kwargs):
|
| 213 |
+
"""Embed and store an interaction for long-term memory."""
|
| 214 |
+
async with async_session_factory() as db:
|
| 215 |
+
text_model = get_text_embeddings()
|
| 216 |
+
vector = await text_model.aembed_query(content)
|
| 217 |
+
db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, content=content, thread_id=thread_id, interaction_id=interaction_id, memory_type=memory_type, embedding=vector))
|
| 218 |
+
await db.commit()
|
| 219 |
+
if thread_id: await invalidate_cache(f"nexus:thread:{thread_id}:masked")
|
| 220 |
+
|
| 221 |
+
async def generate_global_insight(ctx, *args, **kwargs):
|
| 222 |
+
"""Generate platform-wide strategic summary."""
|
| 223 |
+
from tasks.system import check_cron_lock
|
| 224 |
+
if not await check_cron_lock(ctx, "generate_global_insight", window_seconds=600): return
|
| 225 |
+
|
| 226 |
+
from models.platform_insight import PlatformInsight
|
| 227 |
+
async with async_session_factory() as db:
|
| 228 |
+
stmt = select(NexusMemory.content).where(NexusMemory.memory_type == "interaction").order_by(desc(NexusMemory.created_at)).limit(150)
|
| 229 |
+
memories = (await db.execute(stmt)).scalars().all()
|
| 230 |
+
if not memories: return
|
| 231 |
+
|
| 232 |
+
llm = get_llm()
|
| 233 |
+
resp = await llm.ainvoke(f"Analyze these interactions and provide a JSON summary and trends: {' '.join(memories)}")
|
| 234 |
+
try:
|
| 235 |
+
insights = json.loads(str(resp.content).strip().replace("```json", "").replace("```", ""))
|
| 236 |
+
db.add(PlatformInsight(summary=insights.get("summary"), trends=insights.get("trends")))
|
| 237 |
+
await db.commit()
|
| 238 |
+
except: pass
|
| 239 |
+
|
| 240 |
+
async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
|
| 241 |
+
"""Generate background AI insights for a workspace."""
|
| 242 |
+
from api.v1.dashboard import get_dashboard_stats
|
| 243 |
+
from core.cache import set_cached_search
|
| 244 |
+
from models.user import User, UserRole
|
| 245 |
+
|
| 246 |
+
async with async_session_factory() as db:
|
| 247 |
+
try:
|
| 248 |
+
user_stmt = select(User).where(or_(User.global_role == UserRole.SUPERADMIN, User._legacy_role == UserRole.SC_ADMIN), User.is_active).limit(1)
|
| 249 |
+
system_user = (await db.execute(user_stmt)).scalar_one_or_none()
|
| 250 |
+
if not system_user: return
|
| 251 |
+
|
| 252 |
+
stats = await get_dashboard_stats(workspace_id, current_user=system_user, db=db)
|
| 253 |
+
|
| 254 |
+
llm = get_llm(timeout=120)
|
| 255 |
+
prompt = f"Analyze workspace data and provide JSON summary, actions, and metric_insights: {json.dumps(stats)}"
|
| 256 |
+
resp = await llm.ainvoke(prompt)
|
| 257 |
+
insights = json.loads(str(resp.content).strip().replace("```json", "").replace("```", ""))
|
| 258 |
+
|
| 259 |
+
await set_cached_search(f"dashboard:insights:{workspace_id}:system", insights, ttl=1800)
|
| 260 |
+
except Exception as e:
|
| 261 |
+
logger.error(f"Workspace insights failed: {e}")
|
| 262 |
+
|
| 263 |
+
async def process_kb_import_task(ctx, workspace_id: UUID, author_id: UUID, file_content: str, original_filename: str, **kwargs):
|
| 264 |
+
"""Convert raw text into a structured KB Article."""
|
| 265 |
+
from tasks.system import enqueue_task
|
| 266 |
+
llm = get_llm(timeout=180)
|
| 267 |
+
resp = await llm.ainvoke(f"Convert this to Markdown: {file_content}")
|
| 268 |
+
ai_content = str(resp.content).strip()
|
| 269 |
+
|
| 270 |
+
async with async_session_factory() as db:
|
| 271 |
+
new_article = KBArticle(workspace_id=workspace_id, author_id=author_id, title=f"Import: {original_filename}", content=ai_content, category="General", is_published=False)
|
| 272 |
+
db.add(new_article)
|
| 273 |
+
await db.commit()
|
| 274 |
+
await enqueue_task("index_kb_article", new_article.id)
|
| 275 |
+
|
| 276 |
+
async def ai_dynamic_nudge_pulse(ctx, **kwargs):
|
| 277 |
+
"""Identifies tickets at >75% SLA and posts resolution advice."""
|
| 278 |
+
async with async_session_factory() as db:
|
| 279 |
+
now = datetime.utcnow()
|
| 280 |
+
stmt = (
|
| 281 |
+
select(Ticket, EscalationRule)
|
| 282 |
+
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
|
| 283 |
+
.where(Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]), Ticket.deleted_at.is_(None))
|
| 284 |
+
)
|
| 285 |
+
candidates = (await db.execute(stmt)).all()
|
| 286 |
+
|
| 287 |
+
for ticket, rule in candidates:
|
| 288 |
+
age_mins = (now - ticket.created_at.replace(tzinfo=None)).total_seconds() / 60
|
| 289 |
+
if age_mins >= (rule.threshold_minutes * 0.75) and age_mins < rule.threshold_minutes:
|
| 290 |
+
if (ticket.ai_metadata or {}).get("last_nudge_at"): continue
|
| 291 |
+
|
| 292 |
+
llm = get_llm()
|
| 293 |
+
resp = await llm.ainvoke(f"Provide a nudge for ticket: {ticket.title}")
|
| 294 |
+
db.add(Message(workspace_id=ticket.workspace_id, ticket_id=ticket.id, sender_id=UUID("00000000-0000-0000-0000-000000000000"), content=f"🤖 **AI Nudge**: {resp.content}", is_internal=True))
|
| 295 |
+
|
| 296 |
+
meta = dict(ticket.ai_metadata or {})
|
| 297 |
+
meta["last_nudge_at"] = now.isoformat()
|
| 298 |
+
ticket.ai_metadata = meta
|
| 299 |
+
db.add(ticket)
|
| 300 |
+
await db.commit()
|
tasks/analytics.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Analytics and personnel-related background tasks.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from uuid import UUID
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
from sqlalchemy import select, func
|
| 8 |
+
|
| 9 |
+
from core.database import async_session_factory
|
| 10 |
+
from core.logging import get_logger
|
| 11 |
+
from core.llm import get_llm
|
| 12 |
+
from models.user import User, UserRole
|
| 13 |
+
from models.user_workspace import UserWorkspace
|
| 14 |
+
from models.ticket import Ticket
|
| 15 |
+
from models.message import Message
|
| 16 |
+
from tasks.system import check_cron_lock
|
| 17 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 18 |
+
|
| 19 |
+
logger = get_logger(__name__)
|
| 20 |
+
|
| 21 |
+
async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs):
|
| 22 |
+
"""Analyze a resolved ticket and harvest skills for the agent."""
|
| 23 |
+
from agents.staff_profiler import harvest_agent_skills
|
| 24 |
+
async with async_session_factory() as db:
|
| 25 |
+
try:
|
| 26 |
+
stmt = select(Ticket).where(Ticket.id == ticket_id)
|
| 27 |
+
ticket = (await db.execute(stmt)).scalar_one_or_none()
|
| 28 |
+
if not ticket or not ticket.assigned_to: return
|
| 29 |
+
|
| 30 |
+
msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc())
|
| 31 |
+
msgs = (await db.execute(msg_stmt)).scalars().all()
|
| 32 |
+
|
| 33 |
+
agent_stmt = select(User).where(User.id == ticket.assigned_to)
|
| 34 |
+
agent = (await db.execute(agent_stmt)).scalar_one_or_none()
|
| 35 |
+
if not agent: return
|
| 36 |
+
|
| 37 |
+
await harvest_agent_skills(db, ticket, msgs, agent)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Expertise Harvesting failed: {e}")
|
| 40 |
+
|
| 41 |
+
async def generate_nightly_personnel_analytics(ctx, **kwargs):
|
| 42 |
+
"""Gathers user activity metrics and generates an AI narrative."""
|
| 43 |
+
if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"): return
|
| 44 |
+
|
| 45 |
+
async with async_session_factory() as db:
|
| 46 |
+
stmt = select(UserWorkspace).where(UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), UserWorkspace.is_active == True)
|
| 47 |
+
memberships = (await db.execute(stmt)).scalars().all()
|
| 48 |
+
|
| 49 |
+
now = datetime.utcnow()
|
| 50 |
+
last_7d = now - timedelta(days=7)
|
| 51 |
+
|
| 52 |
+
for uw in memberships:
|
| 53 |
+
try:
|
| 54 |
+
# Basic metrics
|
| 55 |
+
res_count = (await db.execute(select(func.count(Ticket.id)).where(Ticket.resolved_by == uw.user_id, Ticket.resolved_at >= last_7d))).scalar() or 0
|
| 56 |
+
|
| 57 |
+
llm = get_llm(timeout=30)
|
| 58 |
+
prompt = ChatPromptTemplate.from_template("Generate performance narrative for staff member with {res} resolutions.")
|
| 59 |
+
narrative_res = await (prompt | llm).ainvoke({"res": res_count})
|
| 60 |
+
|
| 61 |
+
uw.ai_narrative = narrative_res.content.strip()
|
| 62 |
+
uw.activity_summary = {"resolved_7d": res_count, "last_calculated": now.isoformat()}
|
| 63 |
+
db.add(uw)
|
| 64 |
+
except Exception: continue
|
| 65 |
+
await db.commit()
|
tasks/notifications.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Notification background tasks.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from uuid import UUID
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from sqlalchemy import select
|
| 9 |
+
|
| 10 |
+
from core.database import async_session_factory
|
| 11 |
+
from core.logging import get_logger
|
| 12 |
+
from core.config import get_settings
|
| 13 |
+
from core.email import send_email, template_nexus_email
|
| 14 |
+
from core.websockets import manager
|
| 15 |
+
from models.notification import Notification
|
| 16 |
+
from models.user import User
|
| 17 |
+
|
| 18 |
+
logger = get_logger(__name__)
|
| 19 |
+
settings = get_settings()
|
| 20 |
+
|
| 21 |
+
async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None, **kwargs):
|
| 22 |
+
"""Send notification to DB, real-time WebSocket, and simulated Email."""
|
| 23 |
+
async with async_session_factory() as db:
|
| 24 |
+
user_stmt = select(User.email, User.real_email).where(User.id == user_id)
|
| 25 |
+
u_res = (await db.execute(user_stmt)).first()
|
| 26 |
+
|
| 27 |
+
primary_email, real_email = u_res if u_res else (None, None)
|
| 28 |
+
delivery_target = real_email or primary_email
|
| 29 |
+
|
| 30 |
+
notification = Notification(
|
| 31 |
+
workspace_id=workspace_id,
|
| 32 |
+
user_id=user_id,
|
| 33 |
+
title=title,
|
| 34 |
+
message=message,
|
| 35 |
+
link=link
|
| 36 |
+
)
|
| 37 |
+
db.add(notification)
|
| 38 |
+
await db.commit()
|
| 39 |
+
|
| 40 |
+
await manager.send_to_user(user_id, {
|
| 41 |
+
"type": "notification",
|
| 42 |
+
"id": str(notification.id),
|
| 43 |
+
"title": title,
|
| 44 |
+
"message": message,
|
| 45 |
+
"link": link,
|
| 46 |
+
"created_at": datetime.utcnow().isoformat()
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
if delivery_target:
|
| 50 |
+
resource_url = None
|
| 51 |
+
if link:
|
| 52 |
+
if link.startswith('http'):
|
| 53 |
+
resource_url = link
|
| 54 |
+
else:
|
| 55 |
+
resource_url = f"{settings.effective_frontend_url}/{link.lstrip('/')}"
|
| 56 |
+
|
| 57 |
+
email_html = template_nexus_email(
|
| 58 |
+
title=title,
|
| 59 |
+
message=message,
|
| 60 |
+
action_link=resource_url,
|
| 61 |
+
action_label="View Details",
|
| 62 |
+
footer_note=f"Workspace: {workspace_id} | Security Alert level: High"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
email_text = f"Hello,\n\n{message}\n\nAccess it here: {resource_url if resource_url else 'N/A'}"
|
| 66 |
+
await send_email(delivery_target, title, email_text, html_body=email_html)
|
| 67 |
+
|
| 68 |
+
if settings.NOTIFICATION_WEBHOOK_URL:
|
| 69 |
+
try:
|
| 70 |
+
import httpx
|
| 71 |
+
async with httpx.AsyncClient() as client:
|
| 72 |
+
payload = {
|
| 73 |
+
"content" if "discord" in settings.NOTIFICATION_WEBHOOK_URL.lower() else "text":
|
| 74 |
+
f"🔔 *{title}*\n{message}\n{link if link else ''}"
|
| 75 |
+
}
|
| 76 |
+
await client.post(settings.NOTIFICATION_WEBHOOK_URL, json=payload, timeout=5.0)
|
| 77 |
+
except Exception as w_err:
|
| 78 |
+
logger.error(f"Failed to push external webhook: {w_err}")
|
| 79 |
+
|
| 80 |
+
async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None, **kwargs):
|
| 81 |
+
"""
|
| 82 |
+
Background task to notify multiple users about a mention.
|
| 83 |
+
"""
|
| 84 |
+
link = f"/dashboard?ticket={ticket_id}" if ticket_id else None
|
| 85 |
+
for mention in mentions:
|
| 86 |
+
user_id = UUID(mention["user_id"]) if isinstance(mention["user_id"], str) else mention["user_id"]
|
| 87 |
+
await send_triple_notification(
|
| 88 |
+
ctx,
|
| 89 |
+
user_id=user_id,
|
| 90 |
+
workspace_id=workspace_id,
|
| 91 |
+
title=title,
|
| 92 |
+
message=f"You were mentioned: {title}",
|
| 93 |
+
link=link
|
| 94 |
+
)
|
tasks/remediation.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Remediation background tasks.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import httpx
|
| 7 |
+
from uuid import UUID
|
| 8 |
+
from sqlalchemy import select
|
| 9 |
+
|
| 10 |
+
from core.database import async_session_factory
|
| 11 |
+
from core.logging import get_logger
|
| 12 |
+
from core.cache import invalidate_cache
|
| 13 |
+
from models.ticket import Ticket, TicketStatus
|
| 14 |
+
from models.remediation import RemediationHook, RemediationActionType
|
| 15 |
+
|
| 16 |
+
logger = get_logger(__name__)
|
| 17 |
+
|
| 18 |
+
async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str, **kwargs):
|
| 19 |
+
"""Execute a specific remediation action safely in the background."""
|
| 20 |
+
async with async_session_factory() as db:
|
| 21 |
+
ticket_stmt = select(Ticket).where(Ticket.id == UUID(ticket_id), Ticket.deleted_at.is_(None))
|
| 22 |
+
hook_stmt = select(RemediationHook).where(RemediationHook.id == UUID(hook_id))
|
| 23 |
+
|
| 24 |
+
ticket = (await db.execute(ticket_stmt)).scalar_one_or_none()
|
| 25 |
+
hook = (await db.execute(hook_stmt)).scalar_one_or_none()
|
| 26 |
+
|
| 27 |
+
if not ticket or not hook: return
|
| 28 |
+
|
| 29 |
+
if hook.action_type == RemediationActionType.WEBHOOK:
|
| 30 |
+
async with httpx.AsyncClient() as client:
|
| 31 |
+
try:
|
| 32 |
+
payload_str = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id))
|
| 33 |
+
payload = json.loads(payload_str)
|
| 34 |
+
resp = await client.post(hook.target, json=payload, timeout=10.0)
|
| 35 |
+
if resp.status_code >= 400: return
|
| 36 |
+
except Exception: return
|
| 37 |
+
|
| 38 |
+
ticket.status = TicketStatus.RESOLVED
|
| 39 |
+
db.add(ticket)
|
| 40 |
+
await db.commit()
|
| 41 |
+
await invalidate_cache(f"ticket:detail:{ticket_id}")
|
tasks/system.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
System and utility background tasks.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
import asyncio
|
| 7 |
+
from typing import Any, Dict, Optional
|
| 8 |
+
from uuid import UUID
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
+
from sqlalchemy import select, func, text, cast, String
|
| 11 |
+
|
| 12 |
+
from core.database import async_session_factory
|
| 13 |
+
from core.logging import get_logger
|
| 14 |
+
from core.config import get_settings, get_redis_settings
|
| 15 |
+
from core.cache import get_worker_redis_client
|
| 16 |
+
from models.worker_job import WorkerJob, JobStatus
|
| 17 |
+
from models.meta_infra_health import MetaInfraHealth, ServiceStatus
|
| 18 |
+
from models.ticket import Ticket, TicketStatus
|
| 19 |
+
from models.escalation_rule import EscalationRule
|
| 20 |
+
from models.audit_log import AuditLog
|
| 21 |
+
|
| 22 |
+
logger = get_logger(__name__)
|
| 23 |
+
settings = get_settings()
|
| 24 |
+
_redis_pool = None
|
| 25 |
+
|
| 26 |
+
async def get_task_pool():
|
| 27 |
+
global _redis_pool
|
| 28 |
+
if _redis_pool is None:
|
| 29 |
+
from arq import create_pool
|
| 30 |
+
_redis_pool = await create_pool(get_redis_settings())
|
| 31 |
+
return _redis_pool
|
| 32 |
+
|
| 33 |
+
async def check_cron_lock(ctx, task_name: str, window_seconds: int = 60) -> bool:
|
| 34 |
+
"""
|
| 35 |
+
Prevent cross-replica cron duplication using the shared Postgres database.
|
| 36 |
+
"""
|
| 37 |
+
from agents.utils import get_deterministic_uuid
|
| 38 |
+
|
| 39 |
+
job_id_raw = ctx.get('job_id')
|
| 40 |
+
if not job_id_raw:
|
| 41 |
+
return True
|
| 42 |
+
|
| 43 |
+
job_id = get_deterministic_uuid(job_id_raw)
|
| 44 |
+
|
| 45 |
+
async with async_session_factory() as db:
|
| 46 |
+
try:
|
| 47 |
+
limit = datetime.utcnow() - timedelta(seconds=window_seconds)
|
| 48 |
+
stmt = select(WorkerJob).where(
|
| 49 |
+
WorkerJob.id == job_id,
|
| 50 |
+
WorkerJob.status == JobStatus.SUCCESS
|
| 51 |
+
)
|
| 52 |
+
res = await db.execute(stmt)
|
| 53 |
+
if res.scalar_one_or_none():
|
| 54 |
+
logger.info(f"⏭️ Skipping {task_name}: Already successfully completed.")
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
stmt = select(WorkerJob).where(
|
| 58 |
+
WorkerJob.id == job_id,
|
| 59 |
+
WorkerJob.status == JobStatus.RUNNING,
|
| 60 |
+
WorkerJob.started_at > limit
|
| 61 |
+
)
|
| 62 |
+
res = await db.execute(stmt)
|
| 63 |
+
if res.scalar_one_or_none():
|
| 64 |
+
logger.info(f"⏭️ Skipping {task_name}: Already running on another replica.")
|
| 65 |
+
return False
|
| 66 |
+
|
| 67 |
+
return True
|
| 68 |
+
except Exception as e:
|
| 69 |
+
logger.warning(f"Cron lock check failed for {task_name}: {e}")
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
async def check_job_latch(ctx, entity_id: Any, task_type: str) -> bool:
|
| 73 |
+
"""
|
| 74 |
+
Implements Latest-Only Job Deduplication.
|
| 75 |
+
"""
|
| 76 |
+
try:
|
| 77 |
+
redis = get_worker_redis_client()
|
| 78 |
+
job_kwargs = ctx.get('job_kwargs', {})
|
| 79 |
+
enqueue_time = job_kwargs.get('enqueue_time_ms')
|
| 80 |
+
|
| 81 |
+
if not enqueue_time:
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
latch_key = f"job_latch:{task_type}:{str(entity_id)}"
|
| 85 |
+
latest_time_str = await redis.get(latch_key)
|
| 86 |
+
if latest_time_str:
|
| 87 |
+
latest_time = int(latest_time_str)
|
| 88 |
+
if enqueue_time < latest_time:
|
| 89 |
+
logger.info(f"⏭️ Skipping stale job {ctx.get('job_id')} for {task_type}:{entity_id}")
|
| 90 |
+
return False
|
| 91 |
+
|
| 92 |
+
return True
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.warning(f"Job latch check failed: {e}")
|
| 95 |
+
return True
|
| 96 |
+
|
| 97 |
+
async def enqueue_task(task_or_pool: Any, *args, **kwargs):
|
| 98 |
+
"""
|
| 99 |
+
Enqueues an ARQ job and updates the deduplication latch in Redis.
|
| 100 |
+
"""
|
| 101 |
+
try:
|
| 102 |
+
pool_obj = await get_task_pool()
|
| 103 |
+
|
| 104 |
+
if isinstance(task_or_pool, str):
|
| 105 |
+
task_name = task_or_pool
|
| 106 |
+
target_pool = pool_obj
|
| 107 |
+
final_args = args
|
| 108 |
+
else:
|
| 109 |
+
target_pool = task_or_pool
|
| 110 |
+
if not args:
|
| 111 |
+
raise ValueError("enqueue_task(pool, ...) requires a task_name string.")
|
| 112 |
+
task_name = args[0]
|
| 113 |
+
final_args = args[1:]
|
| 114 |
+
|
| 115 |
+
entity_id = final_args[0] if final_args else "none"
|
| 116 |
+
|
| 117 |
+
HEAVY_TASKS = [
|
| 118 |
+
"generate_ticket_embedding", "run_ai_workflow", "auto_summarize_ticket",
|
| 119 |
+
"index_kb_article", "vectorize_nexus_interaction", "generate_global_insight",
|
| 120 |
+
"crystallize_memory", "generate_workspace_insights", "harvest_expertise_task",
|
| 121 |
+
"process_kb_import_task"
|
| 122 |
+
]
|
| 123 |
+
queue_name = "arq:heavy" if task_name in HEAVY_TASKS else "arq:regular"
|
| 124 |
+
|
| 125 |
+
now_ms = int(time.time() * 1000)
|
| 126 |
+
latch_key = f"job_latch:{task_name}:{str(entity_id)}"
|
| 127 |
+
redis = get_worker_redis_client()
|
| 128 |
+
await redis.set(latch_key, now_ms, ex=86400)
|
| 129 |
+
|
| 130 |
+
task_kwargs = kwargs.copy()
|
| 131 |
+
task_kwargs['enqueue_time_ms'] = now_ms
|
| 132 |
+
task_kwargs['metadata_json'] = {
|
| 133 |
+
"entity_id": str(entity_id),
|
| 134 |
+
"task_group": queue_name.split(':')[-1],
|
| 135 |
+
"enqueued_at": datetime.utcnow().isoformat(),
|
| 136 |
+
"latch_key_override": task_name
|
| 137 |
+
}
|
| 138 |
+
if "thread_id" in task_kwargs:
|
| 139 |
+
task_kwargs['metadata_json']["thread_id"] = str(task_kwargs["thread_id"])
|
| 140 |
+
|
| 141 |
+
await target_pool.enqueue_job(task_name, *final_args, _queue_name=queue_name, **task_kwargs)
|
| 142 |
+
logger.info(f"📤 Enqueued {task_name} to {queue_name} for {entity_id}")
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.error(f"Failed to enqueue task: {e}")
|
| 146 |
+
|
| 147 |
+
async def record_workflow_step_task(
|
| 148 |
+
ctx: Any,
|
| 149 |
+
entity_id: str,
|
| 150 |
+
workspace_id: str,
|
| 151 |
+
workflow_type: str,
|
| 152 |
+
step_name: str,
|
| 153 |
+
input_data: Optional[Dict] = None,
|
| 154 |
+
output_data: Optional[Dict] = None,
|
| 155 |
+
current_stage: Optional[str] = None,
|
| 156 |
+
duration_ms: Optional[float] = None,
|
| 157 |
+
**kwargs
|
| 158 |
+
):
|
| 159 |
+
"""Background task to record a workflow lifecycle step."""
|
| 160 |
+
try:
|
| 161 |
+
async with async_session_factory() as db:
|
| 162 |
+
from core.observability import record_workflow_step
|
| 163 |
+
await record_workflow_step(
|
| 164 |
+
db,
|
| 165 |
+
entity_id=UUID(entity_id),
|
| 166 |
+
workspace_id=UUID(workspace_id),
|
| 167 |
+
workflow_type=workflow_type,
|
| 168 |
+
step_name=step_name,
|
| 169 |
+
input_data=input_data,
|
| 170 |
+
output_data=output_data,
|
| 171 |
+
current_stage=current_stage,
|
| 172 |
+
duration_ms=duration_ms or 0.0
|
| 173 |
+
)
|
| 174 |
+
await db.commit()
|
| 175 |
+
except Exception as e:
|
| 176 |
+
logger.warning(f"Failed to record workflow step in background: {e}")
|
| 177 |
+
|
| 178 |
+
async def monitor_sla_thresholds(ctx, *args, **kwargs):
|
| 179 |
+
"""
|
| 180 |
+
Periodic task to check for SLA breaches and apply escalation rules.
|
| 181 |
+
"""
|
| 182 |
+
if not await check_cron_lock(ctx, "monitor_sla_thresholds", window_seconds=120):
|
| 183 |
+
return
|
| 184 |
+
|
| 185 |
+
from core.cache import get_redis_client, invalidate_cache
|
| 186 |
+
from tasks.notifications import send_triple_notification
|
| 187 |
+
|
| 188 |
+
logger.info("Starting SLA monitoring check...")
|
| 189 |
+
async with async_session_factory() as db:
|
| 190 |
+
now = datetime.utcnow()
|
| 191 |
+
stmt = (
|
| 192 |
+
select(Ticket, EscalationRule)
|
| 193 |
+
.join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String)))
|
| 194 |
+
.where(
|
| 195 |
+
Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]),
|
| 196 |
+
Ticket.deleted_at.is_(None),
|
| 197 |
+
Ticket.is_escalated.is_(None),
|
| 198 |
+
EscalationRule.is_active
|
| 199 |
+
)
|
| 200 |
+
.limit(500)
|
| 201 |
+
)
|
| 202 |
+
result = await db.execute(stmt)
|
| 203 |
+
breached_candidates = result.all()
|
| 204 |
+
|
| 205 |
+
manager_cache = {}
|
| 206 |
+
ws_ids = list({t.workspace_id for t, r in breached_candidates})
|
| 207 |
+
|
| 208 |
+
from agents.utils import get_workspace_manager
|
| 209 |
+
manager_lookups = [get_workspace_manager(db, ws_id) for ws_id in ws_ids]
|
| 210 |
+
managers = await asyncio.gather(*manager_lookups)
|
| 211 |
+
for ws_id, mgr in zip(ws_ids, managers):
|
| 212 |
+
manager_cache[ws_id] = mgr
|
| 213 |
+
|
| 214 |
+
notification_tasks = []
|
| 215 |
+
redis = get_redis_client()
|
| 216 |
+
|
| 217 |
+
count = 0
|
| 218 |
+
for ticket, rule in breached_candidates:
|
| 219 |
+
try:
|
| 220 |
+
count += 1
|
| 221 |
+
threshold_time = ticket.created_at.replace(tzinfo=None)
|
| 222 |
+
age_minutes = (now - threshold_time).total_seconds() / 60
|
| 223 |
+
minutes_remaining = rule.threshold_minutes - age_minutes
|
| 224 |
+
|
| 225 |
+
manager_user = manager_cache.get(ticket.workspace_id)
|
| 226 |
+
|
| 227 |
+
if age_minutes >= rule.threshold_minutes:
|
| 228 |
+
if manager_user:
|
| 229 |
+
notification_tasks.append(send_triple_notification(
|
| 230 |
+
ctx, manager_user.id, ticket.workspace_id,
|
| 231 |
+
"🚨 SLA BREACHED: Immediate Intervention Required",
|
| 232 |
+
f"Ticket '{ticket.title}' (Priority: {ticket.priority}) has exceeded its SLA threshold.",
|
| 233 |
+
link=f"/dashboard?ticket={ticket.id}"
|
| 234 |
+
))
|
| 235 |
+
ticket.is_escalated = now
|
| 236 |
+
db.add(ticket)
|
| 237 |
+
await invalidate_cache(f"ticket:detail:{ticket.id}")
|
| 238 |
+
db.add(AuditLog(
|
| 239 |
+
workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
|
| 240 |
+
action="SLA_ESCALATION", user_id=None, new_value={"rule": rule.name}
|
| 241 |
+
))
|
| 242 |
+
|
| 243 |
+
elif 0 <= minutes_remaining <= 120:
|
| 244 |
+
warning_latch = f"notified_sla_pre_breach_2h:{str(ticket.id)}"
|
| 245 |
+
if not await redis.get(warning_latch) and manager_user:
|
| 246 |
+
notification_tasks.append(send_triple_notification(
|
| 247 |
+
ctx, manager_user.id, ticket.workspace_id,
|
| 248 |
+
"⚠️ CRITICAL WARNING: SLA Breach in 2 Hours",
|
| 249 |
+
f"Ticket '{ticket.title}' is approaching its SLA threshold.",
|
| 250 |
+
link=f"/dashboard?ticket={ticket.id}"
|
| 251 |
+
))
|
| 252 |
+
await redis.set(warning_latch, "1", ex=86400)
|
| 253 |
+
db.add(AuditLog(
|
| 254 |
+
workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id,
|
| 255 |
+
action="SLA_PRE_BREACH_WARNING", user_id=None, new_value={"rule": rule.name}
|
| 256 |
+
))
|
| 257 |
+
except Exception as e:
|
| 258 |
+
logger.error(f"SLA Monitor error: {e}")
|
| 259 |
+
|
| 260 |
+
if count % 50 == 0:
|
| 261 |
+
await db.commit()
|
| 262 |
+
if notification_tasks:
|
| 263 |
+
await asyncio.gather(*notification_tasks, return_exceptions=True)
|
| 264 |
+
notification_tasks = []
|
| 265 |
+
|
| 266 |
+
await db.commit()
|
| 267 |
+
if notification_tasks:
|
| 268 |
+
await asyncio.gather(*notification_tasks, return_exceptions=True)
|
| 269 |
+
|
| 270 |
+
async def record_system_heartbeat(ctx, *args, **kwargs):
|
| 271 |
+
"""
|
| 272 |
+
Periodic task to record infrastructure health snapshots.
|
| 273 |
+
"""
|
| 274 |
+
if not await check_cron_lock(ctx, "record_system_heartbeat", window_seconds=120):
|
| 275 |
+
return
|
| 276 |
+
|
| 277 |
+
from arq import create_pool
|
| 278 |
+
import httpx
|
| 279 |
+
|
| 280 |
+
logger.info("Recording system heartbeat...")
|
| 281 |
+
|
| 282 |
+
async with async_session_factory() as db:
|
| 283 |
+
# DB check
|
| 284 |
+
db_start = time.perf_counter()
|
| 285 |
+
db_status = ServiceStatus.DOWN
|
| 286 |
+
db_latency = 0
|
| 287 |
+
try:
|
| 288 |
+
await db.execute(text("SELECT 1"))
|
| 289 |
+
db_status = ServiceStatus.UP
|
| 290 |
+
db_latency = (time.perf_counter() - db_start) * 1000
|
| 291 |
+
except Exception: pass
|
| 292 |
+
db.add(MetaInfraHealth(service_name="DATABASE", status=db_status, latency_ms=db_latency, environment="production"))
|
| 293 |
+
|
| 294 |
+
# Redis check
|
| 295 |
+
redis_start = time.perf_counter()
|
| 296 |
+
redis_status = ServiceStatus.DOWN
|
| 297 |
+
redis_latency = 0
|
| 298 |
+
try:
|
| 299 |
+
pool = ctx.get('redis') or await create_pool(get_redis_settings())
|
| 300 |
+
redis_status = ServiceStatus.UP
|
| 301 |
+
redis_latency = (time.perf_counter() - redis_start) * 1000
|
| 302 |
+
except Exception: pass
|
| 303 |
+
db.add(MetaInfraHealth(service_name="REDIS", status=redis_status, latency_ms=redis_latency, environment="production"))
|
| 304 |
+
|
| 305 |
+
# Ollama check
|
| 306 |
+
ollama_start = time.perf_counter()
|
| 307 |
+
ollama_status = ServiceStatus.DOWN
|
| 308 |
+
ollama_latency = 0
|
| 309 |
+
try:
|
| 310 |
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
| 311 |
+
resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags")
|
| 312 |
+
if resp.status_code == 200:
|
| 313 |
+
ollama_status = ServiceStatus.UP
|
| 314 |
+
ollama_latency = (time.perf_counter() - ollama_start) * 1000
|
| 315 |
+
except Exception: pass
|
| 316 |
+
db.add(MetaInfraHealth(service_name="OLLAMA", status=ollama_status, latency_ms=ollama_latency, environment="production"))
|
| 317 |
+
|
| 318 |
+
await db.commit()
|
| 319 |
+
|
| 320 |
+
async def nexus_pulse_check(ctx, *args, **kwargs):
|
| 321 |
+
"""
|
| 322 |
+
Proactive AI "Pulse" Nudge.
|
| 323 |
+
"""
|
| 324 |
+
if not await check_cron_lock(ctx, "nexus_pulse_check", window_seconds=300):
|
| 325 |
+
return
|
| 326 |
+
|
| 327 |
+
logger.info("Executing Proactive AI Pulse Check...")
|
| 328 |
+
from core.websockets import manager
|
| 329 |
+
|
| 330 |
+
async with async_session_factory() as db:
|
| 331 |
+
fifteen_mins_ago = datetime.utcnow() - timedelta(minutes=15)
|
| 332 |
+
stmt = select(Ticket.workspace_id).where(Ticket.updated_at >= fifteen_mins_ago).distinct()
|
| 333 |
+
workspaces = (await db.execute(stmt)).scalars().all()
|
| 334 |
+
|
| 335 |
+
for w_id in workspaces:
|
| 336 |
+
try:
|
| 337 |
+
sla_breach_count = (await db.execute(
|
| 338 |
+
select(func.count(Ticket.id)).where(
|
| 339 |
+
Ticket.workspace_id == w_id,
|
| 340 |
+
Ticket.priority == "P0",
|
| 341 |
+
Ticket.status != "CLOSED",
|
| 342 |
+
Ticket.updated_at >= fifteen_mins_ago
|
| 343 |
+
)
|
| 344 |
+
)).scalar() or 0
|
| 345 |
+
|
| 346 |
+
if sla_breach_count >= 3:
|
| 347 |
+
alert = {"type": "NEXUS_PULSE_ALERT", "level": "critical", "title": "Anomaly Detected", "message": f"{sla_breach_count} urgent tickets updated."}
|
| 348 |
+
await asyncio.gather(
|
| 349 |
+
manager.broadcast_to_role(w_id, "3sc_admin", alert),
|
| 350 |
+
manager.broadcast_to_role(w_id, "3sc_lead", alert),
|
| 351 |
+
return_exceptions=True
|
| 352 |
+
)
|
| 353 |
+
except Exception: pass
|
| 354 |
+
|
| 355 |
+
async def purge_stale_semantic_cache(ctx, *args, **kwargs):
|
| 356 |
+
"""
|
| 357 |
+
Periodic task to physically delete semantic cache records older than 12 hours.
|
| 358 |
+
"""
|
| 359 |
+
if not await check_cron_lock(ctx, "purge_stale_semantic_cache", window_seconds=600):
|
| 360 |
+
return
|
| 361 |
+
|
| 362 |
+
from models.nexus_semantic_cache import NexusSemanticCache
|
| 363 |
+
from sqlalchemy import delete
|
| 364 |
+
|
| 365 |
+
logger.info("Executing Semantic Cache Purge...")
|
| 366 |
+
async with async_session_factory() as db:
|
| 367 |
+
try:
|
| 368 |
+
stmt = delete(NexusSemanticCache).where(
|
| 369 |
+
NexusSemanticCache.created_at < (func.now() - text("INTERVAL '12 hours'"))
|
| 370 |
+
)
|
| 371 |
+
await db.execute(stmt)
|
| 372 |
+
await db.commit()
|
| 373 |
+
except Exception:
|
| 374 |
+
await db.rollback()
|
| 375 |
+
|
| 376 |
+
async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_role: str, **kwargs):
|
| 377 |
+
"""
|
| 378 |
+
Background worker task to load and mask conversational history for a Nexus thread.
|
| 379 |
+
"""
|
| 380 |
+
from models.nexus_interaction import NexusInteraction
|
| 381 |
+
from agents.security import mask_for_role
|
| 382 |
+
from models.user import User as UserTable
|
| 383 |
+
|
| 384 |
+
logger.info(f"💾 Recovering nexus history for thread {thread_id}...")
|
| 385 |
+
async with async_session_factory() as db:
|
| 386 |
+
stmt = (
|
| 387 |
+
select(NexusInteraction, UserTable.full_name)
|
| 388 |
+
.join(UserTable, NexusInteraction.user_id == UserTable.id)
|
| 389 |
+
.where(
|
| 390 |
+
NexusInteraction.thread_id == thread_id,
|
| 391 |
+
NexusInteraction.workspace_id == workspace_id
|
| 392 |
+
)
|
| 393 |
+
.order_by(NexusInteraction.created_at.asc())
|
| 394 |
+
)
|
| 395 |
+
result = await db.execute(stmt)
|
| 396 |
+
rows = result.all()
|
| 397 |
+
if not rows: return []
|
| 398 |
+
|
| 399 |
+
interaction_dicts = [dict(
|
| 400 |
+
id=i.id,
|
| 401 |
+
input_query=i.input_query,
|
| 402 |
+
ai_answer=i.ai_answer,
|
| 403 |
+
sender_name=full_name,
|
| 404 |
+
created_at=i.created_at.isoformat()
|
| 405 |
+
) for i, full_name in rows]
|
| 406 |
+
|
| 407 |
+
masked = mask_for_role(interaction_dicts, user_role)
|
| 408 |
+
history = []
|
| 409 |
+
for i in masked:
|
| 410 |
+
history.append({"role": "user", "content": i["input_query"], "senderName": i.get("sender_name", "User"), "timestamp": i["created_at"]})
|
| 411 |
+
history.append({"role": "assistant", "content": i["ai_answer"], "senderName": "Nexus", "timestamp": i["created_at"]})
|
| 412 |
+
|
| 413 |
+
return history
|