# Campaigns

`crm.campaigns` — `/v1/campaigns`

One message sent to many people.

| Action | Route | Notes |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/campaigns` | cursor-paged |
| [`get`](#get) | `GET /v1/campaigns/:id` | |
| [`create`](#create) | `POST /v1/campaigns` | you supply `filters` |
| [`createBulk`](#createbulk) | upload + `POST /v1/campaigns` | **numbers or CSV; the SDK does the rest** |
| [`createGroup`](#creategroup) | uploads + `POST /v1/campaigns` | **one bucket per channel or template** |
| [`uploadReceivers`](#uploadreceivers) | upload only | the file half of `createBulk` |
| [`update`](#update) | `PATCH /v1/campaigns/:id` | before it runs |
| [`trigger`](#trigger) | `POST /v1/campaigns/:id/trigger` | **the only call that sends** |
| [`schedule`](#schedule) | `POST /v1/campaigns/:id/schedule` | `trigger` with a required time |
| [`cancel`](#cancel) | `POST /v1/campaigns/:id/cancel` | |
| [`delete`](#delete) | `DELETE /v1/campaigns/:id` | |

**Permissions** — the feature is `CRM.CAMPAIGN`. A team member needs the key; an
owner does not.

| Action | Key |
| --- | --- |
| `list` | `CRM.CAMPAIGN.LIST` |
| `get`, the report endpoints | `CRM.CAMPAIGN.READ` |
| `create`, `createBulk`, `createGroup`, `uploadReceivers` | `CRM.CAMPAIGN.CREATE` |
| `update` | `CRM.CAMPAIGN.UPDATE` |
| `trigger`, `schedule`, `cancel` | `CRM.CAMPAIGN.SEND` |
| `delete` | `CRM.CAMPAIGN.DELETE` |

`cancel` is under `SEND` rather than `UPDATE` on purpose: it is control of a
dispatch, and somebody who may not launch a campaign should not be able to stop
one that is going out.

A campaign is not assigned to anybody, so a role's `data_scope` does not narrow
this list — a member who holds `CRM.CAMPAIGN.LIST` sees the account's campaigns.


---

## Creating a campaign does not send it

Two steps, always:

```ts
const campaign = await crm.campaigns.create({ name: 'Diwali offer', messages });
// nothing has gone out; `campaign.scheduledAt` is undefined

await crm.campaigns.trigger(campaign.id);                              // send now
await crm.campaigns.trigger(campaign.id, { scheduledAt: isoInstant }); // or at a time
```

A created campaign is a **draft**: `pending`, with no `scheduledAt` and an empty
`triggerInfo`. You can `update` it, show it for review, and nothing will send it.
The sender cannot even see it — a campaign with no `scheduledAt` is not a
campaign with a moment.

`trigger` is what arms it, and is also what records *who* armed it: the server
stamps `triggerInfo` (the caller, their ip, the moment) as part of that call.
That is why a send time is **rejected** on `create` and `update` rather than
accepted — a campaign that could be armed by a write could go out with nobody
named against it.

| | `create` / `update` | `trigger` / `schedule` |
| --- | --- | --- |
| `scheduledAt` in the body | **`422`** | that is the point |
| writes `triggerInfo` | no | yes |
| writes `member` | on `create`, by a team member | no |
| campaign becomes sendable | no | yes |

`member` is the other half of that record: the team member who **wrote** the
campaign, stamped at `create` from their token. `triggerInfo.psuid` is who armed
it, which is a later act and can be somebody else. Both are server-set and
refused from a body; an account holder's campaign carries no `member`, because
the campaign is already theirs.

**"Now" is not instant.** `trigger` with no time arms the campaign about a minute
out (`CAMPAIGN_IMMEDIATE_DELAY_SECONDS`), and [`cancel`](#cancel) still stops it
in that window. A second `trigger` on a campaign that is armed but not yet picked
up just re-arms it, so a double-click costs a fresh window rather than a second
send.

---

## The audience is one field with five modes

A campaign's recipients live in `filters`, and **the mode is decided by the shape
of the array**, not by a separate selector:

| `filters` | Audience |
| --- | --- |
| `[]` | every contact in the account |
| `ContactFilterEntry[]` | a segment — see [contact filter](../contact-filter.md) |
| `[{ numbers, hash }]` | a bulk list from an uploaded file |
| `[{ type: 'channel' \| 'template', numbers, hash, … }]` | a **group** campaign: one bucket per channel or template |
| `[{ type: 'status' \| 'selection', … }]` | re-target of an earlier campaign |

Modes cannot be mixed. Bulk and re-target take **exactly one entry** —
everything downstream reads `filters[0]` and ignores the rest, so the server
rejects a second entry rather than silently dropping it.

**Group is the exception**: many entries are the whole point, one per bucket. Its
buckets must all split the same way, though — a `channel` bucket beside a
`template` bucket describes two different splits of the same recipients, and is
refused.

### Recipients are counted when the campaign sends, not when you create it

`campaign.receivers` is `0` on a campaign you just created. The audience is a
stored *query* — even a bulk list is a file the sending service reads later — so
the final count is only known at send time, and a campaign scheduled for next
week can legitimately reach a different number of people than the preview
showed.

`createBulk` returns its own `receivers` count for exactly this reason: it is the
number of rows written into the file, known now, and it is what you should show a
user.

---

## `createBulk`

The bulk path, start to finish. You hand it numbers or a CSV; it hands you a
created campaign.

```ts
const { campaign, receivers, skipped, duplicates } = await crm.campaigns.createBulk({
  name: 'Diwali offer',
  audience: { numbers: '919000000001, 919000000002\n919000000003' },
  messages: [{ channel: { id: channelId }, message: template }],
});

