# Event Analytics Quick Wins - Implementation Plan

**Status**: DRAFT
**Created**: 2026-01-20
**Estimated Effort**: 2-3 days

## Executive Summary

The Event Management system has a fully-built analytics backend (`EventReportService.php`) that the frontend report page doesn't use. This plan wires up existing capabilities to deliver immediate value.

**Quick Wins Scope**:
- Wire existing backend metrics to frontend UI
- Display sales, marketing, inventory, and Comeback Cash analytics
- Enable Year-over-Year comparisons where previous events exist
- Make CSV export work (button exists, needs wiring)

**Out of Scope** (Future Phases):
- Chart.js visualizations (daily revenue, marketing funnel)
- Multi-event comparison feature
- PDF/XLSX export formats
- Mobile API integration
- Real-time dashboard during active events

---

## Current State

### Backend (✅ Ready)

**EventReportService.php** provides these methods:
- `getSalesMetrics($eventId)` - Revenue, transactions, avg ticket, lift vs baseline
- `getMarketingMetrics($eventId)` - SMS delivery rates, click rates, signage impressions
- `getInventoryMetrics($eventId)` - Backstock bins, items, sell-through rate
- `getComebackCashMetrics($eventId)` - Redemption rate, ROI, revenue impact
- `getYearOverYearComparison($eventId)` - Previous year event comparison
- `exportToCsv($eventId)` - Full CSV export

**EventReportController.php** provides API endpoints:
- `GET /api/:typeNum/events/:eventId/report` - All metrics
- `GET /api/:typeNum/events/:eventId/report/export?format=csv` - Export

### Frontend (❌ Incomplete)

**report-detail.html** currently shows:
- Integration status counts only (line 633-697)
- Phase timeline (line 699-740)
- Audit log (line 810-853)

**EventPageController.php:888-969** only calls:
- `getEventOr404()` - Load event
- `getIntegrations()` - Load integration links
- `getAuditLog()` - Load change history

Does NOT call: `EventReportService::getEventMetrics()`

---

## Implementation Plan

### Phase 1: Wire Backend to Controller (30 min)

**File**: `userfrosting/src/BuyerKiosk/EventManagement/Controllers/EventPageController.php`

**Changes**:
1. Inject `EventReportService` into controller constructor
2. In `reportDetail()` method (~line 888), call:
   ```php
   $reportService = new EventReportService($this->db);
   $metrics = $reportService->getEventMetrics($event->id);
   ```
3. Pass `$metrics` to template:
   ```php
   'salesMetrics' => $metrics['sales'],
   'marketingMetrics' => $metrics['marketing'],
   'inventoryMetrics' => $metrics['inventory'],
   'comebackCashMetrics' => $metrics['comebackCash'],
   'yoyComparison' => $metrics['yearOverYear'],
   ```

### Phase 2: Update Report Template (2-3 hours)

**File**: `userfrosting/templates/themes/default/admin/event-management/report-detail.html`

**Add New Sections**:

#### 2.1 Sales Performance Card
Insert after overview cards (~line 697):
- Total Revenue during event
- Total Transactions
- Average Ticket Value
- Items Sold
- Unique Customers
- **Sales Lift** vs baseline period (percentage + absolute)

#### 2.2 Marketing Performance Card
Add new section:
- SMS Blasts: Sent, Delivered, Delivery Rate
- SMS Click Rate (if tracking enabled)
- SMS Triggers: Sent, Delivered
- Digital Signage: Slides Active, Display Hours

#### 2.3 Comeback Cash Performance Card
Add new section:
- Coupons Issued (count + total value)
- Coupons Redeemed (count + value)
- **Redemption Rate** (prominent display)
- Revenue from Redemptions
- **ROI Calculation** (revenue vs coupon cost)

#### 2.4 Inventory Performance Card
Add new section:
- Backstock Events Linked
- Bins Pulled
- Items Processed
- Items Sold
- **Sell-Through Rate**

#### 2.5 Year-over-Year Comparison
Add conditional section (if previous event exists):
- Side-by-side metrics table
- Revenue change (% and $)
- Transaction change
- Average ticket change
- Trend indicators (↑ ↓ →)

### Phase 3: Styling (1 hour)

**File**: `public_html/css/admin/event-management.css`

Add styles for:
- Metric cards with color-coded performance indicators
- Lift/change badges (green for positive, red for negative)
- YoY comparison table
- Redemption rate "gauge" style display

### Phase 4: Wire Export Button (30 min)

**File**: `report-detail.html` (~line 613-616)

Current button exists but may not work. Wire to:
```javascript
function exportReport(format) {
    window.location.href = `/api/${typeNum}/events/${eventId}/report/export?format=${format}`;
}
```

