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

# Conversations

> Conversations are the core of ZappWay — every message exchanged with a contact through any channel (WhatsApp, Email, Widget, TikTok, and more) is organized as a conversation.

> **What you will learn:**
> This page explains how conversations work in ZappWay, how to list and manage them, how to update their status in bulk, how to export them, and how to use the AI summary feature.

***

## 🔢 Table of Contents

1. [Overview](#1-overview)
2. [Endpoint Reference](#2-endpoint-reference)
3. [Listing Conversations](#3-listing-conversations)
4. [Managing a Conversation](#4-managing-a-conversation)
5. [Bulk Status Update](#5-bulk-status-update)
6. [Export Conversations](#6-export-conversations)
7. [Evaluating Answers](#7-evaluating-answers)
8. [Response Format](#8-response-format)
9. [Best Practices](#9-best-practices)
10. [Troubleshooting](#10-troubleshooting)

***

## 1. Overview

### What is a Conversation?

A **Conversation** in ZappWay is a complete thread of messages between a contact and your organization — mediated by an AI Employee, a human agent, or both.

**Conversations can originate from:**

* 💬 WhatsApp (Business API)
* 📧 Email Inbox
* 🌐 Widget (website chat)
* 📱 TikTok DMs
* 🔌 Any connected integration

**Every conversation has:**

* A **contact** — who the conversation is with
* A **channel** — where the conversation is happening
* A **status** — `open`, `resolved`, or `snoozed`
* An **AI Employee** assignment (optional)
* A full **message thread** with timestamps

### AI and Human Collaboration

Conversations support a **hybrid model**: the AI Employee can handle messages automatically, and a human agent can take over at any point. The AI's messages and human messages both appear in the same thread.

***

## 2. Endpoint Reference

| Method   | Endpoint                                          | Description                                    | Auth                           |
| -------- | ------------------------------------------------- | ---------------------------------------------- | ------------------------------ |
| `GET`    | `/api/conversations`                              | List conversations with filters                | Optional auth (widget support) |
| `HEAD`   | `/api/conversations`                              | CORS preflight                                 | None                           |
| `GET`    | `/api/conversations/[conversationId]`             | Get a specific conversation                    | Org session                    |
| `PATCH`  | `/api/conversations/[conversationId]`             | Update conversation (assign agent, set status) | Org session                    |
| `DELETE` | `/api/conversations/[conversationId]`             | Delete a conversation                          | Org session                    |
| `POST`   | `/api/conversations/update-status`                | Bulk update conversation statuses              | Org session                    |
| `POST`   | `/api/conversations/bulk-unread`                  | Mark conversations as unread in bulk           | Org session                    |
| `GET`    | `/api/conversations/export`                       | Export conversations to file                   | Org session                    |
| `POST`   | `/api/conversations/[conversationId]/eval-answer` | Evaluate AI answer quality                     | Org session                    |

***

## 3. Listing Conversations

### List Conversations

```bash theme={null}
GET /api/conversations
```

Supports **optional authentication** — authenticated requests return organization conversations; unauthenticated requests may return public widget conversations.

**Query Parameters:**

| Parameter   | Type                                | Description                                             |
| ----------- | ----------------------------------- | ------------------------------------------------------- |
| `status`    | `"open" \| "resolved" \| "snoozed"` | Filter by conversation status                           |
| `agentId`   | `string`                            | Filter by assigned AI Employee                          |
| `contactId` | `string`                            | Filter by contact                                       |
| `channel`   | `string`                            | Filter by channel (e.g., `whatsapp`, `email`, `widget`) |
| `page`      | `number`                            | Page number for pagination                              |
| `limit`     | `number`                            | Number of results per page                              |
| `search`    | `string`                            | Full-text search across conversation content            |
| `dateFrom`  | `ISO 8601`                          | Filter conversations after this date                    |
| `dateTo`    | `ISO 8601`                          | Filter conversations before this date                   |

**Example:**

```bash theme={null}
GET /api/conversations?status=open&channel=whatsapp&page=1&limit=20
```

**Response:**

```json theme={null}
{
  "conversations": [
    {
      "id": "conv_abc123",
      "contactId": "contact_xyz",
      "contact": {
        "id": "contact_xyz",
        "name": "John Smith",
        "email": "john@example.com",
        "phone": "+1234567890"
      },
      "channel": "whatsapp",
      "status": "open",
      "agentId": "agent_456",
      "lastMessageAt": "2025-01-15T14:30:00.000Z",
      "lastMessagePreview": "Hi, I need help with my order...",
      "unreadCount": 2,
      "createdAt": "2025-01-15T10:00:00.000Z"
    }
  ],
  "total": 142,
  "page": 1,
  "limit": 20
}
```

**cURL:**

```bash theme={null}
curl -X GET "https://your-domain.com/api/conversations?status=open&limit=10" \
  -H "Cookie: next-auth.session-token=YOUR_SESSION_TOKEN"
```

**TypeScript:**

```ts theme={null}
const params = new URLSearchParams({
  status: 'open',
  channel: 'whatsapp',
  page: '1',
  limit: '20',
});

const response = await fetch(`/api/conversations?${params}`);
const data = await response.json();
```

***

## 4. Managing a Conversation

### Get a Conversation

```bash theme={null}
GET /api/conversations/{conversationId}
```

Returns the full conversation object, including all messages and contact details.

### Update a Conversation

```bash theme={null}
PATCH /api/conversations/{conversationId}
Content-Type: application/json
```

**Request Body:**

| Field            | Type                                | Description                       |
| ---------------- | ----------------------------------- | --------------------------------- |
| `status`         | `"open" \| "resolved" \| "snoozed"` | Update conversation status        |
| `agentId`        | `string \| null`                    | Assign or unassign an AI Employee |
| `assignedUserId` | `string \| null`                    | Assign to a human team member     |
| `note`           | `string`                            | Add an internal note              |
| `snoozeUntil`    | `ISO 8601`                          | Snooze until a specific datetime  |

**Example — Resolve a conversation:**

```json theme={null}
{
  "status": "resolved"
}
```

**Example — Assign to AI Employee:**

```json theme={null}
{
  "agentId": "agent_456"
}
```

**Example — Snooze:**

```json theme={null}
{
  "status": "snoozed",
  "snoozeUntil": "2025-01-20T09:00:00.000Z"
}
```

### Delete a Conversation

```bash theme={null}
DELETE /api/conversations/{conversationId}
```

> ⚠️ Deleting a conversation permanently removes all associated messages. This action is irreversible.

***

## 5. Bulk Status Update

Update the status of multiple conversations at once.

```bash theme={null}
POST /api/conversations/update-status
Content-Type: application/json
```

**Request Body:**

| Field             | Type                                | Required | Description                                |
| ----------------- | ----------------------------------- | -------- | ------------------------------------------ |
| `conversationIds` | `string[]`                          | ✅        | Array of conversation IDs to update        |
| `status`          | `"open" \| "resolved" \| "snoozed"` | ✅        | New status for all specified conversations |

**Example — Resolve multiple conversations:**

```json theme={null}
{
  "conversationIds": ["conv_abc123", "conv_def456", "conv_ghi789"],
  "status": "resolved"
}
```

**cURL:**

```bash theme={null}
curl -X POST "https://your-domain.com/api/conversations/update-status" \
  -H "Content-Type: application/json" \
  -H "Cookie: next-auth.session-token=YOUR_SESSION_TOKEN" \
  -d '{
    "conversationIds": ["conv_abc123", "conv_def456"],
    "status": "resolved"
  }'
```

### Mark as Unread in Bulk

```bash theme={null}
POST /api/conversations/bulk-unread
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "conversationIds": ["conv_abc123", "conv_def456"]
}
```

***

## 6. Export Conversations

Download conversations as a file for reporting, compliance, or analysis.

```bash theme={null}
GET /api/conversations/export
```

**Query Parameters:**

| Parameter  | Type              | Description                          |
| ---------- | ----------------- | ------------------------------------ |
| `status`   | `string`          | Filter by status before export       |
| `dateFrom` | `ISO 8601`        | Export conversations from this date  |
| `dateTo`   | `ISO 8601`        | Export conversations until this date |
| `format`   | `"csv" \| "json"` | Export format (default: `csv`)       |

**Example:**

```bash theme={null}
GET /api/conversations/export?status=resolved&dateFrom=2025-01-01&format=csv
```

The response contains the file as a downloadable attachment.

***

## 7. Evaluating Answers

Use the evaluation endpoint to rate the quality of AI-generated answers. This feedback is used to improve AI performance over time.

```bash theme={null}
POST /api/conversations/{conversationId}/eval-answer
Content-Type: application/json
```

**Request Body:**

| Field       | Type                       | Required | Description                          |
| ----------- | -------------------------- | -------- | ------------------------------------ |
| `messageId` | `string`                   | ✅        | The ID of the AI message to evaluate |
| `rating`    | `"positive" \| "negative"` | ✅        | Your quality rating                  |
| `feedback`  | `string`                   | ❌        | Optional written feedback            |

**Example:**

```json theme={null}
{
  "messageId": "msg_abc123",
  "rating": "positive",
  "feedback": "Perfect response — accurate and concise"
}
```

***

## 8. Response Format

### Conversation Object

| Field                | Type             | Description                                   |
| -------------------- | ---------------- | --------------------------------------------- |
| `id`                 | `string`         | Unique conversation ID                        |
| `contactId`          | `string`         | ID of the contact                             |
| `contact`            | `Contact`        | Full contact object                           |
| `channel`            | `string`         | Originating channel                           |
| `status`             | `string`         | Current status: `open`, `resolved`, `snoozed` |
| `agentId`            | `string \| null` | Assigned AI Employee ID                       |
| `assignedUserId`     | `string \| null` | Assigned human user ID                        |
| `lastMessageAt`      | `ISO 8601`       | Timestamp of the last message                 |
| `lastMessagePreview` | `string`         | Preview of the last message                   |
| `unreadCount`        | `number`         | Number of unread messages                     |
| `createdAt`          | `ISO 8601`       | When the conversation was created             |

### Status Codes

| Status | Meaning                            |
| ------ | ---------------------------------- |
| `200`  | Request successful                 |
| `204`  | Deleted successfully               |
| `400`  | Invalid request body or parameters |
| `401`  | Not authenticated                  |
| `403`  | Insufficient permissions           |
| `404`  | Conversation not found             |
| `500`  | Internal server error              |

***

## 9. Best Practices

### Status Management

| Status     | Use When                                                           |
| ---------- | ------------------------------------------------------------------ |
| `open`     | Conversation is active and requires attention                      |
| `resolved` | Issue is fully addressed — conversation is complete                |
| `snoozed`  | Conversation needs follow-up later — auto-reopens at `snoozeUntil` |

**Tips:**

* Use **bulk status update** for end-of-day queue management
* Set `snoozeUntil` to the next business day for low-priority conversations
* Resolve conversations promptly to keep your queue clean

### Filtering and Search

* Combine filters (e.g., `status=open&channel=whatsapp&agentId=agent_123`) for precise results
* Use `search` for keyword lookup when you remember conversation content but not the contact
* Export filtered subsets for specific reporting needs

### AI Answer Evaluation

* Rate AI answers regularly to improve model performance
* Provide written `feedback` for negative ratings — this helps identify patterns
* Focus on rating answers where the AI made a factual error or missed the intent

***

## 10. Troubleshooting

| Problem                            | Possible Cause                                     | Solution                                                  |
| ---------------------------------- | -------------------------------------------------- | --------------------------------------------------------- |
| Conversation not appearing in list | Wrong filter applied                               | Try removing filters and searching by contact or keyword  |
| Bulk status update partially fails | Some IDs don't belong to your organization         | Verify all conversation IDs are correct and from your org |
| Export returns empty file          | No conversations match the date/status filter      | Expand the date range or remove status filter             |
| Cannot delete a conversation       | Conversation is linked to an active widget session | Wait for the session to end, or contact support           |
| AI answer evaluation rejected      | `messageId` is not an AI-generated message         | Only AI-generated messages can be evaluated               |
