From f384d5893722fa15438bed5ab002f207b2466515 Mon Sep 17 00:00:00 2001 From: chihlasm Date: Mon, 16 Mar 2026 01:05:07 -0400 Subject: [PATCH] feat: add get_ticket_context() to ConnectWise provider (Task 8) Fetches ticket details, company, contact, configurations, notes, and related open tickets in parallel via asyncio.gather with partial failure tolerance. Results are cached with a 5-minute TTL per ticket/connection. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../app/services/psa/connectwise/provider.py | 251 ++++++++++++++++++ 1 file changed, 251 insertions(+) diff --git a/backend/app/services/psa/connectwise/provider.py b/backend/app/services/psa/connectwise/provider.py index d84ef73b..a4aca59b 100644 --- a/backend/app/services/psa/connectwise/provider.py +++ b/backend/app/services/psa/connectwise/provider.py @@ -1,6 +1,10 @@ """ConnectWise implementation of PSAProvider.""" from __future__ import annotations +import asyncio +import logging +from datetime import datetime, timezone + from app.services.psa.base import PSAProvider from app.services.psa.cache import psa_cache from app.services.psa.types import ( @@ -14,6 +18,8 @@ from app.services.psa.types import ( ) from .client import ConnectWiseClient +logger = logging.getLogger(__name__) + class ConnectWiseProvider(PSAProvider): """ConnectWise PSA provider implementation.""" @@ -263,6 +269,251 @@ class ConnectWiseProvider(PSAProvider): psa_cache.set(cache_key, result, ttl_seconds=900) return result + # ── Ticket Context ──────────────────────────────────────────────── + + async def get_ticket_context( + self, ticket_id: int, connection_id: str | None = None + ): + """Fetch rich ticket context for AI prompt injection. + + Returns a TicketContext with ticket details, company, contact, + configurations, recent notes, and related open tickets. + Results are cached for 5 minutes per ticket. + """ + from app.schemas.psa_context import ( + TicketContext, + TicketDetails, + CompanyInfo, + ContactInfo, + ConfigItem, + TicketNote, + RelatedTicket, + ) + + cache_key = f"{connection_id or 'default'}:ticket_context:{ticket_id}" + cached = psa_cache.get(cache_key) + if cached is not None: + return cached + + # Fetch ticket first to get company_id and contact_id + ticket_data = await self.client.get( + f"/service/tickets/{ticket_id}", + params={ + "fields": "id,summary,status,priority,board,sla,dateEntered,resources,company,contact" + }, + ) + + company_id = ticket_data.get("company", {}).get("id") if ticket_data.get("company") else None + contact_id = ticket_data.get("contact", {}).get("id") if ticket_data.get("contact") else None + + # Build parallel fetch tasks + configs_task = asyncio.create_task( + self.client.get( + f"/service/tickets/{ticket_id}/configurations", + params={ + "fields": "id,deviceIdentifier,type,osType,serialNumber,ipAddress,modelNumber" + }, + ) + ) + notes_task = asyncio.create_task( + self.client.get( + f"/service/tickets/{ticket_id}/notes", + params={ + "pageSize": "20", + "orderBy": "dateCreated desc", + "fields": "id,text,member,dateCreated,internalAnalysisFlag", + }, + ) + ) + company_task = asyncio.create_task( + self.client.get( + f"/company/companies/{company_id}", + params={ + "fields": "id,name,site,addressLine1,city,state,zip,phoneNumber,type,territory" + }, + ) + ) if company_id else None + + related_task = asyncio.create_task( + self.client.get( + "/service/tickets", + params={ + "conditions": f"company/id={company_id} AND closedFlag=false AND id != {ticket_id}", + "pageSize": "5", + "orderBy": "id desc", + "fields": "id,summary,status,priority,board", + }, + ) + ) if company_id else None + + contact_task = asyncio.create_task( + self.client.get( + f"/company/contacts/{contact_id}", + params={ + "fields": "id,firstName,lastName,title,defaultPhoneNbr,communicationItems" + }, + ) + ) if contact_id else None + + # Gather all tasks with partial failure tolerance + tasks_to_await = [t for t in [configs_task, notes_task, company_task, related_task, contact_task] if t is not None] + task_results = await asyncio.gather(*tasks_to_await, return_exceptions=True) + + # Unpack results in order (skipping None tasks) + result_iter = iter(task_results) + configs_raw = next(result_iter) + notes_raw = next(result_iter) + company_raw = next(result_iter) if company_task else None + related_raw = next(result_iter) if related_task else None + contact_raw = next(result_iter) if contact_task else None + + # Map ticket details + def _parse_dt(val: str | None) -> datetime: + if not val: + return datetime.now(timezone.utc) + try: + # CW returns ISO 8601 strings — ensure timezone aware + dt = datetime.fromisoformat(val.replace("Z", "+00:00")) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt + except (ValueError, AttributeError): + return datetime.now(timezone.utc) + + ticket_details = TicketDetails( + id=ticket_data["id"], + summary=ticket_data.get("summary", ""), + status=ticket_data.get("status", {}).get("name", "") if isinstance(ticket_data.get("status"), dict) else str(ticket_data.get("status", "")), + priority=ticket_data.get("priority", {}).get("name", "") if isinstance(ticket_data.get("priority"), dict) else str(ticket_data.get("priority", "")), + board=ticket_data.get("board", {}).get("name", "") if isinstance(ticket_data.get("board"), dict) else str(ticket_data.get("board", "")), + sla=ticket_data.get("sla", {}).get("name") if isinstance(ticket_data.get("sla"), dict) else ticket_data.get("sla"), + date_entered=_parse_dt(ticket_data.get("dateEntered")), + resources=ticket_data.get("resources"), + ) + + # Map company + company_info: CompanyInfo + if isinstance(company_raw, dict): + addr_parts = [ + company_raw.get("addressLine1"), + company_raw.get("city"), + company_raw.get("state"), + company_raw.get("zip"), + ] + address = ", ".join(p for p in addr_parts if p) or None + company_info = CompanyInfo( + id=company_raw["id"], + name=company_raw.get("name", ""), + site=company_raw.get("site", {}).get("name") if isinstance(company_raw.get("site"), dict) else company_raw.get("site"), + address=address, + phone=company_raw.get("phoneNumber"), + type=company_raw.get("type", {}).get("name") if isinstance(company_raw.get("type"), dict) else company_raw.get("type"), + territory=company_raw.get("territory", {}).get("name") if isinstance(company_raw.get("territory"), dict) else company_raw.get("territory"), + ) + else: + if isinstance(company_raw, Exception): + logger.warning("Failed to fetch company for ticket %s: %s", ticket_id, company_raw) + # Fallback: use data from ticket itself + company_info = CompanyInfo( + id=company_id or 0, + name=ticket_data.get("company", {}).get("name", "") if isinstance(ticket_data.get("company"), dict) else "", + ) + + # Map contact + contact_info: ContactInfo | None = None + if isinstance(contact_raw, dict): + first = contact_raw.get("firstName", "") + last = contact_raw.get("lastName", "") + full_name = f"{first} {last}".strip() or "Unknown" + + # Extract email from communicationItems + email: str | None = None + comm_items = contact_raw.get("communicationItems", []) + if isinstance(comm_items, list): + for item in comm_items: + if isinstance(item, dict) and item.get("communicationType") == "Email": + email = item.get("value") + break + + contact_info = ContactInfo( + name=full_name, + email=email, + phone=contact_raw.get("defaultPhoneNbr"), + title=contact_raw.get("title"), + ) + elif isinstance(contact_raw, Exception): + logger.warning("Failed to fetch contact for ticket %s: %s", ticket_id, contact_raw) + + # Map configurations + configurations: list[ConfigItem] = [] + if isinstance(configs_raw, list): + for cfg in configs_raw: + if not isinstance(cfg, dict): + continue + configurations.append(ConfigItem( + device_identifier=cfg.get("deviceIdentifier", ""), + type=cfg.get("type", {}).get("name") if isinstance(cfg.get("type"), dict) else cfg.get("type"), + os_type=cfg.get("osType", {}).get("name") if isinstance(cfg.get("osType"), dict) else cfg.get("osType"), + serial_number=cfg.get("serialNumber"), + ip_address=cfg.get("ipAddress"), + model_number=cfg.get("modelNumber"), + )) + elif isinstance(configs_raw, Exception): + logger.warning("Failed to fetch configs for ticket %s: %s", ticket_id, configs_raw) + + # Map notes + notes: list[TicketNote] = [] + if isinstance(notes_raw, list): + for note in notes_raw: + if not isinstance(note, dict): + continue + member_name: str | None = None + member_obj = note.get("member") + if isinstance(member_obj, dict): + first = member_obj.get("firstName", "") + last = member_obj.get("lastName", "") + member_name = f"{first} {last}".strip() or member_obj.get("identifier") + elif isinstance(member_obj, str): + member_name = member_obj + + notes.append(TicketNote( + text=note.get("text", ""), + member=member_name, + date_created=_parse_dt(note.get("dateCreated")), + internal_analysis_flag=note.get("internalAnalysisFlag", False), + )) + elif isinstance(notes_raw, Exception): + logger.warning("Failed to fetch notes for ticket %s: %s", ticket_id, notes_raw) + + # Map related tickets + related_tickets: list[RelatedTicket] = [] + if isinstance(related_raw, list): + for rt in related_raw: + if not isinstance(rt, dict): + continue + related_tickets.append(RelatedTicket( + id=rt["id"], + summary=rt.get("summary", ""), + status=rt.get("status", {}).get("name", "") if isinstance(rt.get("status"), dict) else str(rt.get("status", "")), + priority=rt.get("priority", {}).get("name", "") if isinstance(rt.get("priority"), dict) else str(rt.get("priority", "")), + board=rt.get("board", {}).get("name", "") if isinstance(rt.get("board"), dict) else str(rt.get("board", "")), + )) + elif isinstance(related_raw, Exception): + logger.warning("Failed to fetch related tickets for ticket %s: %s", ticket_id, related_raw) + + ctx = TicketContext( + ticket=ticket_details, + company=company_info, + contact=contact_info, + configurations=configurations, + notes=notes, + related_tickets=related_tickets, + fetched_at=datetime.now(timezone.utc), + ) + + psa_cache.set(cache_key, ctx, ttl_seconds=300) + return ctx + # ── Private helpers ─────────────────────────────────────────────── @staticmethod