> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vchata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Campaigns Controller

> Campaign creation, management, and automation API endpoints

# Campaigns Controller

The Campaigns Controller provides comprehensive campaign management capabilities including multi-platform campaign creation, keyword management, AI agent configuration, and automated lead generation for the VChata platform.

## Base Path

```
/campaigns
```

## Overview

This controller enables sophisticated campaign automation:

* 🎯 **Multi-Platform Campaigns** - Create campaigns across Instagram, Facebook, TikTok, and more
* 🤖 **AI Agent Integration** - Configure intelligent response agents for each platform
* 🔍 **Keyword Management** - Advanced keyword matching with priorities and conflict detection
* 📊 **Lead Generation** - Automated lead capture from social media interactions
* 🎭 **A/B Testing** - Support for testing different campaign variations
* 🔄 **Real-time Processing** - Live monitoring and response to social media activity

## Authentication & Authorization

* 🔐 All endpoints require valid JWT authentication token
* 🏢 All operations are scoped to the user's current organization
* 👥 Organization membership required for all operations

## Campaign Management

### Create Campaign

<RequestExample>
  ```http theme={null}
  POST /campaigns/org_abc123
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "name": "Summer Sale 2024",
    "description": "Promote summer products across all platforms",
    "pipelineId": "pipeline_789",
    "platform": "FACEBOOK",
    "socialAccountIds": ["social_123", "social_456"],
    "keywords": [
      {
        "keyword": "summer sale",
        "matchType": "EXACT",
        "priority": 1
      },
      {
        "keyword": "discount",
        "matchType": "CONTAINS",
        "priority": 2
      }
    ],
    "agentConfigs": [
      {
        "channel": "DIRECT_MESSAGE",
        "promptTemplateId": "template_123",
        "autoResponse": true,
        "responseDelay": 30
      },
      {
        "channel": "COMMENT",
        "promptTemplateId": "template_456",
        "autoResponse": true,
        "responseDelay": 60
      }
    ],
    "webhookUrl": "https://api.example.com/webhooks/campaigns",
    "utmSource": "summer_campaign",
    "utmMedium": "social",
    "utmCampaign": "summer_2024"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "campaign": {
      "id": "campaign_123",
      "name": "Summer Sale 2024",
      "description": "Promote summer products across all platforms",
      "organizationId": "org_abc123",
      "pipelineId": "pipeline_789",
      "platform": "FACEBOOK",
      "socialAccountIds": ["social_123", "social_456"],
      "keywords": [
        {
          "id": "keyword_123",
          "keyword": "summer sale",
          "matchType": "EXACT",
          "priority": 1,
          "createdAt": "2024-01-15T10:30:00Z"
        },
        {
          "id": "keyword_456",
          "keyword": "discount",
          "matchType": "CONTAINS",
          "priority": 2,
          "createdAt": "2024-01-15T10:30:00Z"
        }
      ],
      "agentConfigs": [
        {
          "id": "agent_config_123",
          "channel": "DIRECT_MESSAGE",
          "promptTemplateId": "template_123",
          "autoResponse": true,
          "responseDelay": 30,
          "createdAt": "2024-01-15T10:30:00Z"
        }
      ],
      "webhookUrl": "https://api.example.com/webhooks/campaigns",
      "utmSource": "summer_campaign",
      "utmMedium": "social",
      "utmCampaign": "summer_2024",
      "status": "ACTIVE",
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    },
    "message": "Campaign created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates a comprehensive multi-platform campaign with AI agent configuration and keyword management.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="name" type="string" required>
      Campaign name (2-100 characters)
    </ParamField>

    <ParamField path="description" type="string">
      Campaign description (optional)
    </ParamField>

    <ParamField path="pipelineId" type="string" required>
      ID of the pipeline to associate with the campaign
    </ParamField>

    <ParamField path="platform" type="string" required>
      Primary platform (FACEBOOK, INSTAGRAM, TIKTOK, etc.)
    </ParamField>

    <ParamField path="socialAccountIds" type="array" required>
      Array of social account IDs to associate with the campaign
    </ParamField>

    <ParamField path="keywords" type="array">
      Array of keyword objects for trigger-based engagement

      <ParamField path="keyword" type="string" required>
        The keyword to match
      </ParamField>

      <ParamField path="matchType" type="string" required>
        Match type (EXACT, CONTAINS, STARTS\_WITH, ENDS\_WITH)
      </ParamField>

      <ParamField path="priority" type="number" required>
        Priority level (1 = highest)
      </ParamField>
    </ParamField>

    <ParamField path="agentConfigs" type="array">
      Array of AI agent configurations

      <ParamField path="channel" type="string" required>
        Channel type (DIRECT\_MESSAGE, COMMENT, POST)
      </ParamField>

      <ParamField path="promptTemplateId" type="string" required>
        ID of the prompt template to use
      </ParamField>

      <ParamField path="autoResponse" type="boolean">
        Whether to automatically respond (default: true)
      </ParamField>

      <ParamField path="responseDelay" type="number">
        Delay in seconds before responding (default: 0)
      </ParamField>
    </ParamField>

    <ParamField path="webhookUrl" type="string">
      Webhook URL for campaign events
    </ParamField>

    <ParamField path="utmSource" type="string">
      UTM source parameter
    </ParamField>

    <ParamField path="utmMedium" type="string">
      UTM medium parameter
    </ParamField>

    <ParamField path="utmCampaign" type="string">
      UTM campaign parameter
    </ParamField>
  </Expandable>
</ParamField>

### Get All Campaigns

<RequestExample>
  ```http theme={null}
  GET /campaigns/org_abc123?platform=FACEBOOK&status=ACTIVE&page=1&limit=10
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "campaigns": [
      {
        "id": "campaign_123",
        "name": "Summer Sale 2024",
        "description": "Promote summer products across all platforms",
        "organizationId": "org_abc123",
        "pipelineId": "pipeline_789",
        "platform": "FACEBOOK",
        "socialAccountIds": ["social_123", "social_456"],
        "keywords": [
          {
            "id": "keyword_123",
            "keyword": "summer sale",
            "matchType": "EXACT",
            "priority": 1
          }
        ],
        "agentConfigs": [
          {
            "id": "agent_config_123",
            "channel": "DIRECT_MESSAGE",
            "promptTemplateId": "template_123",
            "autoResponse": true,
            "responseDelay": 30
          }
        ],
        "status": "ACTIVE",
        "leadCount": 45,
        "conversionRate": 12.5,
        "createdAt": "2024-01-15T10:30:00Z",
        "updatedAt": "2024-01-20T15:30:00Z"
      }
    ],
    "pagination": {
      "total": 1,
      "page": 1,
      "limit": 10,
      "hasMore": false
    },
    "message": "Campaigns retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves all campaigns for the organization with optional filtering and pagination.

