# Text messaging (SMS)

Each client workspace can get its own phone number through Zernio, register it with US carriers (A2P 10DLC), and send and receive texts in the shared inbox. Opt-outs are honoured automatically.

Implemented against Zernio's OpenAPI specification with a mocked provider. No number was bought, no registration was filed and no text was sent while building it. See "Not live-tested" below.

## Before you start

The person who installed the app needs to do three things once.

1. Set `ZERNIO_API_KEY` on the Convex backend and assign the workspace a Zernio profile in Settings. A phone number is bought into that profile, so each client keeps its own numbers.
2. Run webhook setup again in Settings (Configure). It now adds `message.delivered`, `message.failed`, `sms.registration.status_updated` and `sms.registration.action_required` to the subscription and keeps every event that was already there. Pass `includeTexting: false` to `setup:webhook` to leave them out.
3. Turn on usage-based billing with a payment method in the Zernio account. Numbers and carrier registrations are billed by Zernio to that account. Without it the app reports that billing needs to be set up and nothing is bought.

## Setting up a workspace

Everything is under Settings, in the Text messaging area. Only owners and administrators can change it. Other members see the current state.

1. **Get a number.** Enter a US area code and pick a number. The app shows the monthly price that Zernio's catalog returned for a new US local number and asks you to confirm it. If Zernio returns no price, the number cannot be bought from the app. If you already own a number in the workspace's Zernio profile, choose "I already have a number in Zernio" instead.
2. **Turn on texting.** This happens automatically after a purchase when the carrier is ready. Otherwise press "Turn on texting". The number can receive texts from this point.
3. **Register with US carriers.** A US number cannot send until a registration is approved. Either fill in the form yourself, or press "Send my client a link" and send the link to the business owner. The link works once, for seven days, and needs no Zernio login.
4. **Wait for approval.** The area shows where the registration stands and what happens next. Administrators get an in-app notification (and an email when mail is configured) when it is approved, declined, or needs an answer.

### The registration form

Two kinds are supported: a registered business with a tax ID (standard 10DLC) and one person without a tax ID (sole proprietor 10DLC). Toll-free verification is not included.

- "Check my answers" runs Zernio's dry run first. Findings marked as blocking are listed separately from suggestions. Nothing is filed and nothing is billed by the check.
- "Submit registration" is only available for the exact answers that were checked, within 24 hours. With blocking findings you must tick "Submit anyway".
- Sole proprietors get a verification code by text after submitting. Enter it in the same area. "Send a new code" requests another.
- When a reviewer asks for changes, the request appears with one answer box per point.

The business details, including the tax ID, are passed to Zernio and are not stored in the app. The app keeps the registration's id, type, status, display name, covered numbers, decline reason and any open change request.

## Receiving and replying

- An incoming text arrives on the existing Zernio webhook as `message.received` with `platform: "sms"`. It opens or continues a conversation in the inbox, creates or links a contact, saves the phone number on a new contact, and can start workflows and keyword rules like any other channel.
- Text conversations show a text message mark in the inbox. There is no 24-hour reply window.
- Replies are sent with `POST /v1/sms/messages` from the workspace's number to the contact's number, through the same outbox as other channels.
- The composer explains when a reply is blocked: the number is not approved yet, the contact opted out, or the text is longer than 10 message parts. It also says when a reply will send as more than one text.
- Delivery results from the carrier appear next to each sent text as "Delivered" or "Not delivered" with the carrier's reason.

Workflows on the text channel can start from a keyword, an exact match, a prefix, a first message or any message. Story, comment and button triggers do not apply.

## Starting a text

A member can text a contact first from the contact's editor ("Text") when all of these are true.

- The contact has a full phone number.
- The workspace has a number that is approved to send.
- Permission to text is recorded for that contact and that phone number.
- Nobody on that phone number has opted out.

"Record permission to text" stores how the person agreed, an optional note, who recorded it and when. It is the member's statement that consent was collected. The app does not collect consent from the public on its own. If the contact's phone number changes, permission must be recorded again for the new number.

### For developers: queue a first text from another feature

```ts
import { queueFirstText } from "./smsStore";

const { outboxId, conversationId, duplicate } = await queueFirstText(ctx, {
  workspaceId,
  contactId,
  text: "Hi, it is Sample Plumbing about your quote.",
  logicalKey: `lead:${leadId}:welcome`, // stable per message, 1 to 160 characters
  numberId, // optional: one specific workspace number
});
```

Call it inside a mutation. It enforces the same rules as the "Text" button, reuses an existing text conversation with that phone number, and returns the first result when called again with the same `logicalKey` (the same key with different text throws). It throws a `ConvexError` with a plain reason when the text cannot be queued. The rules are checked again when the worker claims the message, so a text queued before an opt-out is cancelled instead of sent. Outbox rows from this helper have `origin: "manual"` and a `logicalKey` starting with `sms:first:`.

## Opt-outs

