> ## 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.

# Leads Controller

> Lead management, tracking, and conversion pipeline API endpoints

# Leads Controller

The Leads Controller provides comprehensive lead management capabilities including lead creation, tracking, pipeline management, conversion tracking, and analytics for the VChata platform.

## Base Path

```
/leads
```

## Overview

This controller enables complete lead lifecycle management:

* 🎯 **Lead Creation** - Create leads from contacts or social interactions
* 📊 **Pipeline Management** - Move leads through customizable stages
* 🔄 **Conversion Tracking** - Track conversions and attribution
* 📈 **Analytics** - Comprehensive lead analytics and reporting
* 🎭 **Activity Tracking** - Log and track lead interactions
* 🔗 **Social Integration** - Connect leads to social media interactions

## 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

## Lead Management

### Create Lead

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

  {
    "contactId": "contact_456",
    "pipelineId": "pipeline_789",
    "source": "website",
    "value": 1000,
    "notes": "Interested in premium package",
    "utmSource": "google",
    "utmMedium": "cpc",
    "utmCampaign": "premium_ads"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "lead": {
      "id": "lead_123",
      "contactId": "contact_456",
      "pipelineId": "pipeline_789",
      "stageId": "clxyz123456789abcdef",
      "source": "website",
      "value": 1000,
      "status": "NEW",
      "notes": "Interested in premium package",
      "utmSource": "google",
      "utmMedium": "cpc",
      "utmCampaign": "premium_ads",
      "createdAt": "2024-01-15T10:30:00Z"
    },
    "message": "Lead created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates a new lead for an existing contact in the system.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="contactId" type="string" required>
      ID of the existing contact
    </ParamField>

    <ParamField path="pipelineId" type="string" required>
      ID of the pipeline to add the lead to
    </ParamField>

    <ParamField path="source" type="string" required>
      Lead source (website, social, referral, etc.)
    </ParamField>

    <ParamField path="value" type="number">
      Estimated lead value in cents
    </ParamField>

    <ParamField path="notes" type="string">
      Additional notes about the lead
    </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>

### Create Lead with Contact

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

  {
    "contact": {
      "name": "John Doe",
      "email": "john@example.com",
      "phone": "+1234567890",
      "company": "Acme Corp"
    },
    "pipelineId": "pipeline_789",
    "source": "website",
    "value": 1000,
    "notes": "New lead from contact form"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "lead": {
      "id": "lead_123",
      "contactId": "contact_456",
      "pipelineId": "pipeline_789",
      "stageId": "clxyz123456789abcdef",
      "source": "website",
      "value": 1000,
      "status": "NEW",
      "createdAt": "2024-01-15T10:30:00Z"
    },
    "contact": {
      "id": "contact_456",
      "name": "John Doe",
      "email": "john@example.com",
      "phone": "+1234567890",
      "company": "Acme Corp",
      "createdAt": "2024-01-15T10:30:00Z"
    },
    "message": "Lead and contact created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates both a new contact and lead in a single request.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="contact" type="object" required>
      <ParamField path="name" type="string" required>
        Contact's full name
      </ParamField>

      <ParamField path="email" type="string" required>
        Contact's email address
      </ParamField>

      <ParamField path="phone" type="string">
        Contact's phone number
      </ParamField>

      <ParamField path="company" type="string">
        Contact's company name
      </ParamField>
    </ParamField>

    <ParamField path="pipelineId" type="string" required>
      ID of the pipeline to add the lead to
    </ParamField>

    <ParamField path="source" type="string" required>
      Lead source (website, social, referral, etc.)
    </ParamField>

    <ParamField path="value" type="number">
      Estimated lead value in cents
    </ParamField>

    <ParamField path="notes" type="string">
      Additional notes about the lead
    </ParamField>
  </Expandable>
</ParamField>

### Get All Leads

<RequestExample>
  ```http theme={null}
  GET /leads/org_abc123?pipelineId=pipeline_789&status=QUALIFIED&page=1&limit=10
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "leads": [
      {
        "id": "lead_123",
        "contactId": "contact_456",
        "pipelineId": "pipeline_789",
        "stageId": "clxyz987654321fedcba",
        "source": "website",
        "value": 1500,
        "status": "QUALIFIED",
        "assignedToId": "user_789",
        "contact": {
          "id": "contact_456",
          "name": "John Doe",
          "email": "john@example.com",
          "phone": "+1234567890",
          "company": "Acme Corp"
        },
        "pipeline": {
          "id": "pipeline_789",
          "name": "Sales Pipeline",
          "stages": [
            {
              "id": "clxyz987654321fedcba",
              "name": "Qualified",
              "order": 2
            }
          ]
        },
        "socialAccount": {
          "id": "social_123",
          "platform": "FACEBOOK",
          "platformId": "123456789",
          "name": "Acme Corp Facebook"
        },
        "contentPost": {
          "id": "post_456",
          "platformPostId": "987654321",
          "content": "Check out our new product!",
          "url": "https://facebook.com/posts/987654321"
        },
        "createdAt": "2024-01-15T10:30:00Z",
        "updatedAt": "2024-01-20T15:30:00Z"
      }
    ],
    "pagination": {
      "total": 1,
      "page": 1,
      "limit": 10,
      "hasMore": false
    },
    "message": "Leads retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves all leads 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="status" type="string">
      Filter by lead status (NEW, QUALIFIED, CONTACTED, CONVERTED, LOST)
    </ParamField>

    <ParamField path="assignedToId" type="string">
      Filter by assigned user ID
    </ParamField>

    <ParamField path="stageId" type="string">
      Filter by stage ID
    </ParamField>

    <ParamField path="source" type="string">
      Filter by lead source
    </ParamField>

    <ParamField path="socialAccountId" type="string">
      Filter by social account ID
    </ParamField>

    <ParamField path="contentPostId" type="string">
      Filter by content post ID
    </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 Lead Details

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

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "lead": {
      "id": "lead_123",
      "contactId": "contact_456",
      "pipelineId": "pipeline_789",
      "stageId": "clxyz987654321fedcba",
      "source": "website",
      "value": 1500,
      "status": "QUALIFIED",
      "assignedToId": "user_789",
      "notes": "Interested in premium package",
      "utmSource": "google",
      "utmMedium": "cpc",
      "utmCampaign": "premium_ads",
      "converted": false,
      "convertedAt": null,
      "contact": {
        "id": "contact_456",
        "name": "John Doe",
        "email": "john@example.com",
        "phone": "+1234567890",
        "company": "Acme Corp"
      },
      "pipeline": {
        "id": "pipeline_789",
        "name": "Sales Pipeline"
      },
      "stage": {
        "id": "clxyz987654321fedcba",
        "name": "Qualified",
        "order": 2
      },
      "activities": [
        {
          "id": "activity_123",
          "type": "EMAIL_SENT",
          "description": "Follow-up email sent",
          "createdAt": "2024-01-16T10:00:00Z"
        }
      ],
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-20T15:30:00Z"
    },
    "message": "Lead retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves detailed information about a specific lead including activities and related data.

### Update Lead

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

  {
    "value": 2000,
    "status": "CONTACTED",
    "assignedToId": "user_456",
    "notes": "Updated notes after phone call"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "lead": {
      "id": "lead_123",
      "value": 2000,
      "status": "CONTACTED",
      "assignedToId": "user_456",
      "notes": "Updated notes after phone call",
      "updatedAt": "2024-01-20T16:00:00Z"
    },
    "message": "Lead updated successfully"
  }
  ```
</ResponseExample>

**Description**: Updates lead information including status, value, assignment, and notes.

### Delete Lead

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

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

**Description**: Permanently deletes a lead from the system.

## Lead Activities

### Add Lead Activity

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

  {
    "type": "EMAIL_SENT",
    "description": "Follow-up email sent regarding pricing",
    "metadata": {
      "emailSubject": "Re: Your inquiry about our services",
      "emailId": "email_789"
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "activity": {
      "id": "activity_123",
      "leadId": "lead_123",
      "type": "EMAIL_SENT",
      "description": "Follow-up email sent regarding pricing",
      "metadata": {
        "emailSubject": "Re: Your inquiry about our services",
        "emailId": "email_789"
      },
      "createdAt": "2024-01-20T16:00:00Z"
    },
    "message": "Activity added successfully"
  }
  ```
</ResponseExample>

**Description**: Adds an activity record to track interactions with the lead.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="type" type="string" required>
      Activity type (EMAIL\_SENT, PHONE\_CALL, MEETING, NOTE, etc.)
    </ParamField>

    <ParamField path="description" type="string" required>
      Description of the activity
    </ParamField>

    <ParamField path="metadata" type="object">
      Additional metadata for the activity
    </ParamField>
  </Expandable>
</ParamField>

## Pipeline Management

### Move Lead to Stage

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

  {
    "stageId": "clxyz111222333444555",
    "notes": "Lead moved to qualified stage after initial contact"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "lead": {
      "id": "lead_123",
      "stageId": "clxyz111222333444555",
      "status": "QUALIFIED",
      "updatedAt": "2024-01-20T16:00:00Z"
    },
    "message": "Lead moved to new stage successfully"
  }
  ```
</ResponseExample>

**Description**: Moves a lead to a different stage in the pipeline.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="stageId" type="string" required>
      ID of the new stage to move the lead to
    </ParamField>

    <ParamField path="notes" type="string">
      Optional notes about the stage change
    </ParamField>
  </Expandable>
</ParamField>

## Conversion Management

### Convert Conversation to Lead

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

  {
    "conversationId": "conv_123",
    "pipelineId": "pipeline_789",
    "source": "social_media",
    "value": 1500,
    "notes": "Converted from Instagram DM conversation"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "lead": {
      "id": "lead_456",
      "contactId": "contact_789",
      "pipelineId": "pipeline_789",
      "source": "social_media",
      "value": 1500,
      "status": "NEW",
      "createdAt": "2024-01-20T16:00:00Z"
    },
    "contact": {
      "id": "contact_789",
      "name": "Jane Smith",
      "email": "jane@example.com",
      "phone": "+1987654321"
    },
    "message": "Conversation converted to lead successfully"
  }
  ```
</ResponseExample>

**Description**: Converts a conversation (from social media, chat, etc.) into a lead.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="conversationId" type="string" required>
      ID of the conversation to convert
    </ParamField>

    <ParamField path="pipelineId" type="string" required>
      ID of the pipeline to add the lead to
    </ParamField>

    <ParamField path="source" type="string" required>
      Lead source (social\_media, chat, email, etc.)
    </ParamField>

    <ParamField path="value" type="number">
      Estimated lead value in cents
    </ParamField>

    <ParamField path="notes" type="string">
      Additional notes about the conversion
    </ParamField>
  </Expandable>
</ParamField>

## Analytics

### Get Lead Statistics

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

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "stats": {
      "totalLeads": 150,
      "newLeads": 25,
      "qualifiedLeads": 45,
      "contactedLeads": 30,
      "convertedLeads": 15,
      "lostLeads": 5,
      "conversionRate": 10.0,
      "averageValue": 1250,
      "totalValue": 187500
    },
    "message": "Lead statistics retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves comprehensive lead statistics and metrics.

### Get Source Analytics

<RequestExample>
  ```http theme={null}
  GET /leads/org_abc123/analytics/sources
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "sources": [
      {
        "source": "website",
        "count": 75,
        "conversionRate": 12.0,
        "averageValue": 1100,
        "totalValue": 82500
      },
      {
        "source": "social_media",
        "count": 45,
        "conversionRate": 8.9,
        "averageValue": 1400,
        "totalValue": 63000
      }
    ],
    "message": "Source analytics retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves analytics broken down by lead source.

### Get Campaign Analytics

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

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "campaigns": [
      {
        "campaignId": "campaign_123",
        "campaignName": "Summer Sale 2024",
        "leadCount": 30,
        "conversionRate": 15.0,
        "averageValue": 1800,
        "totalValue": 54000
      }
    ],
    "message": "Campaign analytics retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves analytics broken down by campaign.

### Get Pipeline Analytics

<RequestExample>
  ```http theme={null}
  GET /leads/org_abc123/analytics/pipeline
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "pipeline": {
      "id": "pipeline_789",
      "name": "Sales Pipeline",
      "stages": [
        {
          "id": "stage_1",
          "name": "New",
          "leadCount": 25,
          "averageTimeInStage": 2.5
        },
        {
          "id": "stage_2",
          "name": "Qualified",
          "leadCount": 45,
          "averageTimeInStage": 7.2
        },
        {
          "id": "stage_3",
          "name": "Contacted",
          "leadCount": 30,
          "averageTimeInStage": 14.1
        }
      ],
      "overallConversionRate": 10.0,
      "averageTimeToConvert": 23.8
    },
    "message": "Pipeline analytics retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves detailed pipeline analytics including stage performance and conversion metrics.

## Error Responses

### Common Errors

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

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

<ResponseExample status="409">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 409,
    "message": "Lead already exists for this contact and pipeline",
    "error": "Conflict"
  }
  ```
</ResponseExample>

## Lead Status Values

* **NEW** - Recently created lead
* **QUALIFIED** - Lead has been qualified as a potential customer
* **CONTACTED** - Initial contact has been made
* **CONVERTED** - Lead has been converted to a customer
* **LOST** - Lead is no longer viable

## Integration Features

* 🔗 **Social Media Integration** - Connect leads to social media interactions
* 📊 **UTM Tracking** - Track marketing campaign effectiveness
* 🎯 **Attribution** - Track lead sources and conversion paths
* 📈 **Real-time Analytics** - Live updates on lead performance
* 🔄 **Pipeline Automation** - Automatic stage progression rules
* 📧 **Activity Tracking** - Complete interaction history
* 🎭 **Custom Fields** - Extensible lead data structure
