# Contacts

`crm.contacts` — `/v1/audience/contacts`

The people an account talks to, and the resource everything else in the audience
module hangs off. A contact carries a name, a set of channel identities, the
values of every custom field, its tags, and the state of its conversation.

**Scoping** — contacts belong to an account, and a request carries two
identities: the caller and the account they act for. Reads match either; writes
land on the caller's own.

| Action | Route | Scope |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/audience/contacts` | `contacts:read` |
| [`get`](#get) | `GET /v1/audience/contacts/:id` | `contacts:read` |
| [`create`](#create) | `POST /v1/audience/contacts` | `contacts:write` |
| [`update`](#update) | `PATCH /v1/audience/contacts/:id` | `contacts:write` |
| [`delete`](#delete) | `DELETE /v1/audience/contacts/:id` | `contacts:write` |
| [`iterate`](#iterate) | — (walks `list`) | `contacts:read` |

**Permissions** — each route also names a permission key, and a team member
needs it. An owner does not.

| Action | Key |
| --- | --- |
| `list` | `CRM.CONTACT.LIST` |
| `get` | `CRM.CONTACT.READ` |
| `create` | `CRM.CONTACT.CREATE` |
| `update` | `CRM.CONTACT.UPDATE` |
| `delete` | `CRM.CONTACT.DELETE` |

A refusal is `403` with code `A403` (the role does not hold the key) or `E403`
(the account's plan does not cover contacts — `details.feature` names it). An
owner can meet `E403` but never `A403`.

Separately from that, how many contacts a member can see is their role's
`data_scope`: `own` — the default — returns the contacts assigned to them as
`agent`, and `all` returns the account's. A contact assigned to nobody is the
account's and not visible to an `own`-scoped member. Reading, updating or
deleting a contact outside that scope is `404`, never `403`: a `403` would
confirm the contact exists, which is what the scope is hiding.

A contact a **team member** creates is assigned to that member as its `agent`,
whatever their `data_scope` and whatever `agent` the body carried: they are the
one working it. An account holder's create leaves `agent` as given — `null`
unless they named someone — so a contact stays unassigned until it is handed
over.


## The contact object

```ts
interface Contact {
  id: string;
  name: { salutation: string; first_name: string; last_name: string };
  profile: Record<string, ContactProfile>;   // channel identities, keyed by channel
  custom_field_hash: Record<string, unknown>; // values keyed by custom field slug
  chat_metadata: ContactChatMetadata;
  order?: string;
  last_seen: number;                          // unix seconds
  last_icm_timestamp: number;                 // unix seconds, last inbound message
  last_interaction_props: Record<string, unknown>;
  agent: string | null;
  team: string | null;
  lead_source: { type?: string; module?: string; id: string | null };
  status: 'live' | 'trashed';
  privacy_status: 'open' | 'locked';
  tags: ContactTag[];                         // resolved documents, not ids
  createdAt: string;
  updatedAt: string;
}

interface ContactProfile {
  id: string;
  channel: 'whatsapp' | 'facebook' | 'instagram' | 'telegram' | 'email' | 'rcs' | 'webchat';
  identifier: string;   // number, handle or address
  name: string;
  profile_pic: string;
  extra: Record<string, unknown>;
}

interface ContactChatMetadata {
  new: boolean;
  archived: boolean;
  unread: number;
  pause_duration: number;   // seconds to pause automation for
  marked_as_unread: boolean;
  closed: boolean;
  marked_as_done: boolean;
  blocked: { incoming: boolean; outgoing: boolean; bot: boolean; api: boolean };
}
```

`profile`, `last_seen`, `last_icm_timestamp` and `last_interaction_props` are
written by the platform as conversations happen. They are not settable.

---

## list

```ts
crm.contacts.list(query?: Partial<ListContactsQuery>): Promise<Paginated<Contact>>
```

`GET /v1/audience/contacts` · `contacts:read` · **200**

### Query

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |
| `search` | string | — | 1–120 chars. Matches the first and last name, plus the name and identifier of every channel identity. |
| `tag` | ObjectId | — | Contacts carrying this tag. |
| `agent` | ObjectId | — | Contacts assigned to this agent. |
| `status` | `'live' \| 'trashed'` | `'live'` | The trash needs an explicit `'trashed'`. |
| `segment` | string | — | A segment's id **or** its name. A reference matching neither is a `404` — listing everyone because the segment went missing would be the wrong answer. |
| `filter` | `ContactFilter` | — | Ad-hoc conditions. Serialised to JSON by the SDK. See [contact filter](../contact-filter.md). |

`segment` and `filter` can be sent together: the ad-hoc conditions then **narrow**
the saved ones rather than replacing them. `tag`, `agent` and `status` narrow
whatever those produce.

### Example

```ts
const page = await crm.contacts.list({
  search: 'acme',
  status: 'live',
  segment: 'High budget',
  filter: {
    conditions: [
      { operator: null, field_id: 'city', field_type: 'text', condition: 'equal to', value: 'Pune' },
    ],
  },
  rows: 50,
});

