Analytics API

The Analytics API provides metrics, trends, and performance data for dashboards and reporting.

Overview

Analytics endpoints provide:

  • Dashboard Metrics: Quick overview of tickets and articles
  • Ticket Trends: Volume over time
  • Agent Performance: Resolution rates per agent
  • Response Times: First response and resolution time metrics
  • Customer Satisfaction: CSAT scores and rating distribution

Get Overview

Retrieve high-level metrics for the dashboard.

Procedure: analytics.getOverview

Authentication: Required

Input:

{
  startDate?: string;  // ISO date filter (optional)
  endDate?: string;    // ISO date filter (optional)
}

Example:

curl -X GET "https://your-domain.com/api/trpc/analytics.getOverview" \
  -H "Cookie: your-session-cookie"

Response:

{
  "result": {
    "data": {
      "json": {
        "tickets": {
          "total": 1500,
          "open": 125,
          "resolved": 1200,
          "resolutionRate": 80
        },
        "articles": {
          "totalViews": 45000,
          "helpful": 3200,
          "notHelpful": 180,
          "helpfulRate": 95
        }
      }
    }
  }
}

Response Fields

FieldDescription
tickets.totalTotal tickets in the organization
tickets.openTickets with status open or new
tickets.resolvedTickets with status resolved or closed
tickets.resolutionRatePercentage of resolved tickets
articles.totalViewsTotal views across all published articles
articles.helpfulTotal helpful feedback count
articles.notHelpfulTotal not helpful feedback count
articles.helpfulRatePercentage of helpful feedback

Get Ticket Trends

Retrieve ticket creation trends over a specified time period.

Procedure: analytics.getTicketTrends

Authentication: Required

Input:

{
  days: number;  // 1-90, default: 30
}

Example:

curl -X GET "https://your-domain.com/api/trpc/analytics.getTicketTrends?input=%7B%22days%22:30%7D" \
  -H "Cookie: your-session-cookie"

Response:

{
  "result": {
    "data": {
      "json": [
        {
          "date": "2024-01-01",
          "created": 45,
          "resolved": 38
        },
        {
          "date": "2024-01-02",
          "created": 52,
          "resolved": 41
        },
        {
          "date": "2024-01-03",
          "created": 38,
          "resolved": 35
        }
      ]
    }
  }
}

Response Fields

FieldDescription
dateDate in YYYY-MM-DD format
createdNumber of tickets created on this date
resolvedNumber of tickets resolved on this date

Notes:

  • Results are ordered by date ascending
  • Only includes tickets within the specified time range
  • Excludes soft-deleted tickets

Get Agent Performance

Retrieve performance metrics for each agent in the organization.

Procedure: analytics.getAgentPerformance

Authentication: Required

Input: None

Example:

curl -X GET "https://your-domain.com/api/trpc/analytics.getAgentPerformance" \
  -H "Cookie: your-session-cookie"

Response:

{
  "result": {
    "data": {
      "json": [
        {
          "agent": {
            "id": "user-uuid-1",
            "name": "Alice Johnson",
            "email": "alice@company.com"
          },
          "totalTickets": 245,
          "resolvedTickets": 210,
          "resolutionRate": 86
        },
        {
          "agent": {
            "id": "user-uuid-2",
            "name": "Bob Smith",
            "email": "bob@company.com"
          },
          "totalTickets": 180,
          "resolvedTickets": 165,
          "resolutionRate": 92
        }
      ]
    }
  }
}

Response Fields

FieldDescription
agent.idAgent's user UUID
agent.nameAgent's display name
agent.emailAgent's email address
totalTicketsTotal tickets assigned to this agent
resolvedTicketsTickets resolved by this agent
resolutionRatePercentage of resolved tickets

Notes:

  • Only includes users with agent or admin roles
  • Only counts tickets that are assigned to the agent
  • Excludes soft-deleted tickets

Get Response Time Metrics

Retrieve response time and SLA compliance metrics.

Procedure: analytics.getResponseTimeMetrics

Authentication: Required

Input: None

Example:

curl -X GET "https://your-domain.com/api/trpc/analytics.getResponseTimeMetrics" \
  -H "Cookie: your-session-cookie"

