# Templates

`crm.templates` — `/v1/channels/:channelId/templates`

WhatsApp message templates, per channel.

A template is **local until it is submitted to Meta**. Create it as a `draft`,
or pass `applyForApproval: true` to send it straight on, at which point it
becomes `pending` and Meta decides. `sync` pulls Meta's current view back over
ours, which is how approvals and rejections arrive without waiting on a webhook.

Every method takes the channel id first. A template id belonging to another
channel is a `404` rather than a match.

| Action | Route | Scope |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/channels/:channelId/templates` | `channels:read` |
| [`get`](#get) | `GET /v1/channels/:channelId/templates/:id` | `channels:read` |
| [`create`](#create) | `POST /v1/channels/:channelId/templates` | `channels:write` |
| [`update`](#update) | `PATCH /v1/channels/:channelId/templates/:id` | `channels:write` |
| [`delete`](#delete) | `DELETE /v1/channels/:channelId/templates/:id` | `channels:write` |
| [`sync`](#sync) | `POST /v1/channels/:channelId/templates/sync` | `channels:write` |

**Permissions** — the feature is `CRM.TEMPLATE`, flat and with no plan option of
its own. A team member needs the key; an owner does not.

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

`sync` pulls the provider's templates over the stored ones, which is a write to
every template on the channel — hence `UPDATE`.

The **channel** these hang off is gated separately, per type
(`CRM.CHANNEL.WHATSAPP`, `CRM.CHANNEL.SMS`, `CRM.CHANNEL.RCS`), and that gate is
not yet applied: the type is only knowable from the channel row, and on
`/channels/:id/:prop` the verb depends on which prop is named — so both need the
handler rather than the route. Until it lands, a member holding
`CRM.TEMPLATE.LIST` can read templates on any channel the account owns.


## The template object

```ts
interface Template {
  id: string;
  channelId: string;
  type: 'whatsapp';
  status: 'draft' | 'pending' | 'approved' | 'rejected';
  source: 'MANUAL' | 'AUTO_GENERATED';
  templateId?: string;           // Meta's id; absent while still a local draft
  name: string;
  category: 'MARKETING' | 'UTILITY' | 'AUTHENTICATION';
  subCategory: string;
  parameterFormat: 'POSITIONAL' | 'NAMED';
  language: string;              // e.g. 'en_US'
  hash: string;                  // identity within the channel: name + language
  adDetails: { ad_account: string; ad_campaign: string; ad_set: string; ad_id: string };
  components: Record<string, unknown>[];  // Meta's HEADER/BODY/FOOTER/BUTTONS array
  payload?: Record<string, unknown>;      // the last payload sent to Meta
  extra?: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}
```

**Identity is name plus language.** The same name in two languages is two
templates; that pair is what `hash` encodes.

### Lifecycle

```
draft ──applyForApproval──▶ pending ──▶ approved
  ▲                            │
  └── stays local              └──────▶ rejected
