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

# Zoho CRM Integration

> Complete guide to integrating Zoho CRM and importing your data into G-Tateth

The Zoho CRM integration allows you to connect your Zoho CRM account and import your existing data (contacts, deals, tickets, notes, and activities) into G-Tateth CRM.

<Note>
  All API endpoints are documented in the [API Reference](/api-reference) tab. This guide focuses on concepts, workflows, and integration examples.
</Note>

## Overview

With the Zoho CRM integration, you can:

* **Connect Zoho Accounts** - Securely connect multiple Zoho CRM accounts via OAuth 2.0
* **Import Historical Data** - Import contacts, deals, tickets, notes, and activities
* **Data Mapping** - Automatic mapping of Zoho fields to G-Tateth CRM entities
* **Incremental Imports** - Import data for specific date ranges
* **Progress Tracking** - Monitor import progress in real-time

## How It Works

### Data Flow

```
Zoho CRM → OAuth Connection → G-Tateth API → Import Job → Your CRM
```

1. **Connect**: Authorize G-Tateth to access your Zoho CRM account
2. **Configure**: Choose what data to import (contacts, deals, tickets, etc.)
3. **Import**: Data is imported asynchronously in the background
4. **Monitor**: Track progress and review results

### Data Mapping

**Zoho Contacts → G-Tateth Customers**

* Email, name, phone, company information
* Custom fields preserved in `customFields.zoho_*`

**Zoho Deals → G-Tateth Conversations**

* Deal name becomes conversation subject
* Deal stage mapped to conversation status
* Deal amount stored in metadata
* Notes imported as messages

**Zoho Tickets → G-Tateth Conversations**

* Ticket subject becomes conversation subject
* Ticket status and priority mapped
* Description and notes imported as messages

## Complete Integration Flow

Here's the complete flow for integrating Zoho CRM via API:

1. **Get OAuth URL** → `GET /api/zoho/connect`
2. **Redirect user** → User authorizes in Zoho
3. **OAuth callback** → Integration is created automatically
4. **Get Integration ID** → `GET /api/zoho/integrations` to retrieve the `_id`
5. **Use Integration ID** → Use `_id` in all subsequent API calls

## Quick Start

### 1. Connect Your Zoho Account

You can connect Zoho CRM through:

**Dashboard UI:**

1. Go to **Apps → Integrations**
2. Click **Connect Zoho CRM**
3. Authorize access in Zoho
4. Integration is connected automatically

**API:**

```bash theme={null}
# Step 1: Get OAuth URL
curl -X GET https://api.g-tateth.com/api/zoho/connect \
  -H "Authorization: Bearer sk_live_your_api_key"

# Response:
# {
#   "success": true,
#   "authUrl": "https://accounts.zoho.com/oauth/v2/auth?...",
#   "state": "eyJ0ZW5hbnRJZCI6..."
# }

# Step 2: Redirect user to authUrl
# User authorizes in Zoho, then Zoho redirects to your callback URL
# The integration is automatically created

# Step 3: Get Integration ID
# After OAuth callback completes, list integrations to get the ID
curl -X GET https://api.g-tateth.com/api/zoho/integrations \
  -H "Authorization: Bearer sk_live_your_api_key"

# Response:
# {
#   "success": true,
#   "data": [
#     {
#       "_id": "507f1f77bcf86cd799439011",  // This is your integration_id
#       "accountName": "My Zoho Account",
#       "accountEmail": "account@example.com",
#       "isActive": true,
#       ...
#     }
#   ]
# }
```

<Note>
  **Getting the Integration ID**: After the OAuth callback completes, call `GET /api/zoho/integrations` to retrieve the newly created integration. Use the `_id` field as the `integration_id` in subsequent API calls.
</Note>

### 2. Get Integration ID

After connecting, you need the `integration_id` to perform operations. Get it by listing all integrations:

```bash theme={null}
curl -X GET https://api.g-tateth.com/api/zoho/integrations \
  -H "Authorization: Bearer sk_live_your_api_key"
```

**Response:**

```json theme={null}
{
  "success": true,
  "data": [
    {
      "_id": "507f1f77bcf86cd799439011",  // Use this as integration_id
      "accountName": "My Zoho Account",
      "accountEmail": "account@example.com",
      "isActive": true,
      "lastSyncAt": "2024-01-01T12:00:00Z",
      "syncStatus": "idle"
    }
  ]
}
```

<Warning>
  **Multiple Integrations**: If you have multiple Zoho accounts connected, you'll see multiple items in the array. Use the `_id` of the integration you want to work with.
</Warning>

### 3. Start Importing Data

Once you have the `integration_id`, you can import your Zoho data:

**Via Dashboard:**

1. Go to **Settings → Integrations → Zoho**
2. Click **Start Import**
3. Select what to import (contacts, deals, tickets, etc.)
4. Optionally set a date range
5. Click **Start Import**

**Via API:**

