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

# Tracking Leads

## Monitor Lead Performance

<Info>
  **Note:** Lead tracking endpoints are only available for certain partners with organization-level access. Contact [joel@venturu.com](mailto:joel@venturu.com) to enable this feature.
</Info>

Track how many leads your organization and offices are receiving from Venturu. Perfect for monitoring performance and ROI.

## Two Levels of Tracking

<CardGroup cols={2}>
  <Card title="Office Level" icon="building" href="#office-level-leads">
    Get lead counts for a specific office
  </Card>

  <Card title="Organization Level" icon="sitemap" href="#organization-level-leads">
    Get totals across all offices with breakdowns
  </Card>
</CardGroup>

## Office Level Leads

Get the total number of leads for a specific office, optionally filtered by date range.

**Endpoint:** `GET /partner/v1/offices/{officeId}/leads/count`

### Basic Request

```bash Get all leads for an office theme={null}
curl -X GET "https://www.venturu.com/api/partner/v1/offices/12345/leads/count" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response

```json theme={null}
{
  "status": "success",
  "officeId": 12345,
  "officeName": "Downtown Miami Office",
  "totalLeads": 247
}
```

### Filter by Date Range

Add query parameters to filter leads within a specific time period:

<CodeGroup>
  ```bash Last 30 Days theme={null}
  curl -X GET "https://www.venturu.com/api/partner/v1/offices/12345/leads/count?startDate=2024-10-01T00:00:00Z&endDate=2024-10-31T23:59:59Z" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash This Month theme={null}
  # Get current month's leads
  START_DATE=$(date -u +"%Y-%m-01T00:00:00Z")
  END_DATE=$(date -u +"%Y-%m-%dT23:59:59Z")

  curl -X GET "https://www.venturu.com/api/partner/v1/offices/12345/leads/count?startDate=${START_DATE}&endDate=${END_DATE}" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```python Python theme={null}
  import requests
  from datetime import datetime, timedelta
  import os

  # Last 30 days
  end_date = datetime.utcnow()
  start_date = end_date - timedelta(days=30)

  url = "https://www.venturu.com/api/partner/v1/offices/12345/leads/count"
  params = {
      "startDate": start_date.isoformat() + "Z",
      "endDate": end_date.isoformat() + "Z"
  }

  response = requests.get(
      url,
      params=params,
      headers={"Authorization": f"Bearer {os.getenv('VENTURU_API_KEY')}"}
  )

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - 30);

  const params = new URLSearchParams({
    startDate: startDate.toISOString(),
    endDate: endDate.toISOString()
  });

  const response = await fetch(
    `https://www.venturu.com/api/partner/v1/offices/12345/leads/count?${params}`,
    {
      headers: {
        'Authorization': `Bearer ${process.env.VENTURU_API_KEY}`
      }
    }
  );

  const data = await response.json();
  console.log(data);
  ```
</CodeGroup>

## Organization Level Leads

Get lead counts across your entire organization, with optional breakdown by office.

**Endpoint:** `GET /partner/v1/organizations/{organizationId}/leads/count`

### Basic Request

```bash Get all organizational leads theme={null}
curl -X GET "https://www.venturu.com/api/partner/v1/organizations/789/leads/count" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response

```json theme={null}
{
  "status": "success",
  "organizationId": 789,
  "organizationName": "ABC Realty Group",
  "totalLeads": 1523,
  "officeBreakdown": [
    {
      "officeId": 12345,
      "officeName": "Downtown Miami Office",
      "totalLeads": 247
    },
    {
      "officeId": 12346,
      "officeName": "Boca Raton Office",
      "totalLeads": 189
    },
    {
      "officeId": 12347,
      "officeName": "Fort Lauderdale Office",
      "totalLeads": 312
    }
  ]
}
```

### Filter by Date Range

