# CRM triggers

`crm.crmTriggers` — `/v1/audience/crm-triggers`

Fire a webhook when a contact changes.

A trigger asks three questions, and all three have to pass before its action
runs:

1. **`trigger`** — which contact event happened.
2. **`when`** — did the right *fields* move?
3. **`filters`** — does the contact itself match these conditions?

`filters` speak the same [contact filter](../contact-filter.md) DSL segments do,
flat rather than wrapped. They are checked by running the contact list query
pinned to that one contact, so a trigger's conditions mean exactly what they
mean on the list.

| Action | Route | Scope |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/audience/crm-triggers` | `crm_triggers:read` |
| [`get`](#get) | `GET /v1/audience/crm-triggers/:id` | `crm_triggers:read` |
| [`create`](#create) | `POST /v1/audience/crm-triggers` | `crm_triggers:write` |
| [`update`](#update) | `PATCH /v1/audience/crm-triggers/:id` | `crm_triggers:write` |
| [`delete`](#delete) | `DELETE /v1/audience/crm-triggers/:id` | `crm_triggers:write` |
| [`logs`](#logs) | `GET /v1/audience/crm-triggers/logs` | `crm_triggers:read` |

**Permissions** — `CRM.TRIGGER`: `LIST`, `READ` (one trigger, and the log
endpoint), `CREATE`, `UPDATE`, `DELETE`.

## The trigger object

```ts
interface CrmTrigger {
  id: string;
  name: string;
  active: boolean;
  module: 'contact';
  type: 'event' | 'time';
  trigger: CrmTriggerEvent;
  when: { condition: 'any' | 'any_of_selected' | 'all'; fields: string[] };
  filters: ContactFilterEntry[];
  action: {
    type: 'webhook';
    config: { url: string; method: 'POST' | 'PUT' | 'PATCH' | 'GET'; headers: Record<string, string> };
  };
  createdAt: string;
  updatedAt: string;
}
```

### Events

| `trigger` | Fires when |
| --- | --- |
| `created` | A contact is created. |
| `edited`, `modified` | Any change — the two are equivalent. |
| `deleted` | A contact is destroyed. |
| `agent_assigned`, `agent_deassigned` | The assigned agent changed. |
| `marked_as_done`, `marked_as_closed`, `marked_as_archived` | The matching `chat_metadata` flag moved. |
| `blocked` | A `chat_metadata.blocked` flag moved. |

All of these except `created` and `deleted` are narrower readings of the same
update, decided by which paths moved.

### `when`

| `condition` | Passes when |
| --- | --- |
| `any` | Every change — `fields` is ignored. |
| `any_of_selected` | At least one path in `fields` moved. |
| `all` | Every path in `fields` moved. |

`fields` are dotted contact paths: `name.first_name`, `chat_metadata.closed`,
`custom_field_hash.lead_score`.

Events that carry no change set — a creation, a deletion — pass regardless.

> **Known gap.** `filters` are skipped for `deleted` events: the contact is
> already gone, so there is nothing left to match against.

### Time triggers

`type: 'time'` is stored and served, but **nothing dispatches it yet**. Creating
one is not an error; it simply never fires.

---

## list

```ts
crm.crmTriggers.list(query?: Partial<ListCrmTriggersQuery>): Promise<Paginated<CrmTrigger>>
```

`GET /v1/audience/crm-triggers` · `crm_triggers:read` · **200**

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |
| `search` | string | — | 1–120 chars. Matches the trigger **name**. |
| `trigger` | `CrmTriggerEvent` | — | Quick filter. |
| `type` | `'event' \| 'time'` | — | Quick filter. |
| `active` | boolean | — | Quick filter. |

---

## get

```ts
crm.crmTriggers.get(id: string): Promise<CrmTrigger>
```

`GET /v1/audience/crm-triggers/:id` · `crm_triggers:read` · **200**

---

## create

```ts
crm.crmTriggers.create(input: CreateCrmTriggerInput): Promise<CrmTrigger>
```

`POST /v1/audience/crm-triggers` · `crm_triggers:write` · **201**

### Body

| Field | Type | Required | Default | Notes |
| --- | --- | --- | --- | --- |
| `name` | string | yes | — | Trimmed, 1–120 chars. |
| `action` | `CrmTriggerAction` | yes | — | See below. |
| `active` | boolean | no | `true` | |
| `module` | `'contact'` | no | `'contact'` | |
| `type` | `'event' \| 'time'` | no | `'event'` | |
| `trigger` | `CrmTriggerEvent` | no | `'edited'` | |
| `when` | `CrmTriggerWhen` | no | `{ condition: 'any', fields: [] }` | |
| `filters` | `ContactFilterEntry[]` | no | `[]` | At most 50. |

With only `name` and `action`, you get an active `event` trigger on `edited`
with no narrowing — it fires on every change to every contact.

`action.config`:

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `url` | string | — | Required, and must be a valid URL. |
| `method` | `'POST' \| 'PUT' \| 'PATCH' \| 'GET'` | `'POST'` | |
| `headers` | `Record<string, string>` | `{}` | Sent alongside the contact payload. |

```ts
await crm.crmTriggers.create({
  name: 'Notify ops when a VIP conversation closes',
  trigger: 'edited',
  when: { condition: 'any_of_selected', fields: ['chat_metadata.closed'] },
  filters: [
    { operator: null, field_id: 'tags', field_type: 'string', condition: 'equal to', value: [vipTagId] },
  ],
  action: {
    config: {
      url: 'https://ops.example.com/hooks/vip',
      method: 'POST',
      headers: { 'x-source': 'crm' },
    },
  },
});
```

> **Not signed.** Trigger deliveries carry no signature — the schema has no
> per-trigger secret. Put a shared token in `action.config.headers` and check it
> at your endpoint. (`crm.webhooks` deliveries *are* signed.)

---

## update

```ts
crm.crmTriggers.update(id: string, input: UpdateCrmTriggerInput): Promise<CrmTrigger>
```

`PATCH /v1/audience/crm-triggers/:id` · `crm_triggers:write` · **200**

Same fields as `create`, all optional. `when`, `filters` and `action`
**replace** their stored value rather than merging into it.

Pause a trigger with `{ active: false }` rather than deleting it — the
configuration comes back, and the delivery history stays readable either way.

---

## delete

```ts
crm.crmTriggers.delete(id: string): Promise<void>
```

`DELETE /v1/audience/crm-triggers/:id` · `crm_triggers:write` · **204**, no body.

---

## logs

```ts
crm.crmTriggers.logs(query?: Partial<ListCrmTriggerLogsQuery>): Promise<Paginated<CrmTriggerLog>>
```

`GET /v1/audience/crm-triggers/logs` · `crm_triggers:read` · **200**

Delivery history across every trigger, or one trigger's with `{ trigger: id }`.
Newest first.

Note the path: **`logs` is a sibling of `:id`, not a child of it** — there is no
`/crm-triggers/:id/logs`.

Logs are written by the dispatcher, never by a caller, and the collection
expires them after 30 days. There is no way to write or delete one.

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |
| `search` | string | — | Accepted by the route, but ignored: a log row has no searchable text. |
| `trigger` | ObjectId | — | One trigger's history. |
| `event` | `CrmTriggerEvent` | — | Quick filter. |
| `status` | `'success' \| 'fail'` | — | Quick filter. |

```ts
interface CrmTriggerLog {
  id: string;
  trigger: string;                      // the trigger that fired
  event: CrmTriggerEvent;
  status: 'success' | 'fail';
  payload: { url?: string; body?: unknown };
  response?: unknown;                   // status and body, or the error that stopped the call
  expiryDate: string;                   // when the row is removed
  createdAt: string;
  updatedAt: string;
}
```

```ts
const failures = await crm.crmTriggers.logs({ trigger: triggerId, status: 'fail' });
for (const log of failures.data) console.error(log.payload.url, log.response);
```
