# Canned replies

`crm.cannedReplies` — `/v1/audience/canned-replies`

Message payloads an agent sends into a chat without retyping them. The panel
offers them when an agent types `/` followed by the reply's name.

Two kinds, and the difference is who gets the last word:

- **`CANNED`** — every message the reply holds is sent exactly as stored, in
  order, the moment it is picked. A three-message reply puts three messages on
  the contact's phone from one keystroke.
- **`QUICK`** — the reply's text lands in the agent's composer to edit before
  sending. Exactly one message, of type `text`: there is one composer, and
  nowhere in it to put a second message or an image.

| Action | Route | Scope |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/audience/canned-replies` | `canned_replies:read` |
| [`get`](#get) | `GET /v1/audience/canned-replies/:reply` | `canned_replies:read` |
| [`create`](#create) | `POST /v1/audience/canned-replies` | `canned_replies:write` |
| [`update`](#update) | `PATCH /v1/audience/canned-replies/:reply` | `canned_replies:write` |
| [`delete`](#delete) | `DELETE /v1/audience/canned-replies/:reply` | `canned_replies:write` |

**Permissions** — `CRM.CHAT.CANNED_REPLY`: `LIST`, `READ`, `CREATE`, `UPDATE`,
`DELETE`. Account-level, so `data_scope` does not narrow it.

## Addressing a reply: `:reply` is an id **or** a name

A 24-hex-character path segment is read as an **id**; anything else as a
**name**. Names are unique per account, which is what makes addressing by the
name an agent typed safe — and it is the only identifier the panel has at the
moment of picking one.

There is no fallback between the two. A 24-hex id that no longer exists is a
`404`, never a name lookup, so a request for a deleted reply cannot quietly match
a different one that happened to be named after its id. The one real ambiguity is
a reply *named* 24 hex characters: it would be read as an id and 404. Rename it.

## The reply object

```ts
interface CannedReply {
  id: string;
  name: string;                      // unique per account; what the agent types after `/`
  type: 'CANNED' | 'QUICK';
  channel: 'whatsapp' | 'sms' | 'email' | 'rcs' | 'webchat';
  messages: CannedReplyMessage[];
  createdAt: string;                 // ISO
  updatedAt: string;                 // ISO
}
```

`channel` is a channel **type**, never a channel id, so one reply works across
every number on the account. `whatsapp` is the only value the panel offers today,
and the reason is `whatsapp_api` below: a stored message is a literal WhatsApp
Cloud API message object, so a reply is only sendable on a channel that speaks
that shape.

`messages` comes back in full from **every** endpoint, `list` included. It is the
entire point of the record, and a picker that had to fetch each reply before it
could show what the reply says would make one request per keystroke.

## The message object

```ts
interface CannedReplyMessageV2 {
  version: '2';
  whatsapp_api: MessageContent;      // the payload as the provider takes it
  internal?: Record<string, unknown>; // the editor's working copy; never read by the server
}
```

`whatsapp_api` is the same object `crm.inbox.messages.send()` accepts as
`content`. That is the point: picking a reply *is* sending its payloads, with no
translation step in between.

```json
{ "version": "2",
  "whatsapp_api": { "type": "text", "text": { "body": "Hi!", "preview_url": false } } }
```

```json
{ "version": "2",
  "whatsapp_api": { "type": "image", "image": { "link": "https://...", "caption": "Our menu" } } }
```

```json
{ "version": "2",
  "whatsapp_api": { "type": "interactive", "interactive": {
      "type": "button",
      "body": { "text": "Pick one" },
      "action": { "buttons": [ { "type": "reply", "reply": { "id": "btn_0", "title": "Yes" } } ] } } } }