```bash theme={null}
curl -X POST https://api.g-tateth.com/api/zoho/integrations/{integration_id}/import \
  -H "Authorization: Bearer sk_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "importContacts": true,
    "importDeals": true,
    "importTickets": true,
    "importNotes": true,
    "dateRange": {
      "startDate": "2024-01-01",
      "endDate": "2025-01-01"
    }
  }'
```

### 4. Monitor Import Progress

Imports run asynchronously. Check status:

```bash theme={null}
curl -X GET https://api.g-tateth.com/api/zoho/integrations/{integration_id}/import/status \
  -H "Authorization: Bearer sk_live_your_api_key"
```

**Response includes:**

* Current status (`idle`, `in_progress`, `completed`, `failed`)
* Progress metrics (total, processed, successful, failed)
* Results (customers created, conversations created, messages created)
* Any errors encountered

## Import Options

### What Can Be Imported

* **Contacts** → Customers in G-Tateth
* **Deals** → Conversations (sales pipeline)
* **Tickets** → Conversations (support cases)
* **Notes** → Messages in conversations
* **Activities** → Call logs and tasks (optional)

### Date Range Filtering

Import only data from a specific time period:

```json theme={null}
{
  "dateRange": {
    "startDate": "2024-01-01",
    "endDate": "2024-12-31"
  }
}
```

**Use Cases:**

* **Incremental Imports**: Import only recent data
* **Historical Import**: Import all historical data (omit dateRange)
* **Testing**: Import small date range to test before full import

### Selective Import

Choose what to import:

```json theme={null}
{
  "importContacts": true,    // Import contacts as customers
  "importDeals": true,       // Import deals as conversations
  "importTickets": true,     // Import tickets as conversations
  "importNotes": true,       // Import notes as messages
  "importActivities": false  // Import call logs (optional)
}
```

## Data Mapping Details

### Contacts → Customers

| Zoho Field         | g-tateth Field        | Notes                 |
| ------------------ | --------------------- | --------------------- |
| `Email`            | `profile.email`       | Primary identifier    |
| `First_Name`       | `profile.firstName`   |                       |
| `Last_Name`        | `profile.lastName`    |                       |
| `Phone` / `Mobile` | `profile.phone`       |                       |
| `Company`          | `profile.company`     |                       |
| `Title`            | `profile.jobTitle`    |                       |
| Custom fields      | `customFields.zoho_*` | Preserved with prefix |

### Deals → Conversations

| Zoho Field     | g-tateth Field         | Notes                         |
| -------------- | ---------------------- | ----------------------------- |
| `Deal_Name`    | `subject`              | Conversation title            |
| `Stage`        | `status`               | Mapped to open/closed/pending |
| `Amount`       | `metadata.dealAmount`  | Stored in metadata            |
| `Description`  | Initial message        | First message in conversation |
| `Closing_Date` | `metadata.closingDate` |                               |
| Notes          | Additional messages    | Each note becomes a message   |

### Tickets → Conversations

| Zoho Field    | g-tateth Field      | Notes                            |
| ------------- | ------------------- | -------------------------------- |
| `Subject`     | `subject`           | Conversation title               |
| `Status`      | `status`            | Mapped to open/closed/pending    |
| `Priority`    | `priority`          | Mapped to low/medium/high/urgent |
| `Description` | Initial message     | First message in conversation    |
| Notes         | Additional messages | Each note becomes a message      |

## Workflows

### Complete Integration Flow (API)

Here's a complete example showing how to connect and use Zoho integration via API:

```javascript theme={null}
// Step 1: Initiate OAuth
const connectResponse = await fetch('https://api.g-tateth.com/api/zoho/connect', {
  headers: {
    'Authorization': `Bearer ${apiKey}`
  }
});

const { authUrl, state } = await connectResponse.json();

// Step 2: Redirect user to authUrl (in browser)
// window.location.href = authUrl;
// Or in server-side flow, return authUrl to client

// Step 3: After OAuth callback, get the integration ID
// Poll or wait a moment, then fetch integrations
const integrationsResponse = await fetch('https://api.g-tateth.com/api/zoho/integrations', {
  headers: {
    'Authorization': `Bearer ${apiKey}`
  }
});

const { data: integrations } = await integrationsResponse.json();

// Get the most recent integration (or filter by accountName/accountEmail)
const integration = integrations[0]; // Most recent
const integrationId = integration._id;

// Step 4: Now you can use integrationId for operations
console.log(`Integration ID: ${integrationId}`);

// Step 5: Start import
await fetch(`https://api.g-tateth.com/api/zoho/integrations/${integrationId}/import`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    importContacts: true,
    importDeals: true
  })
});
```

<Note>
  **Server-Side Flow**: If you're building a server-side integration, you'll need to:

  1. Store the `state` parameter when initiating OAuth
  2. Set up a webhook or polling mechanism to detect when OAuth completes
  3. Call `GET /api/zoho/integrations` to retrieve the new integration ID
</Note>

### Full Historical Import

Import all data from Zoho:

```bash theme={null}
# 1. Connect Zoho (via UI or API)
# 2. Start full import (no date range)
curl -X POST https://api.g-tateth.com/api/zoho/integrations/{id}/import \
  -H "Authorization: Bearer sk_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "importContacts": true,
    "importDeals": true,
    "importTickets": true,
    "importNotes": true
  }'