console.log(`Sending to ${receivers}`);          // 3
```

### Why this is a method and not a recipe

A bulk recipient list does not travel inside the campaign. A million numbers is
not a request body, and the numbers are personal data that should not sit in an
API log. So the list takes a different route:

1. the recipients are **encrypted** into a file, under a secret generated for
   that one file;
2. the file is **uploaded** to object storage through a presigned URL, so the
   bytes never pass through the API;
3. the campaign stores a **pointer** — `{ numbers: <url>, hash: <secret> }` — and
   the sending service fetches and decrypts the file when the campaign runs.

Every one of those steps has to be exactly right or the campaign fails at send
time, hours later, with nothing useful in the error. That is why it is one call
here rather than a page of instructions.

### The four ways to describe an audience

#### Numbers

```ts
audience: { numbers: '919000000001, 919000000002\n919000000003' }
audience: { numbers: ['+91 90000 00001', '919000000002'] }
```

A string is split on **commas, newlines, tabs, semicolons and spaces — all of
them**, in any mixture. Each entry is reduced to digits, so `+91 90000-00001`
and `919000000001` are the same number. Entries with no digits are dropped.

No per-recipient variables: use one of the forms below if your template has
placeholders.

#### CSV or TSV text

```ts
audience: { csv: await file.text(), recipientColumn: 'phone' }
```

The first row is the header. The delimiter is detected (tab, then semicolon, then
comma) unless you pass `delimiter`. Quoted fields are parsed properly, so
`"1,299"` is one value and `"He said ""yes"""` is one field containing a quote.

**Every column becomes a template variable**, including the recipient column
itself. Headers are normalised the same way the panel always did them —
lower-cased, with each non-alphanumeric character replaced by `_` — so
`First Name` is the variable `first_name`.

#### Rows you already parsed

```ts
audience: { rows: await sheet.getRows(), recipientColumn: 'phone' }
```

From your own CSV reader, a spreadsheet API, or a database query. Values are
stringified; the recipient column is matched by its raw name or its normalised
one.

#### Receivers you built

```ts
audience: {
  receivers: [
    { waba: '919000000001', custom_fields: [{ id: 'name', value: 'Priya' }] },
  ],
}
```

The escape hatch. Taken exactly as given — nothing is normalised, nothing is
de-duplicated.

### What it drops, and tells you about

```ts
const { receivers, skipped, duplicates } = await crm.campaigns.createBulk({ … });
```

- `skipped` — entries with no usable number: blank cells, a `Total` footer row,
  `N/A`.
- `duplicates` — entries whose number already appeared.

Both are **counted and reported** rather than passed over. A row file that is
one-third blank is something you want to know about before the send, not after.

De-duplication is on by default because the cost of a duplicate is not a wasted
table row — it is the same person getting the same marketing message twice,
billed twice, and more likely to report the sender. Pass `dedupe: false` if you
genuinely want two sends to one number.

Nothing is uploaded and no campaign is created if the audience resolves to zero
recipients, or to more than **1,000,000** — both throw `validation_failed`.

### Previewing before you send

The helpers are exported, so a UI can resolve an audience and show the user what
it found before anything is uploaded:

```ts
import { resolveAudience, parseDelimited } from 'ab-ecosystem-cpass';

