# Organizer Analytics API

**Author**: Josh, Lead Backend Team  
**Last Updated**: 2025-12-11  
**Version**: v1.0

**Base URL**: `https://api.nexgate.com/api/v1`

**Short Description**: The Organizer Analytics API provides comprehensive financial and performance insights for event organizers. This API enables organizers to track total collections across all events, analyze revenue by event with filters, monitor individual event performance with detailed metrics, and visualize revenue trends over time with monthly/yearly breakdowns. The system calculates escrow holdings, released payments, ticket sales, attendance rates, and sell-out percentages automatically.

**Hints**: 
- **Organizer Only**: All endpoints restricted to event organizers
- **Auto-Calculations**: Revenue, attendance, sell-out rates computed automatically
- **Escrow Tracking**: Separate tracking for held vs released funds
- **Multi-Event**: Aggregates data across all organizer's events
- **Time Filters**: Filter by status, date range, year
- **Pagination**: Event lists paginated (default 20 per page)
- **Top Performer**: Identifies highest revenue event
- **Trend Analysis**: Monthly/yearly revenue patterns
- **Real-Time**: Updates reflect latest bookings and check-ins

---

## Response Structures

### CollectionSummaryResponse
```json
{
  "eventMetrics": {
    "totalEvents": 15,
    "upcomingEvents": 5,
    "ongoingEvents": 1,
    "completedEvents": 8,
    "cancelledEvents": 1
  },
  "collectionMetrics": {
    "totalTicketsSold": 2500,
    "totalRevenue": 5000000.00,
    "inEscrow": 1200000.00,
    "released": 3800000.00,
    "refunded": 0.00,
    "pendingRefunds": 0.00
  },
  "topEvent": {
    "eventId": "uuid",
    "eventTitle": "East African Tech Summit 2025",
    "revenue": 1500000.00,
    "ticketsSold": 500,
    "attendanceRate": 92.5
  }
}
```

### EventRevenueResponse
```json
{
  "events": [
    {
      "eventId": "uuid",
      "eventTitle": "East African Tech Summit 2025",
      "eventDate": "2025-12-15T09:00:00",
      "status": "PUBLISHED",
      "ticketsSold": 500,
      "totalRevenue": 1500000.00,
      "inEscrow": 1500000.00,
      "released": 0.00,
      "refunded": 0.00,
      "attendanceRate": 0.0,
      "totalCapacity": 1000,
      "sellOutPercentage": 50.0
    }
  ],
  "pagination": {
    "currentPage": 0,
    "pageSize": 20,
    "totalPages": 3,
    "totalElements": 45,
    "hasNext": true,
    "hasPrevious": false
  }
}
```

### EventPerformanceResponse
```json
{
  "eventId": "uuid",
  "eventTitle": "East African Tech Summit 2025",
  "eventDate": "2025-12-15T09:00:00",
  "status": "COMPLETED",
  "financials": {
    "totalRevenue": 1500000.00,
    "inEscrow": 0.00,
    "released": 1500000.00,
    "refunded": 0.00,
    "averageTicketPrice": 3000.00
  },
  "ticketMetrics": {
    "totalCapacity": 1000,
    "totalSold": 500,
    "totalRemaining": 500,
    "sellOutPercentage": 50.0
  },
  "attendanceMetrics": {
    "totalTickets": 500,
    "checkedIn": 462,
    "noShows": 38,
    "attendanceRate": 92.4
  },
  "timeline": {
    "createdAt": "2025-10-01T10:00:00",
    "publishedAt": "2025-10-05T14:30:00",
    "firstSaleAt": "2025-10-06T09:15:00",
    "eventDate": "2025-12-15T09:00:00",
    "completedAt": "2025-12-15T18:00:00"
  }
}
```

### RevenueTrendResponse
```json
{
  "period": "MONTHLY",
  "totalEvents": 12,
  "trends": [
    {
      "label": "JAN",
      "year": 2025,
      "month": 1,
      "eventsCount": 2,
      "ticketsSold": 350,
      "revenue": 875000.00,
      "inEscrow": 0.00,
      "released": 875000.00,
      "averageAttendanceRate": 88.5,
      "averageSellOutRate": 62.0
    }
  ]
}
```