- A text that is exactly STOP, STOPALL, UNSUBSCRIBE, CANCEL, END, QUIT, REVOKE or OPTOUT opts the phone number out. The conversation is suppressed, running workflows stop, and the number appears in the opt-out list in Settings.
- Only the contact can opt back in, by texting START or UNSTOP to the same number. A teammate cannot record permission over a STOP.
- If Zernio refuses a send with 409 because the recipient opted out, the send is marked failed, the conversation is suppressed and the phone number is added to the opt-out list.
- A teammate can mark a contact "do not text". That mark can be lifted by recording permission again.
- HELP is answered by the carrier. The app stores the message and does not start a workflow for it.

Other channels keep their existing behaviour: STOP, UNSUBSCRIBE or CANCEL suppresses the conversation and nothing clears it automatically.

## What is automated

- Buying the confirmed number once, then turning on texting when the number is active.
- Linking the number's SMS account as an inbox account so incoming texts are accepted.
- Applying registration webhooks, notifying administrators, and a read-only refresh of the workspace's numbers after a registration status change.
- **Opt-outs, funnel welcome texts, and delivery results.** Opt-out and opt-in keywords, 409 carrier opt-out refusals, delivery results, and optional **Funnel Lead Routing → Send an automatic welcome text (SMS)** (which starts off, requires an approved number, records `funnel_form` consent for consenting leads with a valid phone number, and skips opted-out numbers).

## Boundaries

- **One client per registration.** Registrations are account-wide at Zernio. The app always sends `phoneNumbers` explicitly, because leaving it out covers every unregistered number on the account. A registration from Zernio's list is only linked to a workspace when every number it covers belongs to that workspace. "Use this business's approved registration" is only offered when the registration Zernio names is already recorded, approved, for the same workspace. Zernio chooses the registration on that call, so the app re-reads the choice before the call and compares the answer after it. If the answer is a different registration, sending stays off for that number and administrators are told to contact Zernio support.
- **Unknown outcomes are held, not retried.** A timeout or 5xx on a purchase, a registration or a send is recorded as unknown. Purchases and registrations block a new attempt until a person presses "Check with Zernio" or "Check status". Texts stay as "Send uncertain" in the thread. This includes Zernio's 503 on purchase, which its documentation describes as safe to retry: the app still leaves that decision to a person.
- **Price.** The only price shown is the monthly number price from Zernio's catalog (`GET /v1/phone-numbers/countries`). The purchase is refused if that price changed between confirming and buying. Carrier registration fees are not returned by the API, so the app tells the user to check them in Zernio and shows no amount.
- **US local numbers only** can be bought from the app. Numbers bought elsewhere in the same profile can be synced in.
- **Text only from the composer.** Picture messages are received and shown. Sending pictures from the inbox is not enabled for texts.
- **Not included:** toll-free verification, appeals of rejected campaigns, document upload for change requests (paste a public https link instead), releasing a number, deactivating a registration, scheduled texts, bulk texting, and sender IDs.
- **Opt-out list.** The list in Settings is this app's record for the workspace. Zernio keeps its own account-wide export (`GET /v1/sms/opt-outs`). A teammate's "do not text" mark is enforced by this app and is not sent to Zernio.
- **Channel sync.** "Sync channels" in Settings does not change texting numbers. They are managed in the Text messaging area.

## Not live-tested

Automated tests use synthetic data and a mocked provider. They cover workspace isolation, administrator-only purchasing, idempotent purchase and the unknown-outcome hold, refusal to reuse another client's registration, registration webhook routing, incoming texts, STOP then START, consent for a first text, the 409 opt-out refusal and delivery results.

These points follow the specification but have not been confirmed against the live service.

- That the SMS account id returned by `POST /v1/phone-numbers/{id}/sms` is the `account.accountId` on incoming text webhooks. The app binds that id. If they differ, incoming texts are recorded as `unbound_account` in the events table.
- That the `conversationId` returned by `POST /v1/sms/messages` equals the `message.conversationId` on later webhooks. The app also matches a reply on the phone number, so a mismatch does not split the thread.
- That the message id on delivery webhooks equals the id returned by the send. The app also tries `platformMessageId`. If neither matches, the result is stored but not shown on a message.
- The exact body of the 409 opt-out refusal on `POST /v1/sms/messages`. The app looks for the documented `recipient_opted_out` code or opt-out wording. Any other 409 is treated as unknown.
- Whether `POST /v1/inbox/conversations/{conversationId}/messages` accepts text conversations. The specification does not say, so the app does not use it for texts.
- The accepted values for `campaign.usecase`, which the specification leaves as free text. The form offers the carrier registry's standard names and relies on Zernio's check.
- Real carrier behaviour: approval times, throughput, filtering and deliverability.

A first live run should use one number and one registration for the installer's own business, with the Zernio dashboard open to confirm each step.

## Where the code lives

- `convex/smsModel.ts`: tables for numbers, registrations, purchases, consent and delivery results.
- `convex/sms.ts`: queries and mutations. `convex/smsWorkers.ts`: provider calls. `convex/smsStore.ts`: rules shared with the inbox and outbox, and `queueFirstText`.
- `src/lib/sms.ts`: phone, keyword, length, registration and status-sentence logic. `src/lib/sms-api.ts`: typed function references.
- `src/components/text-messaging.tsx`: the Settings area. `src/components/sms-tools.tsx`: inbox and contact pieces.
- `tests/sms.spec.ts` and `tests/sms.test.ts`.
