docs: design and OpenSpec change for the WhatsApp inbox
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
085bcafe63
commit
e0df2b2e84
7 files changed
+676
No files matched your search
@@ -0,0 +1,200 @@
|
||||
# WhatsApp inbox: design
|
||||
|
||||
Date: 2026-12-02. Proposed OpenSpec change: `add-whatsapp-inbox`.
|
||||
|
||||
## Intent
|
||||
|
||||
Sales staff follow up event leads by WhatsApp today from their own phones. Nothing is recorded, and nobody else can pick up a chat. Co-Lite gets a shared, two-way WhatsApp inbox on each company's business number:
|
||||
|
||||
- Every chat is owned by the salesperson who handles the lead.
|
||||
- A WhatsApp Admin routes the chats nobody owns.
|
||||
- Every message is kept with the lead.
|
||||
|
||||
Success: an INS lead writes to INS's number and the chat lands with their salesperson within a minute. The salesperson replies from the portal, or starts a chat with an approved template. The WhatsApp Admin sees and reassigns every INS chat. Nobody at CV sees any of it.
|
||||
|
||||
## Decisions
|
||||
|
||||
From the owner (whiteboard 2026-11-26, answers 2026-11-30 and 2026-12-02):
|
||||
|
||||
| Question | Decision |
|
||||
|---|---|
|
||||
| Provider | Meta WhatsApp Cloud API, called directly (360dialog stays a fallback, not built). |
|
||||
| Shape | Full two-way inbox with assignment to sales staff. |
|
||||
| Numbers | One business number per company (INS, CV). A message to a number belongs to that number's company. Staff see only their company's chats; super admins see all. |
|
||||
| Meta accounts | Separate WhatsApp Business Account per company (2026-12-02): each company has its own account id, token and templates. |
|
||||
| Salesperson without WhatsApp access | Counts as no salesperson: the chat keeps its current owner or goes to the unassigned queue. Losing `BO_WHATSAPP` sends a person's chats back to unassigned, like being disabled (2026-12-02). |
|
||||
| Who replies | Staff see and reply only in chats they own. A WhatsApp Admin reads, replies in and reassigns any chat of their company, including to themselves. Starting a chat from a lead: an unowned chat becomes the starter's; a chat someone else owns tells the starter who owns it (2026-12-02). |
|
||||
| Starting chats | Yes, with Meta-approved templates. Outside the 24-hour window the composer only offers templates. |
|
||||
| Media | Send and receive text. Show incoming images, documents, audio, video, stickers and locations. Staff send text and templates only. |
|
||||
| Chat owner | The salesperson assigned to the lead at the lead's most recent event. If that event has no salesperson for the lead, ownership stays with the current owner. If no event ever had one, the chat sits in the unassigned queue. |
|
||||
| Manual reassignment | A WhatsApp Admin's reassignment sticks: later event assignments do not change the owner until the WhatsApp Admin reassigns again. |
|
||||
| Owner deactivated | The chat returns to the unassigned queue. |
|
||||
| Separate admin roles | "System Admin" and "WhatsApp Admin" are separate. The WhatsApp Admin is a role holding the WhatsApp admin module. |
|
||||
| Service | A new service of its own (foundation design, 2026-11-26). |
|
||||
| Secrets | The owner deploys the WhatsApp credentials to Kubernetes after the move to solvway. Code reads them from the environment only. |
|
||||
|
||||
My calls, explained below: polling instead of push, on-demand media download, templates synced from Meta, a local mock of Meta, and the number-to-company map in configuration.
|
||||
|
||||
## Goals, non-goals, anti-goals
|
||||
|
||||
**Goals:** receive and send through the Cloud API, threads per contact per company, ownership rules, the unassigned queue and reassignment, templates, the 24-hour window, delivery ticks, unread counts, a link to the lead, company scoping, an audit trail, and a fully local development and test loop with no Meta account.
|
||||
|
||||
**Non-goals (later):**
|
||||
- broadcasts or campaigns;
|
||||
- sending media;
|
||||
- WhatsApp invitations for events (the invitation design leaves a hook: the same invite link in a template);
|
||||
- chatbots or auto-replies;
|
||||
- multiple numbers per company;
|
||||
- creating or editing templates in Co-Lite (they are made in Meta's WhatsApp Manager);
|
||||
- push or websockets;
|
||||
- 360dialog.
|
||||
|
||||
**Anti-goals:**
|
||||
- A message reaching or being shown to the wrong company.
|
||||
- Message text, phone numbers or tokens in logs.
|
||||
- An unauthenticated webhook: every webhook call must carry a valid Meta signature.
|
||||
- A send that silently fails: a failed message shows as failed in the thread.
|
||||
|
||||
## Approach
|
||||
|
||||
**Recommended: a new `solvway-services-whatsapp` service with its own schema `service-whatsapp`.**
|
||||
- The service owns conversations, messages, templates and the Meta client.
|
||||
- mobile-api is the public edge, as it is for every other service. It receives Meta's webhook (`/api/public/whatsapp/webhook`), checks the signature, and passes the event to the service through the gateway. It also exposes the admin inbox API (`/api/admin/whatsapp/**`).
|
||||
- The portal adds an Inbox page under Leads.
|
||||
|
||||
**Rejected:**
|
||||
- Putting it inside the counter service, which owns leads. That ties chat traffic and Meta outages to lead capture, against the foundation decision.
|
||||
- Letting the gateway pass the webhook straight to the service. Every public endpoint today enters through mobile-api, which already has rate limiting, logging redaction and an API-key exemption list.
|
||||
|
||||
## How it works
|
||||
|
||||
### Configuration and secrets
|
||||
|
||||
All of these come from the environment, with none committed. Each company has its own Meta account, so most settings are per company code:
|
||||
- `WHATSAPP_COMPANIES`: the company codes that use WhatsApp, e.g. `INS,CV`.
|
||||
- Per company, with `<CODE>` being the company code:
|
||||
- `WHATSAPP_<CODE>_PHONE_NUMBER_ID`;
|
||||
- `WHATSAPP_<CODE>_WABA_ID`, the business account id used for templates;
|
||||
- `WHATSAPP_<CODE>_ACCESS_TOKEN`, the system-user token;
|
||||
- `WHATSAPP_<CODE>_APP_SECRET`, used for webhook signatures. Both companies may use one Meta app, in which case the values are the same.
|
||||
- `WHATSAPP_VERIFY_TOKEN`: a value we choose for the webhook handshake. It is shared, because there is one webhook URL.
|
||||
- `WHATSAPP_GRAPH_BASE_URL`: default `https://graph.facebook.com/v21.0`.
|
||||
|
||||
My call: settings live in configuration, not a table. They change only when a number changes, they are deployed with the secrets, and they need no screen. They are keyed by company code, which is stable (codes are uppercase identifiers; a rename would need the settings renamed too). A company without settings has WhatsApp switched off: its inbox says "WhatsApp is not configured", and the rest of Co-Lite still starts.
|
||||
|
||||
### Data (schema `service-whatsapp`, every table carries `company_id`)
|
||||
|
||||
- **`wa_conversation`**
|
||||
- Columns: `id`, `uuid`, `company_id`, `phone_number_id`, `contact_wa_id` (E.164 digits), `contact_name` (WhatsApp profile name), `lead_uuid` (nullable), `owner_user_id` (nullable), `owner_manual` (boolean), `last_inbound_at` (sets the 24-hour window), `last_message_at`, `last_message_preview` (first 80 characters), `created_at`.
|
||||
- Unique on (`company_id`, `contact_wa_id`).
|
||||
- **`wa_message`**
|
||||
- Columns: `id`, `uuid`, `conversation_id`, `direction` (IN/OUT), `wamid` (Meta message id, unique), `type` (text, template, image, document, audio, video, sticker, location, unsupported), `body` (text or template preview), `template_name`, `media_id`, `media_mime`, `media_filename`, `location_lat`/`lng`/`name`, `status` (OUT only: pending, sent, delivered, read, failed), `error_code`, `error_title`, `sent_by_user_id`, `created_at`, `status_at`.
|
||||
- **`wa_read`:** `conversation_id`, `user_id`, `last_read_message_id`. This is the per-user unread marker, as in babyboo's `conversation_read`.
|
||||
- **`wa_template`:** `company_id`, `name`, `language`, `category`, `status`, `body_text`, `param_count`, `synced_at`. These are the approved templates, synced from Meta.
|
||||
|
||||
DDL and rollback go in the change folder. The local seed gets the empty schema.
|
||||
|
||||
### Receiving (Meta to Co-Lite)
|
||||
|
||||
1. Meta calls `GET /api/public/whatsapp/webhook` with `hub.mode`, `hub.verify_token` and `hub.challenge`. mobile-api answers the challenge only when the token matches.
|
||||
2. Meta posts events to `POST /api/public/whatsapp/webhook`. mobile-api reads the raw body and checks `X-Hub-Signature-256`: an HMAC-SHA256 compared in constant time against each configured app secret. It rejects a bad or missing signature with 401. The service later accepts an entry only when its `phone_number_id` belongs to a company whose app secret produced the match, so one company's app cannot post into the other's inbox. mobile-api then forwards the parsed payload with the matched company codes, and answers 200 quickly, because Meta retries on errors.
|
||||
3. The service maps `metadata.phone_number_id` to a company. An unknown number id is dropped and counted, never guessed.
|
||||
- **Messages:** upsert the conversation for (company, `from`), take `contacts[].profile.name`, and insert the message once (idempotent on `wamid`, since Meta redelivers). Set `last_inbound_at` and `last_message_at`. Link the lead on first sight.
|
||||
- **Statuses:** update the OUT message's status and `status_at`. Only move forward (sent, then delivered, then read), except failed, which records `errors[0].code` and `title`.
|
||||
4. Mobile numbers in Co-Lite are E.164 with `+` (`lead.mobile_e164`), and WhatsApp ids are the same digits without it. The service compares them with the `+` added.
|
||||
|
||||
### Linking to a lead and ownership
|
||||
|
||||
- **Linking:** when a conversation is created, or when an owner is recomputed, the service asks the counter for the company's lead by `mobile_e164`, the newest lead when two share a mobile. The answer includes the lead's "latest salesperson": the salesperson of its most recently captured event lead that has one. That is the same value the Leads list already shows (`LeadRepository`), so the inbox and the Leads list never disagree.
|
||||
- **Recompute rule:**
|
||||
- When `owner_manual` is set, the owner is left alone.
|
||||
- Otherwise the owner is the latest salesperson, if that person is active and holds `BO_WHATSAPP`.
|
||||
- When there is no such person, the current owner is kept if they are still active with `BO_WHATSAPP`; otherwise the owner is null (unassigned).
|
||||
- My call, and why it matches the owner's rule: "the salesperson at the most recent event, or keep the current owner when that event has none" gives the same person as "the latest event lead that has a salesperson", because the kept owner came from an earlier event. The one difference is that "most recent" goes by capture time, not event start date, which is how the Leads list already orders them.
|
||||
- **When it runs:**
|
||||
- when a conversation is created;
|
||||
- when a WhatsApp Admin clears a manual owner ("Return to automatic");
|
||||
- when an event lead's salesperson changes or a new event lead is captured for that mobile. The counter calls the service after save. The call is best-effort and logged on failure, and a nightly job repairs any misses.
|
||||
- **Owner loses access:** when a user is disabled (`enabled` false) or their roles no longer grant `BO_WHATSAPP`, their chats go to unassigned and `owner_manual` is cleared. The trigger is a call from the user save path in mobile-api (the one place both happen), plus the same nightly job. My call: a locked-out user (too many failed logins) keeps their chats, because the lock is temporary. A company switched off needs nothing, since nobody can open its chats.
|
||||
- An unknown sender, with no lead for that mobile, gets an unassigned, unlinked conversation. Creating a lead from a chat is a later feature. For now the WhatsApp Admin sees the profile name and number.
|
||||
|
||||
### Sending (Co-Lite to Meta)
|
||||
|
||||
- **Text:** allowed only when `now - last_inbound_at < 24h`. Otherwise the API answers 409 `WINDOW_CLOSED` and the composer has already switched to templates.
|
||||
- **Template:** allowed at any time. It needs an approved template from `wa_template` with every parameter filled. It is sent as type `template`, with `language.code` and body parameters.
|
||||
- **Starting a chat:** "WhatsApp" on a lead or event lead row opens or creates the conversation for the lead's mobile in its company. If the chat has no owner, it becomes the starter's, as a manual assignment. If someone else owns it, the starter is told who, and a WhatsApp Admin can open it anyway. Only the template composer is offered until the lead replies. A lead without a mobile has no WhatsApp action.
|
||||
- **Message lifecycle:** each send inserts the message as `pending`, calls `POST /{phone_number_id}/messages`, then stores the returned `wamid` and `sent`. On an API error it stores `failed` with Meta's error code and title, and the thread shows them. The user can retry, which makes a new message.
|
||||
|
||||
### Templates
|
||||
|
||||
- **Sync:** a WhatsApp Admin presses "Sync templates". It also runs nightly. The sync pulls `GET /{waba_id}/message_templates?status=APPROVED`, and the body text and `{{n}}` count come from the BODY component.
|
||||
- **Company:** each company has its own business account, so each company syncs and sees only its own account's templates.
|
||||
- **What we support:** templates with header media or buttons that need parameters are skipped and shown as "not supported yet". Text-only body templates are what go-live needs.
|
||||
|
||||
### Media
|
||||
|
||||
- An incoming media message stores `media_id`, the mime type and the filename. Nothing is downloaded at webhook time.
|
||||
- When someone opens it, `GET /api/admin/whatsapp/media/{messageUuid}` checks company access, gets the short-lived URL from Graph (`GET /{media_id}`), and streams the bytes with the right content type. Images and stickers show inline, documents and audio as download or play, and a location as a map link.
|
||||
- Ceiling: Meta keeps media for about 30 days, after which the item shows "Media expired". Upgrade path: copy to object storage on receipt.
|
||||
|
||||
### Access, roles and company scoping
|
||||
|
||||
- New modules:
|
||||
- `BO_WHATSAPP`: the inbox. The user sees and replies only in conversations they own, sends templates, and starts chats with leads.
|
||||
- `BO_WHATSAPP_ADMIN`: sees every conversation of their company, plus the unassigned queue. Can read, reply in and reassign any of them (including to themselves), return a chat to automatic, and sync templates.
|
||||
- Super admins see every company's conversations, with a company filter like the other screens.
|
||||
- Every query is scoped to the caller's company, failing closed as the company-scoping spec requires.
|
||||
- The owner field accepts only active users of that company who hold `BO_WHATSAPP`.
|
||||
|
||||
### Portal
|
||||
|
||||
- **Inbox (`/whatsapp`, in the sidebar's Leads section, with an unread badge):**
|
||||
- Two panes on desktop, list then thread on phones.
|
||||
- List tabs: Mine, Unassigned (admin), All (admin), plus search by name or number.
|
||||
- Each row shows the name or number, the lead's name when linked, the last message preview and time, an unread dot, and the owner (admin view).
|
||||
- **Thread:**
|
||||
- The header shows the contact, a link to the lead, the owner with a Reassign control (admin), and the 24-hour window state ("Replies open for 3 h" or "Window closed: send a template").
|
||||
- Messages appear as bubbles with time and ticks (sent, delivered, read, failed with reason). Media is shown as described above.
|
||||
- **Composer:** a text box, and a "Template" button that opens a picker. The picker shows the template preview with fields for each `{{n}}`. Only the template button shows when the window is closed.
|
||||
- **Polling:** the list every 30 s and an open thread every 10 s, paused when the tab is hidden. That's my call, the same as babyboo, which avoids new infrastructure. The ceiling is minute-scale latency at polling cost; the upgrade path is server-sent events.
|
||||
- **Entry points:** a WhatsApp button on lead and event lead rows (phone cards included) when the lead has a mobile and the user holds `BO_WHATSAPP`.
|
||||
|
||||
### Audit and privacy
|
||||
|
||||
- Audit entries:
|
||||
- a template or text sent (conversation uuid, template name, not the body);
|
||||
- a reassignment (from, to);
|
||||
- a template sync.
|
||||
- Logging: never log bodies, phone numbers, media, tokens or signatures. The gateway redactor masks the webhook path's query and body.
|
||||
- Messages are personal data under the same privacy notice: WhatsApp is listed as a contact channel in both languages. They are kept while the lead is kept. A retention policy is a later item.
|
||||
|
||||
### Local development and tests
|
||||
|
||||
- A small `whatsapp-mock` container in `local/docker-compose.yml`. It is a tiny HTTP server, test-only, and its image is never released. It stands in for Graph:
|
||||
- it accepts `/messages` and returns fake `wamid`s;
|
||||
- it serves a fixed template list and a media URL and bytes;
|
||||
- it has a `/simulate/inbound` endpoint that signs and posts a webhook payload to mobile-api, the same way Meta does.
|
||||
- `WHATSAPP_GRAPH_BASE_URL` points at the mock locally. This makes the whole loop testable, including Playwright and the manual e2e, with no Meta account.
|
||||
- Backend tests cover:
|
||||
- the signature check (valid, invalid, missing);
|
||||
- number-to-company mapping and the unknown number;
|
||||
- idempotent `wamid`;
|
||||
- status ordering;
|
||||
- the ownership recompute table;
|
||||
- manual owner stickiness;
|
||||
- the deactivated owner;
|
||||
- the 24-hour window;
|
||||
- template parameter validation;
|
||||
- company isolation.
|
||||
|
||||
## Constraints
|
||||
|
||||
- Java 21, Spring Boot 3.2 like the other services. No new dependency beyond what core-libs and the JDK give: `java.net.http` or RestTemplate, and `javax.crypto.Mac` for HMAC.
|
||||
- Go-live is 2027-01-15. Meta business verification is done and the account is ready (owner, 2026-12-02). Only the secrets wait: they are deployed to Kubernetes after the move to solvway, so real Meta delivery is first tested then. The release notes must list the Meta-side setup:
|
||||
- the webhook URL and verify token;
|
||||
- subscribing to `messages`;
|
||||
- approving the templates.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
The exact package layout, the DTO shapes, the portal component split, bubble styling within DESIGN.md, and polling intervals within ±50%.
|
||||
Reference in new issue
Block a user