# Event Management API

API endpoints for the Unified Event Management system.

## Authentication

All endpoints require session authentication via UserFrosting.

**Permissions:**
- `uri_events` - View events (read access)
- `uri_events_manage` - Create, edit, delete events (write access)
- `uri_events_reports` - View event reports

## Base URL

```
/api/:typeNum/events
```

Where `:typeNum` is the store identifier (e.g., `ou00`, `pa01`).

---

## Event CRUD Endpoints

### List Events

```http
GET /api/:typeNum/events
```

**Query Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `year` | int | Filter by event year |
| `status` | string | Filter by status: `draft`, `scheduled`, `active`, `completed`, `cancelled`, `archived` |
| `eventType` | string | Filter by type: `season`, `holiday`, `sale`, `custom` |

**Response:**
```json
{
  "success": true,
  "events": [
    {
      "id": 1,
      "name": "Back to School 2025",
      "eventType": "season",
      "status": "scheduled",
      "phase": "upcoming",
      "startDate": "2025-07-20",
      "endDate": "2025-08-31",
      "buildUpDays": 14,
      "windDownDays": 7,
      "color": "#4CAF50",
      "icon": "school",
      "isRecurring": true
    }
  ],
  "total": 1,
  "filters": {
    "year": 2025,
    "status": null,
    "eventType": null
  }
}
```

### Get Event

```http
GET /api/:typeNum/events/:eventId
```

**Response:**
```json
{
  "success": true,
  "event": {
    "id": 1,
    "name": "Back to School 2025",
    "description": "Annual back to school promotional event",
    "eventType": "season",
    "year": 2025,
    "startDate": "2025-07-20",
    "endDate": "2025-08-31",
    "buildUpDays": 14,
    "windDownDays": 7,
    "status": "scheduled",
    "phase": "upcoming",
    "color": "#4CAF50",
    "icon": "school",
    "isRecurring": true,
    "templateId": 1,
    "integrations": [
      {
        "id": 1,
        "integrationType": "backstock",
        "foreignId": 5,
        "status": "pending",
        "config": {}
      }
    ]
  }
}
```

### Create Event

```http
POST /api/:typeNum/events
```

**Request Body:**
```json
{
  "name": "Back to School 2025",
  "eventType": "season",
  "startDate": "2025-07-20",
  "endDate": "2025-08-31",
  "description": "Annual back to school promotional event",
  "buildUpDays": 14,
  "windDownDays": 7,
  "color": "#4CAF50",
  "icon": "school",
  "isRecurring": true,
  "templateId": 1,
  "integrations": [
    {
      "integrationType": "backstock",
      "config": {
        "categoryIds": [1, 2, 3]
      }
    }
  ]
}
```

**Required Fields:**
- `name` (string, max 100 chars)
- `eventType` (enum: season, holiday, sale, custom)
- `startDate` (date, YYYY-MM-DD)
- `endDate` (date, YYYY-MM-DD)

**Response:**
```json
{
  "success": true,
  "event": { ... }
}
```

### Update Event

```http
PUT /api/:typeNum/events/:eventId
```

**Request Body:** Same as Create (all fields optional)

**Response:**
```json
{
  "success": true,
  "event": { ... },
  "recalculatedIntegrations": true
}
```

### Delete Event

```http
DELETE /api/:typeNum/events/:eventId
```

**Note:** Only draft events can be deleted. Use archive for other statuses.

**Response:**
```json
{
  "success": true,
  "cascadeDeleted": {
    "backstock": 1,
    "sms_blast": 2,
    "tasks": 5
  }
}
```

---

## Event Actions

### Activate Event

```http
POST /api/:typeNum/events/:eventId/activate
```

Transitions event from `draft` or `scheduled` to `active`.

**Response:**
```json
{
  "success": true,
  "event": { ... },
  "integrationsActivated": 4
}
```

### Cancel Event

```http
POST /api/:typeNum/events/:eventId/cancel
```

Cancels an event and deactivates all pending integrations.

**Response:**
```json
{
  "success": true,
  "event": { ... },
  "integrationsCancelled": 4
}
```

### Duplicate Event

```http
POST /api/:typeNum/events/:eventId/duplicate
```

Creates a copy of an existing event with new dates.

**Request Body:**
```json
{
  "name": "Back to School 2026",
  "startDate": "2026-07-20",
  "endDate": "2026-08-31",
  "includeIntegrations": true
}
```

**Response:**
```json
{
  "success": true,
  "event": { ... },
  "integrationsCreated": 6
}
```

### Archive Event

```http
POST /api/:typeNum/events/:eventId/archive
```

Soft-deletes an event (can be restored).

**Response:**
```json
{
  "success": true,
  "event": { ... }
}
```

### Unarchive Event

```http
POST /api/:typeNum/events/:eventId/unarchive
```

Restores an archived event.

**Response:**
```json
{
  "success": true,
  "event": { ... }
}
```