---

## Endpoints

## 1. Get Collection Summary
**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px;">GET</span> `/analytics/collections/summary`

**Access**: 🔒 Organizer Only

**Success Response**: Returns CollectionSummaryResponse

**Success Response Message**: "Collection summary retrieved"

**Behavior**:
- Aggregates ALL organizer's events
- Calculates escrow (PUBLISHED, HAPPENING events)
- Calculates released (COMPLETED events)
- Identifies top performer by revenue
- Real-time metrics from latest data

**Metrics Included**:
- Event counts by status
- Total tickets sold
- Total revenue (all time)
- Money in escrow (upcoming/ongoing)
- Money released (completed)
- Refunds (placeholder)
- Top performing event

---

## 2. Get Event Revenue
**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px;">GET</span> `/analytics/collections/by-event?status=PUBLISHED&startDate=2025-01-01&endDate=2025-12-31&page=0&size=20`

**Access**: 🔒 Organizer Only

**Query Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| status | string | No | Filter by event status (PUBLISHED, COMPLETED, etc.) |
| startDate | date (ISO) | No | Filter events from this date (2025-01-01) |
| endDate | date (ISO) | No | Filter events until this date (2025-12-31) |
| page | integer | No | Page number (0-indexed, default: 0) |
| size | integer | No | Items per page (default: 20) |

**Success Response**: Returns EventRevenueResponse with pagination

**Success Response Message**: "Event revenue retrieved"

**Behavior**:
- Lists organizer's events with revenue details
- Filters by status and date range
- Sorted by event date (newest first)
- Paginated results
- Includes capacity and sell-out metrics

---

## 3. Get Event Performance
**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px;">GET</span> `/analytics/performance/{eventId}`

**Access**: 🔒 Event Organizer Only

**Path Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| eventId | string (UUID) | Yes | Event identifier |

**Success Response**: Returns EventPerformanceResponse

**Success Response Message**: "Event performance retrieved"

**Behavior**:
- Validates organizer owns event
- Calculates comprehensive metrics
- Shows financial breakdown
- Displays ticket sales vs capacity
- Tracks attendance from check-ins
- Provides event timeline

**Metrics Sections**:
- **Financials**: Revenue, escrow, released, average price
- **Tickets**: Capacity, sold, remaining, sell-out %
- **Attendance**: Total, checked-in, no-shows, rate
- **Timeline**: Key dates from creation to completion

**Errors**:
- `403 FORBIDDEN`: Not event organizer
- `404 NOT_FOUND`: Event not found

---

## 4. Get Revenue Trends
**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px;">GET</span> `/analytics/trends?period=MONTHLY&year=2025`

**Access**: 🔒 Organizer Only

**Query Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| period | string | No | MONTHLY or YEARLY (default: MONTHLY) |
| year | integer | No | Year to analyze (default: current year) |

**Success Response**: Returns RevenueTrendResponse

**Success Response Message**: "Revenue trends retrieved"

**Behavior**:

**MONTHLY Period**:
- Shows all 12 months for specified year
- Data per month: events, tickets, revenue, escrow, released
- Calculates average attendance and sell-out rates

**YEARLY Period**:
- Shows all years organizer has events
- Data per year: total events, tickets, revenue
- Year-over-year comparison

**Each Period Includes**:
- Event count
- Tickets sold
- Total revenue
- Money in escrow
- Money released
- Average attendance rate
- Average sell-out rate

---

## Key Calculations

### Escrow vs Released

**In Escrow** (Not yet paid to organizer):
- PUBLISHED events (upcoming)
- HAPPENING events (ongoing)
- Formula: Sum of booking totals for non-completed events

**Released** (Paid to organizer):
- COMPLETED events only
- Formula: Sum of booking totals for completed events

**Example**:
```
Event A: PUBLISHED, Revenue: 500,000 TZS → In Escrow
Event B: HAPPENING, Revenue: 300,000 TZS → In Escrow  
Event C: COMPLETED, Revenue: 1,200,000 TZS → Released

Total Revenue: 2,000,000 TZS
In Escrow: 800,000 TZS
Released: 1,200,000 TZS
```

