Skip to content

Production Run Analytics API

The Analytics API provides comprehensive insights into tracker journeys within production runs, focusing on state durations and delivery location performance metrics.

Overview

The analytics system calculates detailed metrics for tracker journeys including:

  • Time spent in each state (CREATED, IN_TRANSIT, IN_STORAGE, DELIVERED)
  • Delivery location dwell times (primary customer focus)
  • Storage location breakdowns
  • Journey completion rates and efficiency metrics
  • Aggregate statistics across all trackers in a production run

API Endpoints

All analytics endpoints are nested under production runs and require appropriate client access permissions.

Get Complete Analytics (JSON)

GET /api/v1/production-runs/{production_run_id}/analytics

Returns comprehensive analytics data in JSON format including individual tracker metrics, aggregate statistics, and delivery location performance.

Response Schema: ProductionRunAnalytics

Example Response:

{
  "production_run_id": 123,
  "production_run_description": "Q1 2025 Deployment",
  "production_run_start_date": "2025-01-01T00:00:00Z",
  "production_run_end_date": "2025-03-31T23:59:59Z",
  "total_trackers": 150,
  "tracker_analytics": [
    {
      "tracker_id": 1001,
      "tracker_name": "Tracker-001",
      "total_journey_duration_days": 12.5,
      "delivery_location_name": "Distribution Center A",
      "delivery_location_duration_days": 2.3,
      "delivery_location_duration_hours": 55.2,
      "current_status": "DELIVERED",
      "journey_completion_percent": 100.0
    }
  ],
  "aggregate_metrics": {
    "total_trackers": 150,
    "completed_trackers": 142,
    "completion_rate_percent": 94.7,
    "average_delivery_location_duration_days": 1.8
  },
  "delivery_location_performance": [
    {
      "location_name": "Distribution Center A",
      "tracker_count": 75,
      "average_duration_days": 1.8,
      "min_duration_days": 0.5,
      "max_duration_days": 4.2
    }
  ]
}

Download Analytics CSV

GET /api/v1/production-runs/{production_run_id}/analytics/csv

Downloads analytics data as a CSV file suitable for further analysis in spreadsheet applications.

Query Parameters:

  • include_aggregate_summary (boolean, default: true) - Include summary statistics
  • include_delivery_performance (boolean, default: true) - Include delivery location metrics
  • date_format (string, default: "ISO") - Date format: "ISO", "US", or "EU"

Response: CSV file download with headers:

  • Content-Type: text/csv
  • Content-Disposition: attachment; filename=production_run_{id}_{description}_{timestamp}.csv

CSV Structure:

# Production Run Analytics
Production Run ID,123
Description,Q1 2025 Deployment
Start Date,2025-01-01 00:00:00
...

# Tracker Analytics
Tracker Name,Tracker ID,Current Status,Journey Completion %,Total Journey Duration (days),...
Tracker-001,1001,DELIVERED,100.0%,12.50,...

Get Delivery Location Performance

GET /api/v1/production-runs/{production_run_id}/analytics/delivery-performance

Returns focused delivery location performance metrics without full tracker details.

Response Schema: List[DeliveryLocationPerformance]

Get Aggregate Summary

GET /api/v1/production-runs/{production_run_id}/analytics/summary

Returns high-level summary metrics for quick overview.

Response Schema: AggregateMetrics

Key Metrics Explained

Delivery Location Dwell Time

Primary customer focus metric - measures how long trackers spend at delivery locations.

  • Duration (days): Total time from arrival to departure/completion
  • Duration (hours): Same metric in hours for operational precision
  • Performance comparison: Min/max/average across all trackers at each location

Journey Completion Percentage

Indicates progress through the tracker lifecycle:

  • CREATED: 0% - Initial state
  • IN_TRANSIT: 33.3% - Moving between locations
  • IN_STORAGE: 66.7% - Temporarily stored
  • DELIVERED: 100% - Final destination reached

State Duration Calculations

All durations calculated from status_history table timestamps:

  • Precise timing: Uses actual status change timestamps
  • Current state handling: Includes time from last status change to present
  • Edge case management: Handles incomplete journeys and missing transitions

Storage Location Breakdown

Detailed analysis of storage facility usage:

  • Locations visited: List of all storage facilities used
  • Duration per location: Time spent at each facility
  • Efficiency metrics: Identifies bottlenecks and optimal facilities

Data Quality Considerations

Incomplete Journeys

  • Trackers not yet delivered show partial metrics
  • Journey completion percentage indicates progress
  • Duration calculations include current state time

Missing Status Transitions

  • System handles gaps in status history gracefully
  • Error logging for debugging data quality issues
  • Fallback calculations for edge cases

Time Zone Handling

  • All timestamps stored and calculated in UTC
  • CSV export respects user-selected date format
  • Consistent duration calculations across time zones

Performance Optimization

Caching Strategy

  • Analytics results cached per production run
  • Cache invalidation on status updates
  • Separate cache keys for different user contexts

Query Optimization

  • Leverages existing TimescaleDB continuous aggregates
  • Efficient joins with location tables
  • Batch processing for large production runs

Streaming CSV Generation

  • Large datasets streamed to prevent memory issues
  • Progressive CSV generation for responsive downloads
  • Configurable sections to reduce file size

Usage Examples

Admin Panel Integration

The analytics endpoints are designed for integration into the admin panel production run detail pages:

// Fetch analytics data for display
const analytics = await fetch(`/api/v1/production-runs/${id}/analytics`);

// Download CSV for customer
window.location.href = `/api/v1/production-runs/${id}/analytics/csv?date_format=US`;

// Get quick summary for dashboard
const summary = await fetch(`/api/v1/production-runs/${id}/analytics/summary`);

Customer Reporting

Customers can analyze the CSV data to:

  • Identify delivery location efficiency patterns
  • Track journey completion rates over time
  • Compare storage facility performance
  • Calculate SLA compliance metrics

Operational Insights

Use delivery location performance data to:

  • Optimize facility operations
  • Identify bottleneck locations
  • Plan capacity requirements
  • Improve customer satisfaction

Error Handling

Common Error Responses

  • 404 Not Found: Production run doesn't exist or user lacks access
  • 403 Forbidden: Insufficient permissions for production run
  • 500 Internal Server Error: Analytics calculation failure

Data Validation

  • Production run existence verification
  • Client access permission checks
  • Status history data integrity validation
  • Location reference consistency checks

Security & Access Control

Permission Requirements

  • User must have access to production run's client
  • Same access controls as other production run endpoints
  • Admin users can access all production runs

Data Privacy

  • Analytics only include data user has permission to view
  • No cross-client data leakage
  • Audit logging for analytics access

Future Enhancements

Planned Features

  • Real-time analytics updates via WebSocket
  • Comparative analytics across production runs
  • Predictive delivery time estimates
  • Custom date range filtering
  • Export to additional formats (Excel, PDF)

Performance Improvements

  • Background analytics pre-calculation
  • Incremental updates for large datasets
  • Advanced caching strategies
  • Query optimization for complex filters