### Phase 5: Handle Edge Cases (1 hour)

**Scenarios**:
1. **No sales during event period** - Show "No sales recorded" message
2. **No previous year event** - Hide YoY section
3. **Integration not linked** - Show "Not configured" for that section
4. **SMS feature not enabled** - Hide marketing section gracefully
5. **Comeback Cash not enabled** - Hide that section

---

## Technical Details

### Data Flow After Implementation

```
User visits: /admin/{typeNum}/events/reports/{eventId}
    ↓
EventPageController::reportDetail()
    ↓
    1. getEventOr404() - Load event
    2. getIntegrations() - Load integrations
    3. getAuditLog() - Load history
    4. NEW: EventReportService::getEventMetrics() - Load ALL metrics
    ↓
Pass all data to template
    ↓
report-detail.html renders:
    - Existing: Integration status, phase timeline, audit log
    - NEW: Sales metrics with lift
    - NEW: Marketing metrics with rates
    - NEW: Comeback Cash with redemption rate
    - NEW: Inventory with sell-through
    - NEW: YoY comparison (conditional)
```

### Database Queries (Already Built)

All queries exist in `EventReportService.php`:

| Method | Tables Queried | Lines |
|--------|---------------|-------|
| `getSalesMetrics()` | `buyQueue` | 113-165 |
| `getMarketingMetrics()` | `seller_marketing_blasts`, `dsloop` | 177-228 |
| `getInventoryMetrics()` | `bsEvents`, `buyQueue` | 240-269 |
| `getComebackCashMetrics()` | `ccTransactions`, `cccoupons` | 281-324 |
| `getYearOverYearComparison()` | `events` (self-join) | 336-388 |

### Template Variables

After implementation, template receives:

```twig
{# Sales Metrics #}
{{ salesMetrics.revenue }}
{{ salesMetrics.transactions }}
{{ salesMetrics.avgTicket }}
{{ salesMetrics.itemsSold }}
{{ salesMetrics.uniqueCustomers }}
{{ salesMetrics.lift.percentage }}
{{ salesMetrics.lift.absolute }}

{# Marketing Metrics #}
{{ marketingMetrics.blasts.sent }}
{{ marketingMetrics.blasts.delivered }}
{{ marketingMetrics.blasts.deliveryRate }}
{{ marketingMetrics.triggers.sent }}
{{ marketingMetrics.signage.slidesActive }}

{# Comeback Cash Metrics #}
{{ comebackCashMetrics.issued.count }}
{{ comebackCashMetrics.issued.totalValue }}
{{ comebackCashMetrics.redeemed.count }}
{{ comebackCashMetrics.redeemed.value }}
{{ comebackCashMetrics.redemptionRate }}
{{ comebackCashMetrics.roi }}

{# Inventory Metrics #}
{{ inventoryMetrics.binsPulled }}
{{ inventoryMetrics.itemsProcessed }}
{{ inventoryMetrics.itemsSold }}
{{ inventoryMetrics.sellThroughRate }}

{# YoY Comparison (if exists) #}
{% if yoyComparison %}
{{ yoyComparison.previousEvent.name }}
{{ yoyComparison.revenueChange.percentage }}
{{ yoyComparison.revenueChange.direction }}
{% endif %}
```

---

## Testing Checklist

- [ ] Report page loads without errors
- [ ] Sales metrics display correctly for completed event
- [ ] Lift calculation shows positive/negative correctly
- [ ] Marketing section handles "no SMS" gracefully
- [ ] Comeback Cash shows "N/A" when not configured
- [ ] YoY section appears only when previous event exists
- [ ] YoY section hidden when no linked event
- [ ] CSV export downloads with all metrics
- [ ] Mobile responsive layout works
- [ ] Empty state messages display properly

---

## Success Metrics

After implementation:
- **Coupon redemption rates** visible on report ✅
- **Sales lift** vs baseline visible ✅
- **SMS performance** metrics visible ✅
- **Year-over-year trends** visible ✅
- Report page provides actionable insights instead of just status

---

## Future Phases (Out of Scope)

### Phase 2: Visualizations
- Chart.js daily revenue line chart
- Marketing funnel visualization
- Comeback Cash pie chart
- Requires: Additional JS, new chart components

### Phase 3: Comparisons
- Multi-event comparison (up to 4 events)
- Template performance comparison
- Requires: New API endpoint, new UI page

### Phase 4: Exports
- PDF export with formatting
- XLSX export with multiple sheets
- Requires: PDF library (TCPDF/DOMPDF), PhpSpreadsheet

### Phase 5: Real-Time Dashboard
- Live metrics during active events
- Ably websocket integration
- Requires: Significant frontend work, websocket infrastructure