<CodeGroup>
  ```bash Last Quarter theme={null}
  curl -X GET "https://www.venturu.com/api/partner/v1/organizations/789/leads/count?startDate=2024-07-01T00:00:00Z&endDate=2024-09-30T23:59:59Z" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```python Python - Monthly Report theme={null}
  import requests
  from datetime import datetime
  from calendar import monthrange
  import os

  def get_monthly_leads(org_id, year, month):
      # Calculate first and last day of month
      first_day = datetime(year, month, 1)
      last_day_num = monthrange(year, month)[1]
      last_day = datetime(year, month, last_day_num, 23, 59, 59)
      
      url = f"https://www.venturu.com/api/partner/v1/organizations/{org_id}/leads/count"
      params = {
          "startDate": first_day.isoformat() + "Z",
          "endDate": last_day.isoformat() + "Z"
      }
      
      response = requests.get(
          url,
          params=params,
          headers={"Authorization": f"Bearer {os.getenv('VENTURU_API_KEY')}"}
      )
      
      return response.json()

  # Get October 2024 leads
  leads = get_monthly_leads(789, 2024, 10)
  print(f"Total leads in October: {leads['totalLeads']}")
  ```
</CodeGroup>

## Query Parameters

Both endpoints support the same optional query parameters:

<ParamField query="startDate" type="string" optional>
  Start date for filtering leads (ISO 8601 format: `2024-10-01T00:00:00Z`)

  * If not provided, returns all leads from the beginning
  * Must be a valid ISO 8601 datetime string
  * Timezone aware (use UTC for consistency)
</ParamField>

<ParamField query="endDate" type="string" optional>
  End date for filtering leads (ISO 8601 format: `2024-10-31T23:59:59Z`)

  * If not provided, defaults to current date/time
  * Must be a valid ISO 8601 datetime string
  * Timezone aware (use UTC for consistency)
</ParamField>

## Date Format

All dates must be in **ISO 8601 format**:

<CodeGroup>
  ```text Format theme={null}
  YYYY-MM-DDTHH:MM:SSZ
  ```

  ```text Examples theme={null}
  2024-10-01T00:00:00Z  ← Start of October 1, 2024 (UTC)
  2024-10-31T23:59:59Z  ← End of October 31, 2024 (UTC)
  2024-01-15T12:30:00Z  ← January 15, 2024 at 12:30 PM (UTC)
  ```
</CodeGroup>

<Tip>
  **Pro Tip:** Always use UTC timezone (ending with `Z`) to avoid timezone confusion across different systems.
</Tip>

## Common Use Cases

### Monthly Performance Report

```python theme={null}
# Get leads for each month of the quarter
import requests
from datetime import datetime
import os

def get_leads_for_month(org_id, year, month):
    # Calculate month boundaries
    if month == 12:
        next_month = datetime(year + 1, 1, 1)
    else:
        next_month = datetime(year, month + 1, 1)
    
    start = datetime(year, month, 1)
    end = next_month - timedelta(seconds=1)
    
    params = {
        "startDate": start.isoformat() + "Z",
        "endDate": end.isoformat() + "Z"
    }
    
    response = requests.get(
        f"https://www.venturu.com/api/partner/v1/organizations/{org_id}/leads/count",
        params=params,
        headers={"Authorization": f"Bearer {os.getenv('VENTURU_API_KEY')}"}
    )
    
    return response.json()

# Q4 2024 Report
q4_months = [10, 11, 12]
for month in q4_months:
    data = get_leads_for_month(789, 2024, month)
    print(f"Month {month}: {data['totalLeads']} leads")
```

### Compare Office Performance

```javascript theme={null}
// Get and compare multiple offices
async function compareOffices(officeIds, startDate, endDate) {
  const params = new URLSearchParams({
    startDate: startDate.toISOString(),
    endDate: endDate.toISOString()
  });

  const results = await Promise.all(
    officeIds.map(async (officeId) => {
      const response = await fetch(
        `https://www.venturu.com/api/partner/v1/offices/${officeId}/leads/count?${params}`,
        {
          headers: {
            'Authorization': `Bearer ${process.env.VENTURU_API_KEY}`
          }
        }
      );
      return response.json();
    })
  );

  // Sort by performance
  results.sort((a, b) => b.totalLeads - a.totalLeads);
  
  console.log('Top Performing Offices:');
  results.forEach((office, index) => {
    console.log(`${index + 1}. ${office.officeName}: ${office.totalLeads} leads`);
  });
}

// Compare last 30 days
const end = new Date();
const start = new Date();
start.setDate(start.getDate() - 30);

compareOffices([12345, 12346, 12347], start, end);
```

### Year-to-Date Tracking

```bash theme={null}
# Get all leads from January 1 to now
START_OF_YEAR=$(date -u +"%Y-01-01T00:00:00Z")
NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

curl -X GET "https://www.venturu.com/api/partner/v1/organizations/789/leads/count?startDate=${START_OF_YEAR}&endDate=${NOW}" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

## Error Handling