# 3. Poll status until complete
while true; do
  STATUS=$(curl -s -X GET https://api.g-tateth.com/api/zoho/integrations/{id}/import/status \
    -H "Authorization: Bearer sk_live_your_api_key" | jq -r '.data.status')
  
  if [ "$STATUS" = "completed" ]; then
    echo "Import completed!"
    break
  elif [ "$STATUS" = "failed" ]; then
    echo "Import failed!"
    break
  fi
  
  sleep 5
done
```

### Incremental Import

Import only recent data:

```bash theme={null}
# Import last 30 days
curl -X POST https://api.g-tateth.com/api/zoho/integrations/{id}/import \
  -H "Authorization: Bearer sk_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "importContacts": true,
    "importDeals": true,
    "dateRange": {
      "startDate": "2024-12-01",
      "endDate": "2024-12-31"
    }
  }'
```

### Testing Import

Test with a small dataset first:

```bash theme={null}
# Import only last week's data
curl -X POST https://api.g-tateth.com/api/zoho/integrations/{id}/import \
  -H "Authorization: Bearer sk_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "importContacts": true,
    "importDeals": false,
    "importTickets": false,
    "dateRange": {
      "startDate": "2024-12-25",
      "endDate": "2024-12-31"
    }
  }'
```

## Managing Integrations

### List All Integrations

```bash theme={null}
curl -X GET https://api.g-tateth.com/api/zoho/integrations \
  -H "Authorization: Bearer sk_live_your_api_key"
```

### Get Integration Details

```bash theme={null}
curl -X GET https://api.g-tateth.com/api/zoho/integrations/{id} \
  -H "Authorization: Bearer sk_live_your_api_key"
```

### Disconnect Integration

```bash theme={null}
curl -X DELETE https://api.g-tateth.com/api/zoho/integrations/{id} \
  -H "Authorization: Bearer sk_live_your_api_key"
```

## Best Practices

### 1. Test Before Full Import

Always test with a small date range first:

```json theme={null}
{
  "dateRange": {
    "startDate": "2024-12-25",
    "endDate": "2024-12-31"
  }
}
```

### 2. Monitor Progress

Poll the status endpoint every 3-5 seconds during import:

```javascript theme={null}
async function monitorImport(integrationId, apiKey) {
  while (true) {
    const response = await fetch(
      `https://api.g-tateth.com/api/zoho/integrations/${integrationId}/import/status`,
      {
        headers: { 'Authorization': `Bearer ${apiKey}` }
      }
    );
    
    const { data } = await response.json();
    
    console.log(`Progress: ${data.progress.processed}/${data.progress.total}`);
    
    if (data.status === 'completed' || data.status === 'failed') {
      break;
    }
    
    await new Promise(resolve => setTimeout(resolve, 3000));
  }
}
```

### 3. Handle Errors

Review the `errors` array in the status response:

```javascript theme={null}
if (data.results.errors && data.results.errors.length > 0) {
  console.error('Import errors:', data.results.errors);
  // Log or handle errors appropriately
}
```

### 4. Use Date Ranges for Large Imports

For accounts with thousands of records, use date ranges to import in batches:

```javascript theme={null}
// Import in monthly batches
const months = [
  { start: '2024-01-01', end: '2024-01-31' },
  { start: '2024-02-01', end: '2024-02-29' },
  // ...
];

for (const month of months) {
  await startImport(integrationId, {
    dateRange: month
  });
  
  // Wait for completion before next batch
  await waitForCompletion(integrationId);
}
```

### 5. Preserve Data Integrity

* **Don't re-import**: Re-importing the same data creates duplicates
* **Check before import**: Review what will be imported
* **Backup first**: Ensure you have backups before large imports

## Troubleshooting

### Import Stuck or Slow

* **Large datasets**: Use date ranges to import in smaller batches
* **Rate limits**: Zoho API has rate limits; imports may take time
* **Check status**: Use the status endpoint to see current progress

### Missing Data

* **Check date range**: Ensure date range includes the data you want
* **Verify Zoho access**: Ensure integration has proper permissions
* **Review errors**: Check the `errors` array in status response

### OAuth Issues

* **Reconnect**: Disconnect and reconnect the integration
* **Check permissions**: Ensure Zoho app has required scopes
* **Verify redirect URI**: Ensure redirect URI matches Zoho app settings

## API Reference

For complete API endpoint documentation, see the [API Reference](/api-reference) tab. Key endpoints:

* `GET /api/zoho/connect` - Initiate OAuth flow
* `GET /api/zoho/integrations` - List integrations
* `POST /api/zoho/integrations/:id/import` - Start import
* `GET /api/zoho/integrations/:id/import/status` - Get import status
* `GET /api/zoho/integrations/:id/import/history` - Get import history

## Support

Questions about Zoho integration?

* **Email**: `api-support@g-tateth.com`
* **Documentation**: `https://docs.g-tateth.com`
* **API Reference**: See the [API Reference](/api-reference) tab for endpoint details