<ParamField path="query" type="object">
  <Expandable title="Query Parameters">
    <ParamField path="pipelineId" type="string">
      Filter by pipeline ID
    </ParamField>

    <ParamField path="socialAccountIds" type="string">
      Filter by social account IDs (comma-separated)
    </ParamField>

    <ParamField path="platform" type="string">
      Filter by platform (FACEBOOK, INSTAGRAM, TIKTOK, etc.)
    </ParamField>

    <ParamField path="status" type="string">
      Filter by status (ACTIVE, PAUSED, COMPLETED, DRAFT)
    </ParamField>

    <ParamField path="search" type="string">
      Search in campaign name and description
    </ParamField>

    <ParamField path="page" type="number">
      Page number for pagination (default: 1)
    </ParamField>

    <ParamField path="limit" type="number">
      Number of items per page (default: 10, max: 100)
    </ParamField>
  </Expandable>
</ParamField>

### Get Campaign Details

<RequestExample>
  ```http theme={null}
  GET /campaigns/org_abc123/campaign_123
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "campaign": {
      "id": "campaign_123",
      "name": "Summer Sale 2024",
      "description": "Promote summer products across all platforms",
      "organizationId": "org_abc123",
      "pipelineId": "pipeline_789",
      "platform": "FACEBOOK",
      "socialAccountIds": ["social_123", "social_456"],
      "keywords": [
        {
          "id": "keyword_123",
          "keyword": "summer sale",
          "matchType": "EXACT",
          "priority": 1,
          "createdAt": "2024-01-15T10:30:00Z"
        }
      ],
      "agentConfigs": [
        {
          "id": "agent_config_123",
          "channel": "DIRECT_MESSAGE",
          "promptTemplateId": "template_123",
          "autoResponse": true,
          "responseDelay": 30,
          "promptTemplate": {
            "id": "template_123",
            "name": "Sales Response Template",
            "content": "Thank you for your interest in our summer sale!"
          }
        }
      ],
      "webhookUrl": "https://api.example.com/webhooks/campaigns",
      "utmSource": "summer_campaign",
      "utmMedium": "social",
      "utmCampaign": "summer_2024",
      "status": "ACTIVE",
      "leadCount": 45,
      "conversionRate": 12.5,
      "totalInteractions": 1250,
      "averageResponseTime": 2.5,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-20T15:30:00Z"
    },
    "message": "Campaign retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves detailed information about a specific campaign including performance metrics.

### Update Campaign

<RequestExample>
  ```http theme={null}
  PATCH /campaigns/org_abc123/campaign_123
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "name": "Summer Sale 2024 - Updated",
    "description": "Updated description with new features",
    "keywords": [
      {
        "keyword": "summer sale 2024",
        "matchType": "EXACT",
        "priority": 1
      }
    ],
    "agentConfigs": [
      {
        "channel": "DIRECT_MESSAGE",
        "promptTemplateId": "template_789",
        "autoResponse": true,
        "responseDelay": 45
      }
    ],
    "socialAccountIds": ["social_123", "social_456", "social_789"]
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "campaign": {
      "id": "campaign_123",
      "name": "Summer Sale 2024 - Updated",
      "description": "Updated description with new features",
      "keywords": [
        {
          "id": "keyword_789",
          "keyword": "summer sale 2024",
          "matchType": "EXACT",
          "priority": 1,
          "createdAt": "2024-01-20T16:00:00Z"
        }
      ],
      "agentConfigs": [
        {
          "id": "agent_config_456",
          "channel": "DIRECT_MESSAGE",
          "promptTemplateId": "template_789",
          "autoResponse": true,
          "responseDelay": 45,
          "createdAt": "2024-01-20T16:00:00Z"
        }
      ],
      "socialAccountIds": ["social_123", "social_456", "social_789"],
      "updatedAt": "2024-01-20T16:00:00Z"
    },
    "message": "Campaign updated successfully"
  }
  ```
</ResponseExample>

**Description**: Updates campaign details including keywords, agent configurations, and social account associations.

<Note>
  **Update Behavior**:

  * Keywords: Provide array to replace all keywords, empty array to remove all, omit to leave unchanged
  * Agent Configs: Provide array to replace all configs, empty array to remove all, omit to leave unchanged
  * Social Accounts: Provide array to replace all associations, empty array to remove all, omit to leave unchanged
</Note>

### Delete Campaign

<RequestExample>
  ```http theme={null}
  DELETE /campaigns/org_abc123/campaign_123
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Campaign deleted successfully"
  }
  ```
</ResponseExample>

**Description**: Permanently deletes a campaign and all associated data.

<Warning>
  **Irreversible Action**: Deleting a campaign will permanently remove all associated keywords, agent configurations, and historical data.
</Warning>

## Keyword Management

### Validate Keywords

<RequestExample>
  ```http theme={null}
  POST /campaigns/org_abc123/validate-keywords
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "keywords": [
      {
        "keyword": "summer sale",
        "matchType": "EXACT"
      },
      {
        "keyword": "discount",
        "matchType": "CONTAINS"
      }
    ]
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "validation": {
      "valid": true,
      "conflicts": [],
      "suggestions": [
        {
          "keyword": "summer sale",
          "suggestion": "Consider adding 'summer sale 2024' for better specificity",
          "type": "ENHANCEMENT"
        }
      ],
      "statistics": {
        "totalKeywords": 2,
        "exactMatches": 1,
        "containsMatches": 1,
        "estimatedCoverage": 85.5
      }
    },
    "message": "Keywords validated successfully"
  }
  ```
</ResponseExample>

**Description**: Validates keywords for conflicts and provides suggestions for optimization.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="keywords" type="array" required>
      Array of keyword objects to validate

      <ParamField path="keyword" type="string" required>
        The keyword to validate
      </ParamField>

      <ParamField path="matchType" type="string" required>
        Match type (EXACT, CONTAINS, STARTS\_WITH, ENDS\_WITH)
      </ParamField>
    </ParamField>
  </Expandable>
</ParamField>

### Get Organization Keywords

<RequestExample>
  ```http theme={null}
  GET /campaigns/org_abc123/keywords
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "keywords": [
      {
        "keyword": "summer sale",
        "matchType": "EXACT",
        "campaignId": "campaign_123",
        "campaignName": "Summer Sale 2024",
        "priority": 1,
        "createdAt": "2024-01-15T10:30:00Z"
      },
      {
        "keyword": "discount",
        "matchType": "CONTAINS",
        "campaignId": "campaign_456",
        "campaignName": "Discount Campaign",
        "priority": 2,
        "createdAt": "2024-01-16T09:00:00Z"
      }
    ],
    "total": 2,
    "message": "Organization keywords retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves all keywords across all campaigns in the organization.