const { headers } = parseDelimited(text);            // offer these as the column picker
const { receivers, skipped, duplicates } = resolveAudience({ csv: text, recipientColumn });

// "12,480 recipients · 3 duplicates dropped · 2 rows without a number"
```

`resolveAudience` does no I/O and no crypto. It is the same function `createBulk`
calls, so what you preview is what gets sent.

### Scheduling one

```ts
const { campaign } = await crm.campaigns.createBulk({
  name: 'Renewal reminder',
  audience: { csv, recipientColumn: 'phone' },
  messages: [{ channel: { id: channelId }, message: template }],
});

await crm.campaigns.trigger(campaign.id, { scheduledAt: '2026-11-01T04:30:00.000Z' });
```

The file is uploaded during `createBulk`; the campaign itself does not go out
until you trigger it. Passing `scheduledAt` to `createBulk` is refused — see
[creating does not send](#creating-a-campaign-does-not-send-it).

### Two things to be careful about

**The `hash` is a credential, not a checksum.** It is the key the file is
encrypted under, and the file's URL is a public storage link. Anyone holding both
can read the recipient list. Do not log it, do not put it in an error report, and
do not copy a `filters` entry into another system.

**A campaign is not rolled back if creation fails after upload.** If the upload
succeeds and the `POST` then fails, you have an uploaded file and no campaign —
harmless, but the file stays. Retry with [`uploadReceivers`](#uploadreceivers)
and `create` if you want to avoid re-uploading a large list.

---

## `createGroup`

Splits the recipients into buckets and sends each through a different channel, or
renders each with a different message.

```ts
const { campaign, buckets, receivers } = await crm.campaigns.createGroup({
  name: 'Diwali offer',
  distributeBy: 'channel',
  buckets: [
    { channel: channelA, audience: { rows: north, recipientColumn: 'phone' } },
    { channel: channelB, audience: { rows: south, recipientColumn: 'phone' } },
  ],
  messages: [{ channel: { id: channelA }, message: template }],
});
```

`distributeBy: 'template'` instead splits across the messages, and each bucket
names its message by `pairIndex`:

```ts
buckets: [
  { pairIndex: 0, audience: { numbers: variantA } },
  { pairIndex: 1, audience: { numbers: variantB } },
]
```

### Three ways it differs from `createBulk`

Each of these is something that would be wrong if you assembled the payload by
hand:

- **One file per bucket.** Each bucket is encrypted under its own secret and
  uploaded separately, so `filters` carries one entry per bucket. This is the
  only audience mode with more than one entry.
- **A different file format.** A bucket file is a `||`-delimited table with a
  header row — not the JSON array a bulk file holds. The reading side picks by
  campaign type, so the wrong encoding decrypts cleanly and then parses to
  nothing.
- **Columns are fixed by the first recipient.** A table has one header, so every
  row carries the same variables in the same order. Values are addressed by
  column name, so a row whose variables arrived in a different order is still
  written correctly; a row missing one gets an empty cell rather than a shift.

```
waba||first_name||amount
919000000001||Priya||1299
919000000002||Ravi||499
```

Newlines and literal `||` inside a value are replaced with a space. The format
has no escape for either, and one would end the row early and shift every later
value into the wrong column.

### Empty buckets are dropped, not refused

A bucket whose audience resolves to nobody is left out of `filters` entirely.
Distributing a list across six channels routinely leaves one or two with nothing
in them, and that is not an error. The call fails only when **every** bucket is
empty — or when the buckets together exceed 1,000,000 recipients.

`result.buckets` therefore holds only the buckets that were uploaded, in the
order given, each with its own `receivers` / `skipped` / `duplicates` and its
`fileUrl`. The top-level counts are the totals.

### De-duplication is per bucket

A number appearing in two buckets is sent to twice. That is usually the intent —
the buckets are different channels — and it is not something this can
second-guess. Within one bucket, duplicates are dropped as everywhere else.

### Extra keys ride along

```ts
{ channel: channelA, extra: { priority: 2 }, audience: { … } }
```

`extra` is merged onto the filter entry beside `numbers` and `hash`. The campaign
contract passes anything it does not recognise through to the sending service
untouched, so this is the seam for distribution metadata the SDK does not model.
It cannot overwrite `numbers`, `hash`, `type` or `count`.

### How it is dispatched

Stored as `type: 'group_campaign'`, which is what the campaign list and reports
show. On the hand-off to the sending service it is **relabelled
`bulk_campaign`**, because the two differ only in how many receiver files there
are and the bulk handling is what reads a file of numbers.

The filters are **not** translated along with the name — every bucket, with its
channel binding and its count, is forwarded exactly as stored.

---

## `uploadReceivers`

The file half on its own.

```ts
const filter = await crm.campaigns.uploadReceivers(receivers);
// { numbers: 'https://…/im_m95ibl56.txt', hash: '081389a62af715e91f92026eac67910a' }