### Attendance Rate
```
Attendance Rate = (Checked-In Tickets / Total Tickets) × 100
```

**Example**:
- Total tickets: 500
- Checked-in: 462
- Attendance: 92.4%

### Sell-Out Percentage
```
Sell-Out % = (Tickets Sold / Total Capacity) × 100
```

**Example**:
- Capacity: 1000
- Sold: 500
- Sell-out: 50%

### Average Ticket Price
```
Average Price = Total Revenue / Total Tickets
```

**Example**:
- Revenue: 1,500,000 TZS
- Tickets: 500
- Average: 3,000 TZS

---

## Event Status Flow

```
DRAFT → PUBLISHED → HAPPENING → COMPLETED
   ↓                               ↓
CANCELLED                     (Revenue Released)
```

**Financial Impact by Status**:
- **DRAFT**: No bookings, no revenue
- **PUBLISHED**: Bookings allowed, revenue in escrow
- **HAPPENING**: Ongoing, revenue still in escrow
- **COMPLETED**: Revenue released to organizer
- **CANCELLED**: Refunds processed (if applicable)

---

## Top Performer Logic

**Selection Criteria**: Highest total revenue

**Metrics Included**:
- Event ID and title
- Total revenue (highest wins)
- Tickets sold
- Attendance rate

**Use Case**: Dashboard highlight showing best-performing event

---

## Use Cases

### Dashboard Overview
```
GET /analytics/collections/summary

Shows:
- Total events across all statuses
- Total revenue (all time)
- Current escrow balance
- Released payments
- Top performing event
```

### Event List with Filters
```
GET /analytics/collections/by-event?status=COMPLETED&page=0&size=20

Shows:
- All completed events
- Revenue details per event
- Attendance and sell-out rates
- Paginated for easy navigation
```

### Deep Dive on Specific Event
```
GET /analytics/performance/550e8400-e29b-41d4-a716-446655440000

Shows:
- Complete financial breakdown
- Ticket sales metrics
- Attendance statistics
- Event timeline
```

### Monthly Revenue Analysis
```
GET /analytics/trends?period=MONTHLY&year=2025

Shows:
- Revenue per month in 2025
- Event count trends
- Attendance patterns
- Sell-out trends
```

### Year-Over-Year Comparison
```
GET /analytics/trends?period=YEARLY

Shows:
- Revenue by year
- Growth trends
- Performance evolution
```

---

## Best Practices

### For Organizers
✅ Check collection summary regularly  
✅ Monitor escrow balance (upcoming payouts)  
✅ Track attendance rates to improve future events  
✅ Use trends to identify peak seasons  
✅ Review individual event performance post-event  

### For Developers
✅ Cache collection summary (refresh hourly)  
✅ Paginate event lists (default 20 items)  
✅ Display financial amounts clearly (currency formatting)  
✅ Show percentage metrics with 1 decimal (92.4%)  
✅ Provide export functionality for trends  

---

## Quick Reference

### HTTP Status Codes
- `200 OK`: Successful request
- `401 UNAUTHORIZED`: Authentication required
- `403 FORBIDDEN`: Not event organizer
- `404 NOT_FOUND`: Event not found

### Date Formats
- **Event Date**: LocalDateTime (2025-12-15T09:00:00)
- **Query Params**: ISO Date (2025-01-01)

### Currency
- All amounts in **TZS** (Tanzanian Shilling)
- Format: 1500000.00 (2 decimals)

### Percentage Format
- Format: 92.4 (1 decimal)
- Range: 0.0 - 100.0

### Pagination
- Zero-indexed pages (0, 1, 2...)
- Default size: 20
- Max size: 100 (recommended)

---

## Conclusion

The Organizer Analytics API provides comprehensive insights with:

✅ **Collection Summary**: Total revenue, escrow, and top performers  
✅ **Event Revenue**: Filterable, paginated event list  
✅ **Event Performance**: Deep dive into individual event metrics  
✅ **Revenue Trends**: Monthly/yearly pattern analysis  
✅ **Real-Time**: Auto-calculated from latest bookings  
✅ **Organizer-Focused**: Restricted to event owners only