Response:

{
  "result": {
    "data": {
      "json": {
        "averageFirstResponse": 45,
        "averageResolutionTime": 8.5,
        "withinSLA": 92
      }
    }
  }
}

Response Fields

FieldDescription
averageFirstResponseAverage first response time in minutes
averageResolutionTimeAverage resolution time in hours
withinSLAPercentage of tickets with first response within 24 hours

Notes:

  • First response time is calculated from ticket creation to first conversation
  • Resolution time is calculated from ticket creation to status change (resolved/closed)
  • SLA threshold is 24 hours for first response

Get Customer Satisfaction

Retrieve CSAT (Customer Satisfaction) scores and rating distribution.

Procedure: analytics.getCustomerSatisfaction

Authentication: Required

Input: None

Example:

curl -X GET "https://your-domain.com/api/trpc/analytics.getCustomerSatisfaction" \
  -H "Cookie: your-session-cookie"

Response:

{
  "result": {
    "data": {
      "json": {
        "averageRating": 4.3,
        "totalResponses": 856,
        "distribution": {
          "1": 12,
          "2": 25,
          "3": 68,
          "4": 285,
          "5": 466
        },
        "csatScore": 88
      }
    }
  }
}

Response Fields

FieldDescription
averageRatingAverage rating (1-5 scale)
totalResponsesTotal number of ratings received
distributionCount of ratings by star level (1-5)
csatScoreCSAT score - percentage of 4 and 5 star ratings

Notes:

  • CSAT score is calculated as: (4-star + 5-star ratings) / total ratings * 100
  • Ratings are collected from the ticket_ratings table
  • Returns zeros if no ratings exist

Record Event

Record a custom analytics event for tracking user actions.

Procedure: analytics.recordEvent

Authentication: Required

Input:

{
  eventName: string;                           // Event identifier
  properties?: Record<string, any>;            // Optional event properties
}

Example:

curl -X POST "https://your-domain.com/api/trpc/analytics.recordEvent" \
  -H "Content-Type: application/json" \
  -H "Cookie: your-session-cookie" \
  -d '{
    "json": {
      "eventName": "ticket_merged",
      "properties": {
        "sourceTicketId": "uuid-1",
        "targetTicketId": "uuid-2",
        "mergeReason": "duplicate"
      }
    }
  }'

Response:

{
  "result": {
    "data": {
      "json": {
        "success": true
      }
    }
  }
}

Notes:

  • Events are stored with the user ID and organization ID
  • Properties can contain any JSON-serializable data
  • Useful for tracking custom workflows and feature usage

Common Event Names

Suggested event names for consistency:

Event NameDescription
ticket_createdNew ticket created
ticket_mergedTickets merged
ticket_escalatedTicket escalated
article_publishedArticle published
macro_appliedMacro applied to ticket
automation_triggeredAutomation rule fired
integration_connectedIntegration connected
search_performedSearch query executed

Error Codes

CodeDescription
FORBIDDENUser not associated with an organization
INTERNAL_SERVER_ERRORDatabase query failed

Performance Notes

All analytics queries are optimized for performance:

  • Bulk queries: Single database queries are used instead of N+1 patterns
  • Minimal data selection: Only required columns are fetched
  • In-memory aggregation: Grouping and calculations are performed efficiently
  • Graceful degradation: Returns default values if tables don't exist

Use Cases

Dashboard Widget

// Fetch overview for dashboard
const overview = await trpc.analytics.getOverview.query()

// Display ticket stats
console.log(`Open: ${overview.tickets.open}`)
console.log(`Resolution Rate: ${overview.tickets.resolutionRate}%`)

Agent Leaderboard

// Get agent performance
const performance = await trpc.analytics.getAgentPerformance.query()

// Sort by resolution rate
const leaderboard = performance.sort((a, b) =>
  b.resolutionRate - a.resolutionRate
)

Trend Chart

// Get 30-day trends
const trends = await trpc.analytics.getTicketTrends.query({ days: 30 })

// Format for charting library
const chartData = trends.map(day => ({
  x: day.date,
  created: day.created,
  resolved: day.resolved
}))