Files
co-lite/openspec/changes/add-whatsapp-inbox/design.md
T
ngqileandClaude Opus 5.5 3e610e0f88 fix(whatsapp): answer 503 when the inbox cannot take an event, so Meta redelivers
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
2026-12-02 11:49:17 +08:00

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 RestTemplateCustomUtil and RestApi*ServiceConstants, enforces modules in AdminModuleAccess, records audit through AuditChanges, and limits by IP through PublicRegistrationService.limit.
  • Leads live in the counter service:
    • lead.mobile_e164 holds the mobile with a leading +;
    • event_lead.salesperson_user_id holds the salesperson;
    • LeadRepository already computes the "latest salesperson".
  • The gateway routes by Path=/<service>/** (solvway-api-gateway/src/main/resources/application.yml).
  • Logging: LogRedactor masks token path segments.
  • Async work: @Scheduled exists 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

  1. The service. solvway-services-whatsapp is cloned from solvway-services-email's layout (pom parent, Dockerfile, application.yml with ${...} env, port 80). Package com.solvway.services.whatsapp, with controller, service, repository, model, dto, meta (the Graph client) and job. It uses JPA on schema service-whatsapp. The gateway route is Path=/whatsapp/**. Compose adds the service and whatsapp-mock.

  2. Settings. WhatsAppSettings binds WHATSAPP_COMPANIES and, for each code, WHATSAPP_<CODE>_PHONE_NUMBER_ID, _WABA_ID, _ACCESS_TOKEN and _APP_SECRET, plus WHATSAPP_VERIFY_TOKEN and WHATSAPP_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.

  3. Webhook path.

    1. 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 wamid it 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.)
    2. The service accepts each entry.changes[].value only when its metadata.phone_number_id belongs 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.
    3. 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.
  4. Idempotency and ordering. wa_message.wamid is unique, so an insert that conflicts is ignored. Status updates follow the rank pending 0 < sent 1 < delivered 2 < read 3, and failed always applies.

  5. 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 from LeadRepository.

  6. 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 holds BO_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.
  7. Losing access. mobile-api's AdminUserService save path calls POST /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 with BO_WHATSAPP and clears owner_manual. The nightly job repeats this.

  8. Sending. MetaClient:

    • posts /{phone_number_id}/messages with the company's bearer token, sending a text body or template{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 failed with Meta's error.code and error.title (an expired token included).

  9. Admin API in mobile-api (/api/admin/whatsapp/**, modules checked through AdminModuleAccess, 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 backwards
    • POST conversations/{uuid}/messages, taking {text} or {template, params[]}
    • POST conversations/{uuid}/read
    • POST conversations/{uuid}/assign, taking {userId} or {automatic: true}
    • POST start, taking {leadUuid} or {eventLeadUuid}
    • GET templates and POST templates/sync
    • GET media/{messageUuid}, which streams
    • GET unread-count
    • GET assignees, listing active users of the company with BO_WHATSAPP
  10. Portal.

    • app/whatsapp/page.tsx holds the list and thread, polling at 30 s and 10 s and pausing while document.hidden.
    • routeModules maps /whatsapp to BO_WHATSAPP.
    • The sidebar map adds BO_WHATSAPP to the Leads section, with icon MessageCircle added to the icon map. The badge comes from unread-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 on bg-accent.
  11. Mock. local/whatsapp-mock is 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-packaging workflow builds only the services listed there.
  12. Audit. mobile-api's AuditChanges records 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.

  13. Redaction.

    • LogRedactor masks hub.verify_token and hub.challenge query 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

  1. Run sql/01-whatsapp-schema.sql (schema, tables) and sql/02-whatsapp-modules.sql (modules BO_WHATSAPP and BO_WHATSAPP_ADMIN, granted to no role; super admins grant them under Roles).
  2. Deploy the service, mobile-api, counter, gateway and portal.
  3. Set the environment per company.
  4. In Meta, set the webhook URL https://<public mobile-api host>/api/public/whatsapp/webhook and the verify token, and subscribe to messages.
  5. Sync templates.

Rollback: sql/99-rollback.sql drops the schema and the modules. Redeploy the previous images.