// For a group bucket, which uses the || table format:
const bucket = await crm.campaigns.uploadReceivers(receivers, undefined, 'table');

await crm.campaigns.create({
  name: 'Diwali offer',
  type: 'bulk_campaign',
  filters: [filter],
  messages: [{ channel: { id: channelId }, message: template }],
});
```

Useful when the two halves should fail independently: a large upload you do not
want to repeat if campaign creation is rejected, or several campaigns addressed
to one uploaded list.

Keep the returned `hash` with the URL. There is no copy of it anywhere else —
lose it and the file cannot be decrypted by anything, including us.

---

## How the file is encrypted

Documented because it is a cross-service contract: the sending service decrypts
these, so the scheme cannot be changed on one side alone.

```
secret      = 16 random bytes, hex                 -- the campaign's `hash`
key         = md5(secret)                          -- 32 hex characters
key bytes   = the ASCII bytes of that hex          -- 32 bytes, so AES-256
iv          = ASCII bytes of '678025308de70905'
plaintext   = JSON.stringify([{ waba, custom_fields }, …])   -- bulk
            | waba||col||col
… (a || table with a header row)  -- group bucket
ciphertext  = AES-256-CBC, PKCS#7 padded
file body   = base64(ciphertext)
```

Two parts are counter-intuitive and both are deliberate, because this has to
match what `CryptoJS.AES.encrypt(text, keyWordArray, { iv })` produces:

- **The key is the hex *text*, not the 16 digest bytes.** `md5()` returns a
  32-character string, parsed as UTF-8 — which is 32 bytes, hence AES-256. Using
  the raw digest would be AES-128 and would not decrypt.
- **There is no `Salted__` header.** CryptoJS writes one only when deriving a key
  from a passphrase; given a key directly, its default formatter emits bare
  base64.

The fixed IV is a known weakness — it means two files encrypted under the same
secret share leading blocks. What keeps it from mattering is that **the secret is
fresh for every file**, so the IV is never reused under one key. Revising the
format means a random IV prepended to the ciphertext, and it has to land on the
sending service before it lands here.

---

## `list`

```ts
const { data, nextCursor } = await crm.campaigns.list({ limit: 50, status: 'completed' });
```

| Query | Type | Notes |
| --- | --- | --- |
| `limit` | `number` | 1–100, default 50 |
| `cursor` | `string` | from the previous page's `nextCursor` |
| `status` | `pending` `processing` `completed` `failed` `cancelled` | |
| `campaignType` | `general` `payment` | |
| `type` | `string` | dispatch route, e.g. `bulk_campaign` |
| `hidden` | `boolean` | |

## `get`

```ts
const campaign = await crm.campaigns.get(id);
```

### What a campaign's `id` is

The `id` on a campaign is its own identity and the only one this API accepts —
the same value the campaign manager is handed as `broadcast.id` and stamps on
every report row as `cid`. So it is what you pass to `get`, `trigger`, `report`,
and what a re-target filter's `cid` must name.

It is a 24-character ObjectId string, but it is not the document's `_id`: that
is Mongo's key and never appears in a request or a response. The `nextCursor`
from [`list`](#list) is a paging position rather than an id — pass it back as a
cursor, never as a campaign id.

## `create`

For an audience you have already expressed as `filters` — every contact,
a segment, or a re-target. For a bulk list use [`createBulk`](#createbulk).

Returns a draft. Call [`trigger`](#trigger) to send it.

| Field | Type | Default |
| --- | --- | --- |
| `name` | `string` | required, 1–160 |
| `messages` | `CampaignMessage[]` | required, at least one |
| `type` | `string` | `general` — also decides the dispatch pacing, see [below](#trigger) |
| `campaignType` | `general` `payment` | `general` |
| `trigger` | `immediate` `schedule` | `immediate` — advisory; `trigger()` rewrites it |
| `scheduledAt` | — | **not accepted**; `422`. Pass it to [`trigger`](#trigger) |
| `channelType` | `string` | `whatsapp` |
| `messagingPattern` | `string` | `A2O` |
| `filters` | `CampaignFilter[]` | `[]` — every contact |
| `showMessageInPanel` | `boolean` | `true` |
| `isRepeating` | `boolean` | `false` |
| `repeat` | `{ every, unit, until }` | — |
| `hidden` | `boolean` | `false` |

## `update`

```ts
await crm.campaigns.update(id, { name: 'Diwali offer (revised)' });
```

Every `create` field, all optional — `scheduledAt` included, which means it is
refused here too. Only meaningful while the campaign is `pending`.

## `trigger`

```ts
await crm.campaigns.trigger(id);                                   // now
await crm.campaigns.trigger(id, { scheduledAt: '2026-11-01T04:30:00.000Z' });
```

| | |
| --- | --- |
| Route | `POST /v1/campaigns/:id/trigger` |
| Body | `{}` or `{ scheduledAt }` — ISO-8601 with an offset |
| Scope | `campaigns:write` |
| `404` | no such campaign, or not this account's |
| `409` | the campaign is not `pending` — already sending, sent, failed or cancelled |
| `409` | `channel_webhook_unset`: a channel cannot report delivery back (see below) |

Writes `trigger`, `scheduledAt` and `triggerInfo`, and nothing else. A past
`scheduledAt` is accepted and means "now".

**The webhook preflight runs here.** Before the campaign is armed, each v2
WhatsApp channel's Meta subscription is checked and repaired if it has drifted. A
channel that still cannot deliver webhooks fails the call with `409
channel_webhook_unset` and the campaign stays a draft — because that failure is
otherwise invisible: an unsubscribed channel *sends perfectly* and reports
nothing, leaving every recipient stuck at `sent` forever.

### How the campaign reaches the sender

Once armed, a poller picks the campaign up when its moment arrives and hands it
to the sending service. Which route it takes depends on `type`:

| `type` | route |
| --- | --- |
| `general` | straight to the sender |
| anything else (`bulk_campaign`, `group_campaign`, `retarget`, …) | through the account's pacing lane — `<user_id>_user_campaign`, shared with the legacy middleware — which releases one campaign per minute per account |

So an account that arms five bulk campaigns at once has them delivered to the
sender a minute apart, in the order they were armed, while a general campaign
goes immediately. This is invisible in the API — the only trace is when the
report starts filling.

## `schedule`

```ts
await crm.campaigns.schedule(id, '2026-11-01T04:30:00.000Z');
```

The same call as `trigger` with a required time. Kept because it is the name the
panel uses; new code can use either.

## `cancel`

```ts
await crm.campaigns.cancel(id);
```

## `delete`

```ts
await crm.campaigns.delete(id);
```

---

# Reporting

Campaign reporting lives on its own page: **[campaign messages](campaign-messages.md)**
— `crm.campaignMessages`.

There is no report collection and no export job. One row is written per attempted
send, its status is advanced by the channel's delivery webhooks, and every number
is counted off those rows when you ask for it:

```ts
const stats = await crm.campaignMessages.stats(id);
// { total, sent, delivered, read, replied, failed }
```