console.log(page.pagination); // { page: 1, rows: 50, total: 128, pages: 3 }
```

---

## get

```ts
crm.contacts.get(id: string): Promise<Contact>
```

`GET /v1/audience/contacts/:id` · `contacts:read` · **200**

One contact with its tags resolved. `404 not_found` if no contact with that id
belongs to the caller — including a contact in the trash of another account.

---

## create

```ts
crm.contacts.create(input?: CreateContactInput): Promise<Contact>
```

`POST /v1/audience/contacts` · `contacts:write` · **201**

### Body

Every field is optional; `crm.contacts.create()` with no argument creates a
blank contact.

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `name` | `Partial<ContactName>` | — | `salutation` ≤ 20 chars, `first_name` and `last_name` ≤ 120. |
| `whatsapp` | string | — | The contact's WhatsApp number, in any shape. Creates the channel identity. Create-only. |
| `order` | string | — | Free-form external reference. |
| `tags` | ObjectId[] | `[]` | Contact tag ids. |
| `agent` | ObjectId \| null | — | Assigned agent. **Ignored for a team member**: the member creating the contact is assigned it. |
| `team` | ObjectId \| null | — | Assigned team. |
| `lead_source` | `{ type?, module?, id? }` | — | Where the contact came from. |
| `status` | `'live' \| 'trashed'` | `'live'` | |
| `privacy_status` | `'open' \| 'locked'` | `'open'` | |
| `custom_field_hash` | object | — | Values keyed by custom field **slug**. |
| `chat_metadata` | partial | — | Including `blocked`, itself partial. |

```ts
const contact = await crm.contacts.create({
  name: { first_name: 'Ada', last_name: 'Lovelace' },
  whatsapp: '+91 98765 43210',
  tags: [vipTagId],
  custom_field_hash: { city: 'Pune', lead_score: 80 },
});

contact.profile.whatsapp.identifier; // '919876543210'
```

### The `whatsapp` field

Pass it unless the contact is genuinely a placeholder. A contact with no channel
identity cannot be messaged, will not be matched to an inbound message, is
invisible to a number search, and drops out of every segment whose filter reaches
into channel identities.

**Any shape is accepted and stored as digits only.** `+91 98765 43210`,
`+919876543210` and `919876543210` all store `919876543210`, which is the form an
inbound message carries — the comparison that matches a reply to this contact is
made against that string, so the punctuation has to go.

| Response | When |
| --- | --- |
| `409 conflict` | The account already holds that number, on another contact or on this one. Nothing is created; the existing contact is untouched. |
| `422` | The value contains no digits at all. An empty identifier would be a channel identity that can never be messaged or matched. |

A number identifies **one contact per account**, and `profile` holds **one
identity per channel** — so a contact cannot carry two WhatsApp numbers, and two
contacts cannot share one.

Identities for the other channels are still written by the conversation that
starts on them.

---

## update

```ts
crm.contacts.update(id: string, input: UpdateContactInput): Promise<Contact>
```

`PATCH /v1/audience/contacts/:id` · `contacts:write` · **200**

Takes the same body as `create` minus `whatsapp`, all optional. Anything left out
is untouched.

`tags` and `custom_field_hash` **replace** their stored value rather than merging
into it — read the contact first if you mean to add one tag to the existing set.

`whatsapp` is **not** accepted. A channel identity lives in its own collection, so
changing a number is a write there plus a delete of the identity it replaces —
not something a patch of the contact can express. It is create-only for now.

```ts
await crm.contacts.update(id, { agent: agentId, chat_metadata: { closed: true } });
```

---

## delete

```ts
crm.contacts.delete(id: string): Promise<ContactDeleteResult>
```

`DELETE /v1/audience/contacts/:id` · `contacts:write` · **200**

Two-stage, and **200 rather than 204 both times**: the body is what says which
stage ran.

| Call | Contact was | Result |
| --- | --- | --- |
| first | `live` | `{ id, status: 'trashed' }` — recoverable with `update(id, { status: 'live' })` |
| second | `trashed` | `{ id, status: 'deleted' }` — the contact, its notes and its channel identities are gone |

```ts
const first = await crm.contacts.delete(id);  // { status: 'trashed' }
const second = await crm.contacts.delete(id); // { status: 'deleted' }
```

---

## iterate

```ts
crm.contacts.iterate(query?: Partial<ListContactsQuery>): AsyncGenerator<Contact>
```

Walks every page of `list`, yielding one contact at a time. Takes the same query;
`page` is managed for you and is ignored if passed.

```ts
for await (const contact of crm.contacts.iterate({ tag: vipTagId })) {
  await sync(contact);
}
```

The walk reads live data. A contact created while you are part-way through may
be missed or seen twice — take a `filter` on `SYSTEM_CREATED_ON` if you need a
stable set.