```

`internal` is the form state a composer needs to **reopen** the message for
editing — which media type was chosen, whether the upload was still local, the
button rows before they were flattened into an action. Stored and returned
verbatim, never read by the server. It is optional: a reply created through the
API without one is valid, and an editor just opens it in whatever state it can
infer from `whatsapp_api`.

### Variables are not substituted here

`{{first_name}}` and friends are stored **literally**. Substitution happens at
the moment of sending, against the contact in front of the agent — there is no
contact when a reply is written, so there is nothing here to substitute against.

### Reading older rows

Rows written by the previous editor are still in the collection and carry a
different shape entirely: a flat `type` plus a `components` array in template
form. They come back exactly as stored, because synthesising a `whatsapp_api` for
them would mean inventing a payload nobody approved.

Narrow before you read:

```ts
for (const message of reply.messages) {
  if (message.version === '2') {
    send(message.whatsapp_api);
  } else {
    // A v1 row. Render it read-only, or ask the user to re-save the reply.
  }
}
```

New writes are v2 only — there is no way to create a v1 row through this API.

---

## list

```ts
crm.cannedReplies.list(query?: Partial<ListCannedRepliesQuery>): Promise<Paginated<CannedReply>>
```

`GET /v1/audience/canned-replies` · `canned_replies:read` · **200**

Offset paginated, newest first.

### Query

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |
| `search` | string | — | 1–120 chars. Matches the **name**, case-insensitively, anywhere in it. The term is escaped, so `(` and `.` are searched for rather than compiled. |
| `type` | `'CANNED' \| 'QUICK'` | — | — |
| `channel` | channel **type** | — | e.g. `whatsapp`. Not a channel id. |

```ts
// What the chat panel asks for: the replies usable on the open chat's channel.
const { data } = await crm.cannedReplies.list({ channel: 'whatsapp', rows: 100 });
```

To count without fetching, ask for one row and read the total:

```ts
const { pagination } = await crm.cannedReplies.list({ rows: 1 });
pagination.total; // how many replies the account has
```

> There is no `isListing` flag. Legacy had one, and all it dropped from the
> response was `createdAt` and `updatedAt` — it kept `messages`, the only field
> in the record with any weight.

---

## get

```ts
crm.cannedReplies.get(ref: string): Promise<CannedReply>
```

`GET /v1/audience/canned-replies/:reply` · `canned_replies:read` · **200**

`ref` is an id or a name — see [addressing](#addressing-a-reply-reply-is-an-id-or-a-name).

`404 not_found` if the reply is not the caller's.

```ts
const reply = await crm.cannedReplies.get('price list');
```

---

## create

```ts
crm.cannedReplies.create(input: CreateCannedReplyInput): Promise<CannedReply>
```

`POST /v1/audience/canned-replies` · `canned_replies:write` · **201**

### Body

| Field | Type | Required | Default | Notes |
| --- | --- | --- | --- | --- |
| `name` | string | yes | — | Trimmed, 1–120 chars. Unique per account. |
| `type` | `'CANNED' \| 'QUICK'` | yes | — | — |
| `channel` | channel type | no | `'whatsapp'` | — |
| `messages` | `CannedReplyMessageInput[]` | yes | — | 1–10 entries. See [the message object](#the-message-object). |

`messages[].version` defaults to `'2'` and is the only accepted value;
`messages[].whatsapp_api` is required; `messages[].internal` is optional.

```ts
const reply = await crm.cannedReplies.create({
  name: 'price list',
  type: 'CANNED',
  channel: 'whatsapp',
  messages: [
    { version: '2', whatsapp_api: { type: 'text', text: { body: 'Here you go' } } },
    { version: '2', whatsapp_api: {
        type: 'document',
        document: { link: 'https://.../prices.pdf', filename: 'prices.pdf' } } },
  ],
});
```

### Errors

| Status | Code | When |
| --- | --- | --- |
| 409 | `conflict` | The name is already used on this account. |
| 422 | `invalid_canned_reply` | A `QUICK` reply holds more than one message, or one that is not `text`. |
| 422 | `validation_failed` | `messages` is empty or longer than 10; a message has no `whatsapp_api.type`; `name` is blank. |

The `QUICK` rule is enforced here because legacy did not: it stored a `QUICK`
reply holding an image happily, and the panel then refused to use it forever —
the only explanation being a toast at the moment an agent reached for it.

---

## update

```ts
crm.cannedReplies.update(ref: string, input: UpdateCannedReplyInput): Promise<CannedReply>
```

`PATCH /v1/audience/canned-replies/:reply` · `canned_replies:write` · **200**

`ref` is an id or a name. The body is any subset of `create`'s.

`messages` is replaced **whole**, never merged: a reply is an ordered sequence,
and there is no sensible way to patch element two of a list whose length is also
changing. Send the array you want stored.

Renaming works. It silently did not in legacy, whose update built its `$set` from
`messages` alone and discarded every other field — while still *requiring* `type`
and `channel` in the request it then ignored.

An empty body is a no-op and returns the reply as it stands.

### Errors

| Status | Code | When |
| --- | --- | --- |
| 404 | `not_found` | No such reply on this account. |
| 409 | `conflict` | A rename into a name that is already used. |
| 422 | `invalid_canned_reply` | The **merged** result breaks the `QUICK` rule. |

That last one is checked against the merge, so flipping a three-message reply to
`QUICK` is refused — while renaming one that *already* breaks the rule is not.
The check runs only when the patch touches `type` or `messages`: a rename alone
leaves a reply exactly as valid as it already was, and running the rule
regardless would make a v1 row unrenameable, punishing existing data for a rule
introduced after it was written.

```ts
await crm.cannedReplies.update('price list', {
  messages: [{ version: '2', whatsapp_api: { type: 'text', text: { body: 'Updated prices attached' } } }],
});
```

---

## delete

```ts
crm.cannedReplies.delete(ref: string): Promise<void>
```

`DELETE /v1/audience/canned-replies/:reply` · `canned_replies:write` · **204**, no body.

`ref` is an id or a name. `404 not_found` if the reply is not the caller's.

Nothing else holds a reference to a canned reply — a sent message is a message
row, with its own copy of the content — so a delete leaves nothing dangling.

---

## Events

Each write publishes one, for panels that cache the list:

| Event | Payload |
| --- | --- |
| `canned_reply.created` | the full `CannedReply` |
| `canned_reply.updated` | the full `CannedReply` |
| `canned_reply.deleted` | `{ id, name }` |

The delete carries the **name** as well as the id, because a panel caching
replies by name — which is how an agent picks them — has no id to evict by.
