The webhook answered 200 whatever happened downstream, and Meta only redelivers on a non-2xx answer, so an event that reached a stopped service, or a just-started one that had not resolved its companies yet, was lost. mobile-api now answers 503 on an unreachable service or a 5xx (a 4xx refusal still gets 200), and the service answers 503 for a configured number whose company is not resolved yet. wamid uniqueness makes the redelivery safe. Owner decision 2026-12-02; design D3 and the spec updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
9.1 KiB
Context
The product design is docs/superpowers/specs/2026-12-02-whatsapp-inbox-design.md, with the owner's decisions of 2026-11-26, 2026-11-30 and 2026-12-02. Facts from the codebase:
- mobile-api is the public edge. It calls services through the gateway with
RestTemplateCustomUtilandRestApi*ServiceConstants, enforces modules inAdminModuleAccess, records audit throughAuditChanges, and limits by IP throughPublicRegistrationService.limit. - Leads live in the counter service:
lead.mobile_e164holds the mobile with a leading+;event_lead.salesperson_user_idholds the salesperson;LeadRepositoryalready computes the "latest salesperson".
- The gateway routes by
Path=/<service>/**(solvway-api-gateway/src/main/resources/application.yml). - Logging:
LogRedactormasks token path segments. - Async work:
@Scheduledexists in the counter service. There is no queue broker. - Pattern source: babyboo's member messaging, with conversations, messages and read markers, and polling at 30 s for the list and 15 s for a thread.
Goals / Non-Goals
Goals: everything in the spec delta.
Non-goals:
- broadcasts;
- sending media;
- WhatsApp event invitations;
- chatbots;
- several numbers per company;
- managing templates in Co-Lite;
- push or websockets;
- 360dialog.
Decisions
-
The service.
solvway-services-whatsappis cloned fromsolvway-services-email's layout (pom parent, Dockerfile,application.ymlwith${...}env, port 80). Packagecom.solvway.services.whatsapp, withcontroller,service,repository,model,dto,meta(the Graph client) andjob. It uses JPA on schemaservice-whatsapp. The gateway route isPath=/whatsapp/**. Compose adds the service andwhatsapp-mock. -
Settings.
WhatsAppSettingsbindsWHATSAPP_COMPANIESand, for each code,WHATSAPP_<CODE>_PHONE_NUMBER_ID,_WABA_ID,_ACCESS_TOKENand_APP_SECRET, plusWHATSAPP_VERIFY_TOKENandWHATSAPP_GRAPH_BASE_URL. Settings are resolved to a company id at startup through the system service's company lookup by code, and a code with no matching company is skipped. mobile-api needs the app secrets and the verify token for the webhook, so it binds the same variables, with no duplicate files: both read the environment. -
Webhook path.
- mobile-api,
POST /api/public/whatsapp/webhook:- reads the body as raw bytes (
@RequestBody byte[]) before any JSON binding; - computes the HMAC-SHA256 under each configured app secret and compares it in constant time (
MessageDigest.isEqual); - collects the matching company codes, answering 401 when none match;
- parses the body and forwards
{ matchedCompanyCodes, payload }to the service at/whatsapp/webhook/ingest; - answers 503 when the service cannot take the event (unreachable or 5xx), so Meta redelivers it (for up to 7 days); the service ignores a
wamidit already holds, so a redelivery is safe. A refusal from the service (4xx) still answers 200, since a redelivery cannot succeed. It logs the status code only. (Owner decision 2026-12-02: the first version answered 200 on any service error, and that loses the event, because Meta redelivers only on a non-2xx answer.)
- reads the body as raw bytes (
- The service accepts each
entry.changes[].valueonly when itsmetadata.phone_number_idbelongs to one of the matched companies. For a configured number whose company it has not resolved yet (the system service was unreachable), it answers 503 so that Meta redelivers. - The webhook is exempt from the API key and admin JWT, like the other public routes, and rate-limited per IP at a high ceiling.
- mobile-api,
-
Idempotency and ordering.
wa_message.wamidis unique, so an insert that conflicts is ignored. Status updates follow the rankpending 0 < sent 1 < delivered 2 < read 3, andfailedalways applies. -
Lead lookup. A new counter endpoint,
GET /counter/lead/whatsappContact?companyId&mobileE164, returns{ leadUuid, name, latestSalespersonUserId }, taking the newest lead for that mobile. It reuses the latest-salesperson query fromLeadRepository. -
Ownership recompute is one method,
OwnershipService.recompute(conversation). It calls the lookup, then asks mobile-api's internal user check whether a user id is active, belongs to the company and holdsBO_WHATSAPP, through a system-service endpoint that returns the user's modules. It runs:- when a conversation is created;
- on "Return to automatic";
- when the counter's event-lead save path calls
POST /whatsapp/ownership/leadChanged {companyId, mobileE164}. The call is best-effort: a failure is logged without the mobile; - nightly over all automatic conversations.
-
Losing access. mobile-api's
AdminUserServicesave path callsPOST /whatsapp/ownership/userChanged {userId}after a save that disables a user or changes their roles. The service then unassigns every conversation whose owner is no longer active withBO_WHATSAPPand clearsowner_manual. The nightly job repeats this. -
Sending.
MetaClient:- posts
/{phone_number_id}/messageswith the company's bearer token, sending a text body ortemplate{name, language{code}, components[{type: body, parameters: [{type: text, text}]}]}; - for templates, uses
GET /{waba_id}/message_templates?status=APPROVED&limit=200(following paging); - for media, uses
GET /{media_id}, then a GET of the returned URL with the bearer token.
Timeouts are 10 s. Errors map to stored
failedwith Meta'serror.codeanderror.title(an expired token included). - posts
-
Admin API in mobile-api (
/api/admin/whatsapp/**, modules checked throughAdminModuleAccess, company resolved as on every other admin endpoint):GET conversations?tab=mine|unassigned|all&q=&page=GET conversations/{uuid}, which returns messages, newest last, paged backwardsPOST conversations/{uuid}/messages, taking{text}or{template, params[]}POST conversations/{uuid}/readPOST conversations/{uuid}/assign, taking{userId}or{automatic: true}POST start, taking{leadUuid}or{eventLeadUuid}GET templatesandPOST templates/syncGET media/{messageUuid}, which streamsGET unread-countGET assignees, listing active users of the company withBO_WHATSAPP
-
Portal.
app/whatsapp/page.tsxholds the list and thread, polling at 30 s and 10 s and pausing whiledocument.hidden.routeModulesmaps/whatsapptoBO_WHATSAPP.- The sidebar map adds
BO_WHATSAPPto the Leads section, with iconMessageCircleadded to the icon map. The badge comes fromunread-count. - WhatsApp buttons go on the leads list and event leads rows and phone cards.
- Components use the existing ui kit and DESIGN.md tokens. Bubbles: inbound on
bg-muted, outbound onbg-accent.
-
Mock.
local/whatsapp-mockis a minimal Node or JDK-only HTTP server; the builder picks whichever needs no new dependency in the repo.- It serves the Graph endpoints above with canned data and returns
wamid.MOCK…ids. POST /simulate/inbound {companyCode, from, text|type}builds a Meta-shaped payload, signs it with that company's app secret from its env, and posts it to mobile-api's webhook.- It stays out of release packaging. The
release-packagingworkflow builds only the services listed there.
- It serves the Graph endpoints above with canned data and returns
-
Audit. mobile-api's
AuditChangesrecords send (conversation uuid and template name), assign (from and to user) and sync. The webhook is not audited per message: it is volume, not an admin write. -
Redaction.
LogRedactormaskshub.verify_tokenandhub.challengequery values on the webhook path.- The gateway body logger is already off (
stop-gateway-body-logging). - The service logs ids and counts only.
Risks / Trade-offs
- Polling latency is up to 30 s for the list. Acceptable for a sales inbox.
ponytail:note on the poll; upgrade with server-sent events. - Media kept only about 30 days by Meta.
ponytail:note on the proxy; upgrade by copying to object storage on receipt. - Best-effort ownership calls from counter and mobile-api can miss. The nightly job repairs them, and the worst case is a chat with a stale owner for a day.
- Real Meta is not testable until the secrets are deployed after the move to solvway. The mock reproduces Meta's documented payloads. The first real message is a release step in
docs/deployment.md. - Two Meta apps: if the companies use different Meta apps, one webhook URL is subscribed in both. The per-company secret matching handles it.
Migration Plan
- Run
sql/01-whatsapp-schema.sql(schema, tables) andsql/02-whatsapp-modules.sql(modulesBO_WHATSAPPandBO_WHATSAPP_ADMIN, granted to no role; super admins grant them under Roles). - Deploy the service, mobile-api, counter, gateway and portal.
- Set the environment per company.
- In Meta, set the webhook URL
https://<public mobile-api host>/api/public/whatsapp/webhookand the verify token, and subscribe tomessages. - Sync templates.
Rollback: sql/99-rollback.sql drops the schema and the modules. Redeploy the previous images.