## Campaign Status Values

* **DRAFT** - Campaign is being created/configured
* **ACTIVE** - Campaign is running and processing interactions
* **PAUSED** - Campaign is temporarily stopped
* **COMPLETED** - Campaign has finished
* **ARCHIVED** - Campaign is archived and no longer active

## Match Types

* **EXACT** - Exact keyword match
* **CONTAINS** - Keyword is contained within the text
* **STARTS\_WITH** - Text starts with the keyword
* **ENDS\_WITH** - Text ends with the keyword

## Channel Types

* **DIRECT\_MESSAGE** - Private messages/DMs
* **COMMENT** - Public comments on posts
* **POST** - Direct posts (for posting content)

## Error Responses

### Common Errors

<ResponseExample status="409">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 409,
    "message": "Keyword 'summer sale' already exists in campaign 'Existing Campaign'",
    "error": "Conflict",
    "conflictingCampaign": {
      "id": "campaign_456",
      "name": "Existing Campaign"
    }
  }
  ```
</ResponseExample>

<ResponseExample status="400">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 400,
    "message": [
      "name is required",
      "pipelineId must be a valid UUID",
      "platform must be one of: FACEBOOK, INSTAGRAM, TIKTOK"
    ],
    "error": "Bad Request"
  }
  ```
</ResponseExample>

<ResponseExample status="404">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 404,
    "message": "Campaign not found or you don't have access",
    "error": "Not Found"
  }
  ```
</ResponseExample>

## Advanced Features

### Multi-Platform Support

* **Cross-Platform Campaigns** - Run campaigns across multiple social media platforms
* **Platform-Specific Agents** - Different AI agents for each platform
* **Unified Lead Management** - All leads funnel into the same pipeline

### Keyword Priority System

* **Priority Levels** - Keywords with higher priority (lower numbers) are processed first
* **Conflict Resolution** - Automatic conflict detection and resolution
* **Smart Matching** - Advanced matching algorithms for better targeting

### AI Agent Configuration

* **Channel-Specific Responses** - Different responses for DMs vs comments
* **Response Delays** - Configurable delays to appear more human
* **Template Management** - Reusable prompt templates across campaigns

### Webhook Integration

* **Real-time Events** - Webhook notifications for campaign events
* **Lead Notifications** - Instant notifications when leads are generated
* **Performance Metrics** - Real-time campaign performance data

### UTM Tracking

* **Campaign Attribution** - Track which campaigns generate leads
* **Source Identification** - Identify the best performing traffic sources
* **ROI Measurement** - Measure return on investment for each campaign