<AccordionGroup>
  <Accordion title="400 Bad Request" icon="triangle-exclamation">
    Invalid query parameters or date format.

    ```json theme={null}
    {
      "status": "error",
      "error": "Invalid query parameters. Dates must be in ISO 8601 format."
    }
    ```

    **Solutions:**

    * Check date format is ISO 8601: `YYYY-MM-DDTHH:MM:SSZ`
    * Ensure dates include timezone (use `Z` for UTC)
    * Verify `startDate` is before `endDate`
  </Accordion>

  <Accordion title="401 Unauthorized" icon="lock">
    Missing or invalid API key, or insufficient permissions.

    ```json theme={null}
    {
      "status": "error",
      "error": "Unauthorized"
    }
    ```

    **Solutions:**

    * Verify your API key is correct
    * Check that your key has lead tracking permissions
    * Contact [joel@venturu.com](mailto:joel@venturu.com) to enable this feature
  </Accordion>

  <Accordion title="404 Not Found" icon="magnifying-glass">
    Office or organization doesn't exist or you don't have access.

    ```json theme={null}
    {
      "status": "error",
      "error": "Office not found"
    }
    ```

    **Solutions:**

    * Verify the office/organization ID is correct
    * Check that the office belongs to your organization
    * Ensure you're using the Venturu ID, not your external ID
  </Accordion>
</AccordionGroup>

## Best Practices

<CardGroup cols={2}>
  <Card title="Use UTC Timezone" icon="clock">
    Always use UTC (Z suffix) for consistent cross-system reporting.
  </Card>

  <Card title="Cache Results" icon="database">
    Lead counts don't change retroactively. Cache historical data.
  </Card>

  <Card title="Batch Requests" icon="layer-group">
    Use organization endpoint instead of multiple office calls.
  </Card>

  <Card title="Regular Intervals" icon="calendar">
    Pull data on a schedule (daily/weekly) for trend analysis.
  </Card>
</CardGroup>

## Common Questions

<AccordionGroup>
  <Accordion title="What counts as a lead?" icon="circle-question">
    A lead is created when a buyer expresses interest in a listing through:

    * Direct contact form submission
    * Phone inquiries (if tracked)
    * Email inquiries to the broker
  </Accordion>

  <Accordion title="Can I get individual lead details?" icon="circle-question">
    Currently, the API only provides lead **counts** and statistics. Individual lead details (names, emails, messages) are not available through the API for privacy reasons.
  </Accordion>

  <Accordion title="How often is data updated?" icon="circle-question">
    Lead counts update in real-time. When you query the API, you get the current count for your specified date range.
  </Accordion>

  <Accordion title="What if I don't have an organizationId?" icon="circle-question">
    Contact [joel@venturu.com](mailto:joel@venturu.com). The organization ID is provided during partnership setup for partners with this feature enabled.
  </Accordion>

  <Accordion title="Can I get leads for all my offices at once?" icon="circle-question">
    Yes! Use the organization endpoint - it returns total leads plus a breakdown by each office automatically.
  </Accordion>
</AccordionGroup>

## Integration Example

Here's a complete example building a simple lead dashboard:

```python Complete Dashboard Example theme={null}
import requests
from datetime import datetime, timedelta
import os

API_KEY = os.getenv('VENTURU_API_KEY')
BASE_URL = "https://www.venturu.com/api/partner/v1"
ORG_ID = 789

def get_leads_by_period(org_id, start_date, end_date):
    """Get leads for a specific date range."""
    params = {
        "startDate": start_date.isoformat() + "Z",
        "endDate": end_date.isoformat() + "Z"
    }
    
    response = requests.get(
        f"{BASE_URL}/organizations/{org_id}/leads/count",
        params=params,
        headers={"Authorization": f"Bearer {API_KEY}"}
    )
    
    return response.json()

# Generate monthly report for Q4 2024
months = [
    ("October", datetime(2024, 10, 1), datetime(2024, 10, 31, 23, 59, 59)),
    ("November", datetime(2024, 11, 1), datetime(2024, 11, 30, 23, 59, 59)),
    ("December", datetime(2024, 12, 1), datetime(2024, 12, 31, 23, 59, 59)),
]

print("=== Q4 2024 Lead Report ===\n")

for month_name, start, end in months:
    data = get_leads_by_period(ORG_ID, start, end)
    
    print(f"{month_name} {start.year}")
    print(f"Total Leads: {data['totalLeads']}")
    print("\nOffice Breakdown:")
    
    for office in data['officeBreakdown']:
        print(f"  - {office['officeName']}: {office['totalLeads']} leads")
    
    print("\n" + "-" * 50 + "\n")
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Create a Broker" icon="user-plus" href="./creating-a-broker">
    Set up brokers to receive leads
  </Card>

  <Card title="Create a Listing" icon="circle-plus" href="./creating-a-listing">
    Create listings to generate leads
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference">
    Full API documentation
  </Card>

  <Card title="Contact Support" icon="envelope" href="mailto:joel@venturu.com">
    Enable lead tracking
  </Card>
</CardGroup>