### Permanently Delete Event

```http
DELETE /api/:typeNum/events/:eventId/permanent
```

Hard-deletes an archived event. Cannot be undone.

**Request Body:**
```json
{
  "confirm": true
}
```

**Response:**
```json
{
  "success": true,
  "cascadeDeleted": { ... }
}
```

---

## Conflict Detection

### Check Event Conflicts

```http
POST /api/:typeNum/events/check-conflicts
```

Validates event dates and integrations for conflicts before create/update.

**Request Body:**
```json
{
  "eventId": null,
  "startDate": "2025-07-20",
  "endDate": "2025-08-31",
  "eventType": "season",
  "integrations": []
}
```

**Response:**
```json
{
  "success": true,
  "hasConflicts": false,
  "conflicts": [],
  "warnings": [
    {
      "type": "short_buildup",
      "message": "Build-up period is less than recommended",
      "suggestion": "Consider starting event preparation earlier"
    }
  ]
}
```

---

## Templates

### List Templates

```http
GET /api/:typeNum/events/templates
```

**Query Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `scope` | string | Filter by scope: `global`, `franchise`, `store` |
| `eventType` | string | Filter by type |

**Response:**
```json
{
  "success": true,
  "templates": [
    {
      "id": 1,
      "name": "Back to School",
      "description": "Annual back to school promotional template",
      "eventType": "season",
      "scope": "global",
      "defaultBuildUpDays": 14,
      "defaultWindDownDays": 7,
      "color": "#4CAF50",
      "icon": "school"
    }
  ]
}
```

### Get Template

```http
GET /api/:typeNum/events/templates/:templateId
```

**Response:**
```json
{
  "success": true,
  "template": {
    "id": 1,
    "name": "Back to School",
    "integrations": [
      {
        "integrationType": "backstock",
        "config": { ... },
        "relativeDays": -14,
        "isOptional": false
      }
    ]
  }
}
```

---

## Reports

### Get Event Report

```http
GET /api/:typeNum/events/:eventId/report
```

**Permission:** `uri_events_reports`

**Response:**
```json
{
  "success": true,
  "report": {
    "event": {
      "id": 1,
      "name": "Back to School 2024",
      "startDate": "2024-07-20",
      "endDate": "2024-08-31"
    },
    "period": {
      "totalDays": 43,
      "buildUpDays": 14,
      "activeDays": 22,
      "windDownDays": 7
    },
    "sales": {
      "totalRevenue": 45000.00,
      "totalTransactions": 450,
      "averageTicket": 100.00,
      "salesLift": 15.5
    },
    "marketing": {
      "smsSent": 1500,
      "smsDelivered": 1450,
      "clickRate": 8.5
    },
    "inventory": {
      "binsPulled": 25,
      "itemsProcessed": 500
    },
    "comebackCash": {
      "couponsIssued": 200,
      "couponsRedeemed": 45,
      "redemptionRate": 22.5,
      "revenueImpact": 2250.00
    }
  }
}
```

### Export Report CSV

```http
GET /api/:typeNum/events/:eventId/report/csv
```

Returns CSV file download.

---

## Error Responses

All endpoints return errors in the following format:

```json
{
  "success": false,
  "error": "Error message",
  "code": "ERROR_CODE"
}
```

**Common Error Codes:**
- `UNAUTHORIZED` - Not authenticated (401)
- `FORBIDDEN` - Missing required permission (403)
- `NOT_FOUND` - Event not found (404)
- `VALIDATION_ERROR` - Invalid input data (400)
- `CONFLICT` - Event date conflict (409)
- `INVALID_STATUS_TRANSITION` - Cannot transition to requested status (400)

---

## Event Status Lifecycle

```
draft → scheduled → active → completed → archived
                 ↘         ↘
                  cancelled → archived
```

**Valid Transitions:**
| From | To |
|------|-----|
| draft | scheduled, cancelled |
| scheduled | active, cancelled |
| active | completed, cancelled |
| completed | archived |
| cancelled | archived |

---

## Integration Types

| Type | Description | Target Table |
|------|-------------|--------------|
| `backstock` | Backstock event | bsEvents |
| `sms_blast` | SMS marketing blast | seller_marketing_blasts |
| `sms_trigger` | SMS marketing trigger | seller_marketing_triggers |
| `signage` | Digital signage slides | dsLoop |
| `comeback_cash` | Comeback Cash event | ccEvents |
| `task` | Staff task | tasks |
| `note` | Workbook note | workbook_notes |

---

## Event Phases

Events automatically transition through phases based on current date:

| Phase | Description | Timing |
|-------|-------------|--------|
| `upcoming` | Before build-up starts | > buildUpDays before startDate |
| `build_up` | Preparation period | buildUpDays before startDate |
| `active` | Event is live | startDate to endDate |
| `wind_down` | Post-event period | endDate to endDate + windDownDays |
| `completed` | Event concluded | After wind_down |