```

`AUTO_GENERATED` templates are created by the platform, not by a caller.

---

## list

```ts
crm.templates.list(channelId: string, query?: Partial<ListTemplatesQuery>): Promise<Paginated<Template>>
```

`GET /v1/channels/:channelId/templates` · `channels:read` · **200**

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |
| `search` | string | — | 1–120 chars. Matches the **name and sub-category**. |
| `status` | `TemplateStatus` | — | Quick filter. |
| `category` | `TemplateCategory` | — | Quick filter. |
| `parameterFormat` | `'POSITIONAL' \| 'NAMED'` | — | Quick filter. |
| `language` | string | — | Exact language code. |

```ts
const approved = await crm.templates.list(channelId, { status: 'approved', language: 'en_US' });
```

---

## get

```ts
crm.templates.get(channelId: string, id: string): Promise<Template>
```

`GET /v1/channels/:channelId/templates/:id` · `channels:read` · **200**

---

## create

```ts
crm.templates.create(channelId: string, input: CreateTemplateInput): Promise<Template>
```

`POST /v1/channels/:channelId/templates` · `channels:write` · **201**

### Body

| Field | Type | Required | Default | Notes |
| --- | --- | --- | --- | --- |
| `name` | string | yes | — | 1–512 chars, `^[a-z0-9_]+$` — Meta's own rule. |
| `category` | `'MARKETING' \| 'UTILITY' \| 'AUTHENTICATION'` | yes | — | |
| `language` | string | yes | — | 2–15 chars, e.g. `en` or `en_US`. |
| `components` | object[] | yes | — | At least one. Meta's component array. |
| `subCategory` | string | no | `''` | Up to 120 chars. |
| `parameterFormat` | `'POSITIONAL' \| 'NAMED'` | no | `'POSITIONAL'` | `{{1}}` vs `{{name}}`. |
| `source` | `'MANUAL' \| 'AUTO_GENERATED'` | no | `'MANUAL'` | |
| `payload` | object | no | — | |
| `extra` | object | no | — | |
| `adDetails` | partial | no | all `''` | Click-to-WhatsApp ad attribution. |
| `applyForApproval` | boolean | no | `false` | Submit to Meta immediately. |

Re-using a `name` + `language` pair that already exists on the channel is a
`409 conflict`.

**Meta goes first.** With `applyForApproval: true`, the template is submitted
before any row is written, so a rejection leaves nothing behind — it surfaces as
a `400` carrying Meta's reason.

```ts
const template = await crm.templates.create(channelId, {
  name: 'order_update',
  category: 'UTILITY',
  language: 'en_US',
  components: [
    { type: 'BODY', text: 'Hi {{1}}, your order {{2}} has shipped.' },
  ],
  applyForApproval: true,
});

template.status; // 'pending'
```

---

## update

```ts
crm.templates.update(channelId: string, id: string, input: UpdateTemplateInput): Promise<Template>
```

`PATCH /v1/channels/:channelId/templates/:id` · `channels:write` · **200**

Every field from `create`, plus `status`, all optional. At least one is required.

### What may change depends on where the template is

A **draft** is fully editable. **Once it is with Meta its identity is fixed**,
and `name`, `language`, `category`, `subCategory`, `parameterFormat`, `source`
and `adDetails` are silently ignored — only `components`, `payload` and `extra`
still move.

### Nothing is sent to Meta unless you ask

Pass `applyForApproval: true`, or a `status` other than `'draft'`. Then:

- a **draft** is submitted for the first time;
- a template **already at Meta** is updated in place.

Either way the row comes back `pending`. A non-draft with no Meta id is
`409 template_not_submitted`.

Changing a draft's `name` or `language` into a pair that already exists is a
`409 conflict`.

```ts
// Edit the copy and resubmit
await crm.templates.update(channelId, id, {
  components: [{ type: 'BODY', text: 'Hi {{1}}, order {{2}} is on its way.' }],
  applyForApproval: true,
});
```

---

## delete

```ts
crm.templates.delete(channelId: string, id: string): Promise<void>
```

`DELETE /v1/channels/:channelId/templates/:id` · `channels:write` · **204**, no body.

A **draft** only exists here and is simply removed. Anything submitted is
**deleted at Meta first**, so no row is kept for a template the WABA no longer
has. If Meta refuses, the call fails with `400 template_deletion_failed` and the
row stays.

---

## sync

```ts
crm.templates.sync(channelId: string): Promise<TemplateSyncResult>
```

`POST /v1/channels/:channelId/templates/sync` · `channels:write` · **200**

Pulls the channel's templates from Meta and writes their current state over
ours, so approvals and rejections show up without waiting for a webhook.

Note the path: **`sync` is a sibling of `:id`, not a child of it.**

```ts
{ fetched: number, created: number, updated: number, skipped: number }
```

`skipped` is templates Meta returned that are not storable here — one in a
category this platform does not model, for instance. `400 template_sync_failed`
if Meta refuses the listing.

```ts
const result = await crm.templates.sync(channelId);
console.log(`${result.updated} templates changed status`);
```
