# Event Phase Processor - Operational Runbook

## Overview

The Event Phase Processor is an on-demand service that updates event phases based on the current date. It runs when stores open (checked during initialization) rather than via scheduled cron.

## System Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    Store Initialization                      │
├─────────────────────────────────────────────────────────────┤
│  1. User accesses store (admin panel or workspace)           │
│  2. Store context loaded                                     │
│  3. EventPhaseProcessor::processStore() called              │
│  4. All scheduled/active events evaluated                    │
│  5. Phase transitions executed                               │
│  6. Integrations activated/deactivated as needed            │
└─────────────────────────────────────────────────────────────┘
```

## Component Location

```
userfrosting/src/BuyerKiosk/EventManagement/Services/EventPhaseProcessor.php
```

## Phase Transition Rules

Events progress through 5 phases based on dates:

| Phase | Condition | Actions |
|-------|-----------|---------|
| `upcoming` | Today < startDate - buildUpDays | No action |
| `build_up` | startDate - buildUpDays <= Today < startDate | Prepare integrations |
| `active` | startDate <= Today <= endDate | Activate pending integrations |
| `wind_down` | endDate < Today <= endDate + windDownDays | Begin cleanup |
| `completed` | Today > endDate + windDownDays | Mark event complete |

## Integration Activation

When an event transitions to `active` phase:

1. All integrations with `status = 'pending'` are activated
2. Backstock events are marked ready
3. SMS blasts scheduled within range are queued
4. Digital signage slides are added to loop
5. Comeback Cash earning periods begin
6. Tasks become visible to staff
7. Notes are published

## Error Handling

The processor implements per-event error isolation:

```php
foreach ($events as $event) {
    try {
        $this->processEvent($event);
    } catch (Exception $e) {
        // Log error but continue processing other events
        error_log("Event {$event->id} failed: " . $e->getMessage());
    }
}
```

## Monitoring

### Log Locations

- PHP Error Log: `/var/log/php/error.log`
- Application Log: Event changes logged to `event_audit_log` table

### Key Log Patterns

```
# Successful phase transition
EventPhaseProcessor: Event 123 transitioned from upcoming to build_up

# Integration activation
EventPhaseProcessor: Activated 4 integrations for event 123

# Error (non-fatal)
EventPhaseProcessor: Event 456 failed: Integration service unavailable
```

### Database Audit

```sql
-- Recent phase transitions
SELECT * FROM event_audit_log
WHERE action = 'phase_transition'
ORDER BY created_at DESC
LIMIT 20;

-- Events by phase
SELECT phase, COUNT(*)
FROM events
WHERE status = 'scheduled' OR status = 'active'
GROUP BY phase;

-- Pending integrations
SELECT integrationType, COUNT(*)
FROM event_integrations
WHERE status = 'pending'
GROUP BY integrationType;
```

## Manual Intervention

### Force Phase Recalculation

To manually recalculate phases for a store:

```php
$db = dbConnectByName('kiosk_' . $typeNum);
$processor = new EventPhaseProcessor($db, $integrationService, $userId);
$results = $processor->processStore();
```

### Skip Processing for Event

If an event should not auto-transition:

1. Set status to `cancelled` or `archived`
2. Or set dates far in future

### Fix Stuck Integration

```sql
-- Check integration status
SELECT * FROM event_integrations WHERE eventId = 123;

-- Reset to pending for reprocessing
UPDATE event_integrations
SET status = 'pending'
WHERE eventId = 123 AND integrationType = 'backstock';
```

## Troubleshooting

### Events Not Transitioning

1. Check event status is `scheduled` or `active`
2. Verify dates are set correctly
3. Confirm store has been accessed (triggers processing)
4. Check error logs for exceptions

### Integrations Not Activating

1. Verify integration `status = 'pending'`
2. Check `foreignId` references valid record
3. Ensure target system (backstock, SMS, etc.) is operational
4. Check IntegrationService logs

### Performance Issues

If processing is slow:

1. Check number of events per store (should be < 50 active)
2. Verify database indexes on `events.status`, `events.phase`
3. Check IntegrationService adapter performance

## Recovery Procedures

### After Database Restore

```sql
-- Recalculate all phases to match current date
UPDATE events
SET phase = CASE
    WHEN CURDATE() < DATE_SUB(startDate, INTERVAL buildUpDays DAY) THEN 'upcoming'
    WHEN CURDATE() < startDate THEN 'build_up'
    WHEN CURDATE() <= endDate THEN 'active'
    WHEN CURDATE() <= DATE_ADD(endDate, INTERVAL windDownDays DAY) THEN 'wind_down'
    ELSE 'completed'
END
WHERE status IN ('scheduled', 'active');
```

### Rollback Integration Activation

```sql
-- Revert integrations to pending
UPDATE event_integrations
SET status = 'pending'
WHERE eventId = 123 AND status = 'active';

-- May need to clean up foreign tables
DELETE FROM bsEvents WHERE eventId = 123;
DELETE FROM dsLoop WHERE eventId = 123;
```

## Future Enhancements (Planned)

- [ ] Cron-based scheduled processing (for automated transition without store access)
- [ ] Ably real-time broadcast on phase changes
- [ ] Webhook notifications for external systems
- [ ] Task orchestration integration

## Related Documentation

- [Event Management API](../api/EVENT_MANAGEMENT_API.md)
- [Solution Design - Phase Processor](../specs/004-unified-event-management/solution-design.md#phase-processor)
- [Integration Adapters](../specs/004-unified-event-management/solution-design.md#integration-adapters)
